react-semaphor 0.1.136 → 0.1.137

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.
Files changed (24) hide show
  1. package/dist/chunks/{dashboard-controls-C35Jz1fx.js → dashboard-controls-CxQYnkax.js} +3 -3
  2. package/dist/chunks/{dashboard-controls-Dxx6-zR2.js → dashboard-controls-hLb7d4n_.js} +1 -1
  3. package/dist/chunks/{dashboard-export-dialog-BDv_HVGR.js → dashboard-export-dialog-JVjnwTLv.js} +1 -1
  4. package/dist/chunks/{dashboard-export-dialog-DYKctzwH.js → dashboard-export-dialog-XQQow9XX.js} +3 -3
  5. package/dist/chunks/{dashboard-json-DbfqDpJH.js → dashboard-json-CSK4231d.js} +1 -1
  6. package/dist/chunks/{dashboard-json-DizAEdr3.js → dashboard-json-W8a-T1U3.js} +1 -1
  7. package/dist/chunks/{edit-dashboard-visual-CovPTSDH.js → edit-dashboard-visual-BGH8yv2A.js} +455 -448
  8. package/dist/chunks/edit-dashboard-visual-C8ZQJfdk.js +200 -0
  9. package/dist/chunks/{editor-action-buttons-CPJ-_aGj.js → editor-action-buttons-BmBNyNxY.js} +1 -1
  10. package/dist/chunks/{editor-action-buttons-D-k-U0HS.js → editor-action-buttons-zUsKxZMu.js} +2 -2
  11. package/dist/chunks/{index-baj-eF5k.js → index-MdpD3qo9.js} +3 -3
  12. package/dist/chunks/{index-Bqqna9eB.js → index-NjRBKdZ2.js} +23 -11
  13. package/dist/chunks/{resource-management-panel-BJfU9o5-.js → resource-management-panel-C_q7Ilyi.js} +2 -2
  14. package/dist/chunks/{resource-management-panel-CU-aO9tG.js → resource-management-panel-Di5Mg69T.js} +1 -1
  15. package/dist/chunks/{use-visual-utils-DP_QQo_Q.js → use-visual-utils-CmKlc7fo.js} +1 -1
  16. package/dist/chunks/{use-visual-utils-r0hON58l.js → use-visual-utils-oliZ5xcR.js} +1 -1
  17. package/dist/dashboard/index.cjs +1 -1
  18. package/dist/dashboard/index.js +1 -1
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +4 -4
  21. package/dist/surfboard/index.cjs +1 -1
  22. package/dist/surfboard/index.js +1 -1
  23. package/package.json +1 -1
  24. package/dist/chunks/edit-dashboard-visual-AgjWs5LG.js +0 -200
@@ -970,7 +970,7 @@ ${(e*100).toLocaleString()}%`}}},scales:{_index_:{display:!1,padding:10,grid:{di
970
970
  `),"","You can apply a few solutions:",['Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".',"Render a single element as the child so that we can forward the props onto that element."].map(h=>` - ${h}`).join(`
971
971
  `)].join(`
972
972
  `))}else{let h=d.props,m=h==null?void 0:h.className,p=typeof m=="function"?(...x)=>K4(m(...x),l.className):K4(m,l.className),g=p?{className:p}:{},b=pK(d.props,ju(vj(l,["ref"])));for(let x in f)x in b&&delete f[x];return j.cloneElement(d,Object.assign({},b,f,u,{ref:s($Oe(d),u.ref)},g))}return j.createElement(o,Object.assign({},vj(l,["ref"]),o!==j.Fragment&&u,o!==j.Fragment&&f),d)}function OOe(){let e=j.useRef([]),t=j.useCallback(n=>{for(let r of e.current)r!=null&&(typeof r=="function"?r(n):r.current=n)},[]);return(...n)=>{if(!n.every(r=>r==null))return e.current=n,t}}function FOe(...e){return e.every(t=>t==null)?void 0:t=>{for(let n of e)n!=null&&(typeof n=="function"?n(t):n.current=t)}}function pK(...e){if(e.length===0)return{};if(e.length===1)return e[0];let t={},n={};for(let r of e)for(let s in r)s.startsWith("on")&&typeof r[s]=="function"?(n[s]!=null||(n[s]=[]),n[s].push(r[s])):t[s]=r[s];if(t.disabled||t["aria-disabled"])for(let r in n)/^(on(?:Click|Pointer|Mouse|Key)(?:Down|Up|Press)?)$/.test(r)&&(n[r]=[s=>{var o;return(o=s==null?void 0:s.preventDefault)==null?void 0:o.call(s)}]);for(let r in n)Object.assign(t,{[r](s,...o){let i=n[r];for(let a of i){if((s instanceof Event||(s==null?void 0:s.nativeEvent)instanceof Event)&&s.defaultPrevented)return;a(s,...o)}}});return t}function yR(...e){if(e.length===0)return{};if(e.length===1)return e[0];let t={},n={};for(let r of e)for(let s in r)s.startsWith("on")&&typeof r[s]=="function"?(n[s]!=null||(n[s]=[]),n[s].push(r[s])):t[s]=r[s];for(let r in n)Object.assign(t,{[r](...s){let o=n[r];for(let i of o)i==null||i(...s)}});return t}function $i(e){var t;return Object.assign(j.forwardRef(e),{displayName:(t=e.displayName)!=null?t:e.name})}function ju(e){let t=Object.assign({},e);for(let n in t)t[n]===void 0&&delete t[n];return t}function vj(e,t=[]){let n=Object.assign({},e);for(let r of t)r in n&&delete n[r];return n}function $Oe(e){return j.version.split(".")[0]>="19"?e.props.ref:e.ref}function LOe(e,t,n){let[r,s]=j.useState(n),o=e!==void 0,i=j.useRef(o),a=j.useRef(!1),l=j.useRef(!1);return o&&!i.current&&!a.current?(a.current=!0,i.current=o,console.error("A component is changing from uncontrolled to controlled. This may be caused by the value changing from undefined to a defined value, which should not happen.")):!o&&i.current&&!l.current&&(l.current=!0,i.current=o,console.error("A component is changing from controlled to uncontrolled. This may be caused by the value changing from a defined value to undefined, which should not happen.")),[o?e:r,Ct(u=>(o||s(u),t==null?void 0:t(u)))]}function zOe(e){let[t]=j.useState(e);return t}function gK(e={},t=null,n=[]){for(let[r,s]of Object.entries(e))xK(n,bK(t,r),s);return n}function bK(e,t){return e?e+"["+t+"]":t}function xK(e,t,n){if(Array.isArray(n))for(let[r,s]of n.entries())xK(e,bK(t,r.toString()),s);else n instanceof Date?e.push([t,n.toISOString()]):typeof n=="boolean"?e.push([t,n?"1":"0"]):typeof n=="string"?e.push([t,n]):typeof n=="number"?e.push([t,`${n}`]):n==null?e.push([t,""]):gK(n,t,e)}let BOe="span";var vR=(e=>(e[e.None=1]="None",e[e.Focusable=2]="Focusable",e[e.Hidden=4]="Hidden",e))(vR||{});function VOe(e,t){var n;let{features:r=1,...s}=e,o={ref:t,"aria-hidden":(r&2)===2?!0:(n=s["aria-hidden"])!=null?n:void 0,hidden:(r&4)===4?!0:void 0,style:{position:"fixed",top:1,left:1,width:1,height:0,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0",...(r&4)===4&&(r&2)!==2&&{display:"none"}}};return Fi()({ourProps:o,theirProps:s,slot:{},defaultTag:BOe,name:"Hidden"})}let yK=$i(VOe),HOe=j.createContext(null);function UOe({children:e}){let t=j.useContext(HOe);if(!t)return j.createElement(j.Fragment,null,e);let{target:n}=t;return n?Pn.createPortal(j.createElement(j.Fragment,null,e),n):null}function WOe({data:e,form:t,disabled:n,onReset:r,overrides:s}){let[o,i]=j.useState(null),a=vx();return j.useEffect(()=>{if(r&&o)return a.addEventListener(o,"reset",r)},[o,t,r]),j.createElement(UOe,null,j.createElement(qOe,{setForm:i,formId:t}),gK(e).map(([l,u])=>j.createElement(yK,{features:vR.Hidden,...ju({key:l,as:"input",type:"hidden",hidden:!0,readOnly:!0,form:t,disabled:n,name:l,value:u,...s})})))}function qOe({setForm:e,formId:t}){return j.useEffect(()=>{if(t){let n=document.getElementById(t);n&&e(n)}},[e,t]),t?null:j.createElement(yK,{features:vR.Hidden,as:"input",type:"hidden",hidden:!0,readOnly:!0,ref:n=>{if(!n)return;let r=n.closest("form");r&&e(r)}})}let YOe=j.createContext(void 0);function vK(){return j.useContext(YOe)}function GOe(e){let t=e.parentElement,n=null;for(;t&&!(t instanceof HTMLFieldSetElement);)t instanceof HTMLLegendElement&&(n=t),t=t.parentElement;let r=(t==null?void 0:t.getAttribute("disabled"))==="";return r&&KOe(n)?!1:r}function KOe(e){if(!e)return!1;let t=e.previousElementSibling;for(;t!==null;){if(t instanceof HTMLLegendElement)return!1;t=t.previousElementSibling}return!0}let wK=Symbol();function ZOe(e,t=!0){return Object.assign(e,{[wK]:t})}function kl(...e){let t=j.useRef(e);j.useEffect(()=>{t.current=e},[e]);let n=Ct(r=>{for(let s of t.current)s!=null&&(typeof s=="function"?s(r):s.current=r)});return e.every(r=>r==null||(r==null?void 0:r[wK]))?void 0:n}let wR=j.createContext(null);wR.displayName="DescriptionContext";function SK(){let e=j.useContext(wR);if(e===null){let t=new Error("You used a <Description /> component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(t,SK),t}return e}function XOe(){var e,t;return(t=(e=j.useContext(wR))==null?void 0:e.value)!=null?t:void 0}let QOe="p";function JOe(e,t){let n=j.useId(),r=xR(),{id:s=`headlessui-description-${n}`,...o}=e,i=SK(),a=kl(t);Gn(()=>i.register(s),[s,i.register]);let l=r||!1,u=j.useMemo(()=>({...i.slot,disabled:l}),[i.slot,l]),d={ref:a,...i.props,id:s};return Fi()({ourProps:d,theirProps:o,slot:u,defaultTag:QOe,name:i.name||"Description"})}let eFe=$i(JOe);Object.assign(eFe,{});var ys=(e=>(e.Space=" ",e.Enter="Enter",e.Escape="Escape",e.Backspace="Backspace",e.Delete="Delete",e.ArrowLeft="ArrowLeft",e.ArrowUp="ArrowUp",e.ArrowRight="ArrowRight",e.ArrowDown="ArrowDown",e.Home="Home",e.End="End",e.PageUp="PageUp",e.PageDown="PageDown",e.Tab="Tab",e))(ys||{});let xS=j.createContext(null);xS.displayName="LabelContext";function CK(){let e=j.useContext(xS);if(e===null){let t=new Error("You used a <Label /> component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(t,CK),t}return e}function yS(e){var t,n,r;let s=(n=(t=j.useContext(xS))==null?void 0:t.value)!=null?n:void 0;return((r=e==null?void 0:e.length)!=null?r:0)>0?[s,...e].filter(Boolean).join(" "):s}function tFe({inherit:e=!1}={}){let t=yS(),[n,r]=j.useState([]),s=e?[t,...n].filter(Boolean):n;return[s.length>0?s.join(" "):void 0,j.useMemo(()=>function(o){let i=Ct(l=>(r(u=>[...u,l]),()=>r(u=>{let d=u.slice(),f=d.indexOf(l);return f!==-1&&d.splice(f,1),d}))),a=j.useMemo(()=>({register:i,slot:o.slot,name:o.name,props:o.props,value:o.value}),[i,o.slot,o.name,o.props,o.value]);return j.createElement(xS.Provider,{value:a},o.children)},[r])]}let nFe="label";function rFe(e,t){var n;let r=j.useId(),s=CK(),o=vK(),i=xR(),{id:a=`headlessui-label-${r}`,htmlFor:l=o??((n=s.props)==null?void 0:n.htmlFor),passive:u=!1,...d}=e,f=kl(t);Gn(()=>s.register(a),[a,s.register]);let h=Ct(b=>{let x=b.currentTarget;if(x instanceof HTMLLabelElement&&b.preventDefault(),s.props&&"onClick"in s.props&&typeof s.props.onClick=="function"&&s.props.onClick(b),x instanceof HTMLLabelElement){let y=document.getElementById(x.htmlFor);if(y){let v=y.getAttribute("disabled");if(v==="true"||v==="")return;let w=y.getAttribute("aria-disabled");if(w==="true"||w==="")return;(y instanceof HTMLInputElement&&(y.type==="radio"||y.type==="checkbox")||y.role==="radio"||y.role==="checkbox"||y.role==="switch")&&y.click(),y.focus({preventScroll:!0})}}}),m=i||!1,p=j.useMemo(()=>({...s.slot,disabled:m}),[s.slot,m]),g={ref:f,...s.props,id:a,htmlFor:l,onClick:h};return u&&("onClick"in g&&(delete g.htmlFor,delete g.onClick),"onClick"in d&&delete d.onClick),Fi()({ourProps:g,theirProps:d,slot:p,defaultTag:l?nFe:"div",name:s.name||"Label"})}let sFe=$i(rFe),oFe=Object.assign(sFe,{});function iFe(e,t){return e!==null&&t!==null&&typeof e=="object"&&typeof t=="object"&&"id"in e&&"id"in t?e.id===t.id:e===t}function aFe(e=iFe){return j.useCallback((t,n)=>{if(typeof e=="string"){let r=e;return(t==null?void 0:t[r])===(n==null?void 0:n[r])}return e(t,n)},[e])}function lFe(e){if(e===null)return{width:0,height:0};let{width:t,height:n}=e.getBoundingClientRect();return{width:t,height:n}}function Z4(e,t=!1){let[n,r]=j.useReducer(()=>({}),{}),s=j.useMemo(()=>lFe(e),[e,n]);return Gn(()=>{if(!e)return;let o=new ResizeObserver(r);return o.observe(e),()=>{o.disconnect()}},[e]),t?{width:`${s.width}px`,height:`${s.height}px`}:s}let cFe=class extends Map{constructor(t){super(),this.factory=t}get(t){let n=super.get(t);return n===void 0&&(n=this.factory(t),this.set(t,n)),n}};function NK(e,t){let n=e(),r=new Set;return{getSnapshot(){return n},subscribe(s){return r.add(s),()=>r.delete(s)},dispatch(s,...o){let i=t[s].call(n,...o);i&&(n=i,r.forEach(a=>a()))}}}function jK(e){return j.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}let uFe=new cFe(()=>NK(()=>[],{ADD(e){return this.includes(e)?this:[...this,e]},REMOVE(e){let t=this.indexOf(e);if(t===-1)return this;let n=this.slice();return n.splice(t,1),n}}));function SR(e,t){let n=uFe.get(t),r=j.useId(),s=jK(n);if(Gn(()=>{if(e)return n.dispatch("ADD",r),()=>n.dispatch("REMOVE",r)},[n,e]),!e)return!1;let o=s.indexOf(r),i=s.length;return o===-1&&(o=i,i+=1),o===i-1}let ME=new Map,pg=new Map;function X4(e){var t;let n=(t=pg.get(e))!=null?t:0;return pg.set(e,n+1),n!==0?()=>Q4(e):(ME.set(e,{"aria-hidden":e.getAttribute("aria-hidden"),inert:e.inert}),e.setAttribute("aria-hidden","true"),e.inert=!0,()=>Q4(e))}function Q4(e){var t;let n=(t=pg.get(e))!=null?t:1;if(n===1?pg.delete(e):pg.set(e,n-1),n!==1)return;let r=ME.get(e);r&&(r["aria-hidden"]===null?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",r["aria-hidden"]),e.inert=r.inert,ME.delete(e))}function dFe(e,{allowed:t,disallowed:n}={}){let r=SR(e,"inert-others");Gn(()=>{var s,o;if(!r)return;let i=xa();for(let l of(s=n==null?void 0:n())!=null?s:[])l&&i.add(X4(l));let a=(o=t==null?void 0:t())!=null?o:[];for(let l of a){if(!l)continue;let u=yx(l);if(!u)continue;let d=l.parentElement;for(;d&&d!==u.body;){for(let f of d.children)a.some(h=>f.contains(h))||i.add(X4(f));d=d.parentElement}}return i.dispose},[r,t,n])}function fFe(e,t,n){let r=af(s=>{let o=s.getBoundingClientRect();o.x===0&&o.y===0&&o.width===0&&o.height===0&&n()});j.useEffect(()=>{if(!e)return;let s=t===null?null:t instanceof HTMLElement?t:t.current;if(!s)return;let o=xa();if(typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>r.current(s));i.observe(s),o.add(()=>i.disconnect())}if(typeof IntersectionObserver<"u"){let i=new IntersectionObserver(()=>r.current(s));i.observe(s),o.add(()=>i.disconnect())}return()=>o.dispose()},[t,r,e])}let TE=["[contentEditable=true]","[tabindex]","a[href]","area[href]","button:not([disabled])","iframe","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].map(e=>`${e}:not([tabindex='-1'])`).join(",");var hFe=(e=>(e[e.First=1]="First",e[e.Previous=2]="Previous",e[e.Next=4]="Next",e[e.Last=8]="Last",e[e.WrapAround=16]="WrapAround",e[e.NoScroll=32]="NoScroll",e[e.AutoFocus=64]="AutoFocus",e))(hFe||{}),mFe=(e=>(e[e.Error=0]="Error",e[e.Overflow=1]="Overflow",e[e.Success=2]="Success",e[e.Underflow=3]="Underflow",e))(mFe||{}),pFe=(e=>(e[e.Previous=-1]="Previous",e[e.Next=1]="Next",e))(pFe||{}),kK=(e=>(e[e.Strict=0]="Strict",e[e.Loose=1]="Loose",e))(kK||{});function gFe(e,t=0){var n;return e===((n=yx(e))==null?void 0:n.body)?!1:fl(t,{0(){return e.matches(TE)},1(){let r=e;for(;r!==null;){if(r.matches(TE))return!0;r=r.parentElement}return!1}})}var bFe=(e=>(e[e.Keyboard=0]="Keyboard",e[e.Mouse=1]="Mouse",e))(bFe||{});typeof window<"u"&&typeof document<"u"&&(document.addEventListener("keydown",e=>{e.metaKey||e.altKey||e.ctrlKey||(document.documentElement.dataset.headlessuiFocusVisible="")},!0),document.addEventListener("click",e=>{e.detail===1?delete document.documentElement.dataset.headlessuiFocusVisible:e.detail===0&&(document.documentElement.dataset.headlessuiFocusVisible="")},!0));function xFe(e,t=n=>n){return e.slice().sort((n,r)=>{let s=t(n),o=t(r);if(s===null||o===null)return 0;let i=s.compareDocumentPosition(o);return i&Node.DOCUMENT_POSITION_FOLLOWING?-1:i&Node.DOCUMENT_POSITION_PRECEDING?1:0})}function EK(){return/iPhone/gi.test(window.navigator.platform)||/Mac/gi.test(window.navigator.platform)&&window.navigator.maxTouchPoints>0}function yFe(){return/Android/gi.test(window.navigator.userAgent)}function _K(){return EK()||yFe()}function wp(e,t,n,r){let s=af(n);j.useEffect(()=>{if(!e)return;function o(i){s.current(i)}return document.addEventListener(t,o,r),()=>document.removeEventListener(t,o,r)},[e,t,r])}function vFe(e,t,n,r){let s=af(n);j.useEffect(()=>{if(!e)return;function o(i){s.current(i)}return window.addEventListener(t,o,r),()=>window.removeEventListener(t,o,r)},[e,t,r])}const J4=30;function wFe(e,t,n){let r=SR(e,"outside-click"),s=af(n),o=j.useCallback(function(l,u){if(l.defaultPrevented)return;let d=u(l);if(d===null||!d.getRootNode().contains(d)||!d.isConnected)return;let f=function h(m){return typeof m=="function"?h(m()):Array.isArray(m)||m instanceof Set?m:[m]}(t);for(let h of f)if(h!==null&&(h.contains(d)||l.composed&&l.composedPath().includes(h)))return;return!gFe(d,kK.Loose)&&d.tabIndex!==-1&&l.preventDefault(),s.current(l,d)},[s,t]),i=j.useRef(null);wp(r,"pointerdown",l=>{var u,d;i.current=((d=(u=l.composedPath)==null?void 0:u.call(l))==null?void 0:d[0])||l.target},!0),wp(r,"mousedown",l=>{var u,d;i.current=((d=(u=l.composedPath)==null?void 0:u.call(l))==null?void 0:d[0])||l.target},!0),wp(r,"click",l=>{_K()||i.current&&(o(l,()=>i.current),i.current=null)},!0);let a=j.useRef({x:0,y:0});wp(r,"touchstart",l=>{a.current.x=l.touches[0].clientX,a.current.y=l.touches[0].clientY},!0),wp(r,"touchend",l=>{let u={x:l.changedTouches[0].clientX,y:l.changedTouches[0].clientY};if(!(Math.abs(u.x-a.current.x)>=J4||Math.abs(u.y-a.current.y)>=J4))return o(l,()=>l.target instanceof HTMLElement?l.target:null)},!0),vFe(r,"blur",l=>o(l,()=>window.document.activeElement instanceof HTMLIFrameElement?window.document.activeElement:null),!0)}function vS(...e){return j.useMemo(()=>yx(...e),[...e])}function SFe(e,t,n,r){let s=af(n);j.useEffect(()=>{e=e??window;function o(i){s.current(i)}return e.addEventListener(t,o,r),()=>e.removeEventListener(t,o,r)},[e,t,r])}function DK(e){let t=j.useRef({value:"",selectionStart:null,selectionEnd:null});return SFe(e,"blur",n=>{let r=n.target;r instanceof HTMLInputElement&&(t.current={value:r.value,selectionStart:r.selectionStart,selectionEnd:r.selectionEnd})}),Ct(()=>{if(document.activeElement!==e&&e instanceof HTMLInputElement&&e.isConnected){if(e.focus({preventScroll:!0}),e.value!==t.current.value)e.setSelectionRange(e.value.length,e.value.length);else{let{selectionStart:n,selectionEnd:r}=t.current;n!==null&&r!==null&&e.setSelectionRange(n,r)}t.current={value:"",selectionStart:null,selectionEnd:null}}})}function CFe(e,t){return j.useMemo(()=>{var n;if(e.type)return e.type;let r=(n=e.as)!=null?n:"button";if(typeof r=="string"&&r.toLowerCase()==="button"||(t==null?void 0:t.tagName)==="BUTTON"&&!t.hasAttribute("type"))return"button"},[e.type,e.as,t])}function NFe(){let e;return{before({doc:t}){var n;let r=t.documentElement,s=(n=t.defaultView)!=null?n:window;e=Math.max(0,s.innerWidth-r.clientWidth)},after({doc:t,d:n}){let r=t.documentElement,s=Math.max(0,r.clientWidth-r.offsetWidth),o=Math.max(0,e-s);n.style(r,"paddingRight",`${o}px`)}}}function jFe(){return EK()?{before({doc:e,d:t,meta:n}){function r(s){return n.containers.flatMap(o=>o()).some(o=>o.contains(s))}t.microTask(()=>{var s;if(window.getComputedStyle(e.documentElement).scrollBehavior!=="auto"){let a=xa();a.style(e.documentElement,"scrollBehavior","auto"),t.add(()=>t.microTask(()=>a.dispose()))}let o=(s=window.scrollY)!=null?s:window.pageYOffset,i=null;t.addEventListener(e,"click",a=>{if(a.target instanceof HTMLElement)try{let l=a.target.closest("a");if(!l)return;let{hash:u}=new URL(l.href),d=e.querySelector(u);d&&!r(d)&&(i=d)}catch{}},!0),t.addEventListener(e,"touchstart",a=>{if(a.target instanceof HTMLElement)if(r(a.target)){let l=a.target;for(;l.parentElement&&r(l.parentElement);)l=l.parentElement;t.style(l,"overscrollBehavior","contain")}else t.style(a.target,"touchAction","none")}),t.addEventListener(e,"touchmove",a=>{if(a.target instanceof HTMLElement){if(a.target.tagName==="INPUT")return;if(r(a.target)){let l=a.target;for(;l.parentElement&&l.dataset.headlessuiPortal!==""&&!(l.scrollHeight>l.clientHeight||l.scrollWidth>l.clientWidth);)l=l.parentElement;l.dataset.headlessuiPortal===""&&a.preventDefault()}else a.preventDefault()}},{passive:!1}),t.add(()=>{var a;let l=(a=window.scrollY)!=null?a:window.pageYOffset;o!==l&&window.scrollTo(0,o),i&&i.isConnected&&(i.scrollIntoView({block:"nearest"}),i=null)})})}}:{}}function kFe(){return{before({doc:e,d:t}){t.style(e.documentElement,"overflow","hidden")}}}function EFe(e){let t={};for(let n of e)Object.assign(t,n(t));return t}let Bu=NK(()=>new Map,{PUSH(e,t){var n;let r=(n=this.get(e))!=null?n:{doc:e,count:0,d:xa(),meta:new Set};return r.count++,r.meta.add(t),this.set(e,r),this},POP(e,t){let n=this.get(e);return n&&(n.count--,n.meta.delete(t)),this},SCROLL_PREVENT({doc:e,d:t,meta:n}){let r={doc:e,d:t,meta:EFe(n)},s=[jFe(),NFe(),kFe()];s.forEach(({before:o})=>o==null?void 0:o(r)),s.forEach(({after:o})=>o==null?void 0:o(r))},SCROLL_ALLOW({d:e}){e.dispose()},TEARDOWN({doc:e}){this.delete(e)}});Bu.subscribe(()=>{let e=Bu.getSnapshot(),t=new Map;for(let[n]of e)t.set(n,n.documentElement.style.overflow);for(let n of e.values()){let r=t.get(n.doc)==="hidden",s=n.count!==0;(s&&!r||!s&&r)&&Bu.dispatch(n.count>0?"SCROLL_PREVENT":"SCROLL_ALLOW",n),n.count===0&&Bu.dispatch("TEARDOWN",n)}});function _Fe(e,t,n=()=>({containers:[]})){let r=jK(Bu),s=t?r.get(t):void 0,o=s?s.count>0:!1;return Gn(()=>{if(!(!t||!e))return Bu.dispatch("PUSH",t,n),()=>Bu.dispatch("POP",t,n)},[e,t]),o}function DFe(e,t,n=()=>[document.body]){let r=SR(e,"scroll-lock");_Fe(r,t,s=>{var o;return{containers:[...(o=s.containers)!=null?o:[],n]}})}function e3(e){return[e.screenX,e.screenY]}function MFe(){let e=j.useRef([-1,-1]);return{wasMoved(t){let n=e3(t);return e.current[0]===n[0]&&e.current[1]===n[1]?!1:(e.current=n,!0)},update(t){e.current=e3(t)}}}function TFe(e=0){let[t,n]=j.useState(e),r=j.useCallback(l=>n(l),[t]),s=j.useCallback(l=>n(u=>u|l),[t]),o=j.useCallback(l=>(t&l)===l,[t]),i=j.useCallback(l=>n(u=>u&~l),[n]),a=j.useCallback(l=>n(u=>u^l),[n]);return{flags:t,setFlag:r,addFlag:s,hasFlag:o,removeFlag:i,toggleFlag:a}}var t3,n3;typeof process<"u"&&typeof globalThis<"u"&&typeof Element<"u"&&((t3=process==null?void 0:process.env)==null?void 0:t3.NODE_ENV)==="test"&&typeof((n3=Element==null?void 0:Element.prototype)==null?void 0:n3.getAnimations)>"u"&&(Element.prototype.getAnimations=function(){return console.warn(["Headless UI has polyfilled `Element.prototype.getAnimations` for your tests.","Please install a proper polyfill e.g. `jsdom-testing-mocks`, to silence these warnings.","","Example usage:","```js","import { mockAnimationsApi } from 'jsdom-testing-mocks'","mockAnimationsApi()","```"].join(`
973
- `)),[]});var RFe=(e=>(e[e.None=0]="None",e[e.Closed=1]="Closed",e[e.Enter=2]="Enter",e[e.Leave=4]="Leave",e))(RFe||{});function IFe(e){let t={};for(let n in e)e[n]===!0&&(t[`data-${n}`]="");return t}function AFe(e,t,n,r){let[s,o]=j.useState(n),{hasFlag:i,addFlag:a,removeFlag:l}=TFe(e&&s?3:0),u=j.useRef(!1),d=j.useRef(!1),f=vx();return Gn(()=>{var h;if(e){if(n&&o(!0),!t){n&&a(3);return}return(h=void 0)==null||h.call(r,n),PFe(t,{inFlight:u,prepare(){d.current?d.current=!1:d.current=u.current,u.current=!0,!d.current&&(n?(a(3),l(4)):(a(4),l(2)))},run(){d.current?n?(l(3),a(4)):(l(4),a(3)):n?l(1):a(1)},done(){var m;d.current&&typeof t.getAnimations=="function"&&t.getAnimations().length>0||(u.current=!1,l(7),n||o(!1),(m=void 0)==null||m.call(r,n))}})}},[e,n,t,f]),e?[s,{closed:i(1),enter:i(2),leave:i(4),transition:i(2)||i(4)}]:[n,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}function PFe(e,{prepare:t,run:n,done:r,inFlight:s}){let o=xa();return FFe(e,{prepare:t,inFlight:s}),o.nextFrame(()=>{n(),o.requestAnimationFrame(()=>{o.add(OFe(e,r))})}),o.dispose}function OFe(e,t){var n,r;let s=xa();if(!e)return s.dispose;let o=!1;s.add(()=>{o=!0});let i=(r=(n=e.getAnimations)==null?void 0:n.call(e).filter(a=>a instanceof CSSTransition))!=null?r:[];return i.length===0?(t(),s.dispose):(Promise.allSettled(i.map(a=>a.finished)).then(()=>{o||t()}),s.dispose)}function FFe(e,{inFlight:t,prepare:n}){if(t!=null&&t.current){n();return}let r=e.style.transition;e.style.transition="none",n(),e.offsetHeight,e.style.transition=r}function $Fe(e,{container:t,accept:n,walk:r}){let s=j.useRef(n),o=j.useRef(r);j.useEffect(()=>{s.current=n,o.current=r},[n,r]),Gn(()=>{if(!t||!e)return;let i=yx(t);if(!i)return;let a=s.current,l=o.current,u=Object.assign(f=>a(f),{acceptNode:a}),d=i.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,u,!1);for(;d.nextNode();)l(d.currentNode)},[t,e,s,o])}function r3(e,t){let n=j.useRef([]),r=Ct(e);j.useEffect(()=>{let s=[...n.current];for(let[o,i]of t.entries())if(n.current[o]!==i){let a=r(t,s);return n.current=t,a}},[r,...t])}function LFe(){const e=navigator.userAgentData;return e&&Array.isArray(e.brands)?e.brands.map(t=>{let{brand:n,version:r}=t;return n+"/"+r}).join(" "):navigator.userAgent}const MK={...D},zFe=MK.useInsertionEffect,BFe=zFe||(e=>e());function TK(e){const t=D.useRef(()=>{if(process.env.NODE_ENV!=="production")throw new Error("Cannot call an event handler while rendering.")});return BFe(()=>{t.current=e}),D.useCallback(function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];return t.current==null?void 0:t.current(...r)},[])}var RE=typeof document<"u"?j.useLayoutEffect:j.useEffect;let s3=!1,VFe=0;const o3=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+VFe++;function HFe(){const[e,t]=D.useState(()=>s3?o3():void 0);return RE(()=>{e==null&&t(o3())},[]),D.useEffect(()=>{s3=!0},[]),e}const UFe=MK.useId,WFe=UFe||HFe;let nb;process.env.NODE_ENV!=="production"&&(nb=new Set);function qFe(){for(var e,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];const s="Floating UI: "+n.join(" ");if(!((e=nb)!=null&&e.has(s))){var o;(o=nb)==null||o.add(s),console.warn(s)}}function YFe(){for(var e,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];const s="Floating UI: "+n.join(" ");if(!((e=nb)!=null&&e.has(s))){var o;(o=nb)==null||o.add(s),console.error(s)}}function GFe(){const e=new Map;return{emit(t,n){var r;(r=e.get(t))==null||r.forEach(s=>s(n))},on(t,n){e.set(t,[...e.get(t)||[],n])},off(t,n){var r;e.set(t,((r=e.get(t))==null?void 0:r.filter(s=>s!==n))||[])}}}const KFe=D.createContext(null),ZFe=D.createContext(null),XFe=()=>{var e;return((e=D.useContext(KFe))==null?void 0:e.id)||null},QFe=()=>D.useContext(ZFe),JFe="data-floating-ui-focusable";function e5e(e){const{open:t=!1,onOpenChange:n,elements:r}=e,s=WFe(),o=D.useRef({}),[i]=D.useState(()=>GFe()),a=XFe()!=null;if(process.env.NODE_ENV!=="production"){const m=r.reference;m&&!es(m)&&YFe("Cannot pass a virtual element to the `elements.reference` option,","as it must be a real DOM element. Use `refs.setPositionReference()`","instead.")}const[l,u]=D.useState(r.reference),d=TK((m,p,g)=>{o.current.openEvent=m?p:void 0,i.emit("openchange",{open:m,event:p,reason:g,nested:a}),n==null||n(m,p,g)}),f=D.useMemo(()=>({setPositionReference:u}),[]),h=D.useMemo(()=>({reference:l||r.reference||null,floating:r.floating||null,domReference:r.reference}),[l,r.reference,r.floating]);return D.useMemo(()=>({dataRef:o,open:t,onOpenChange:d,elements:h,events:i,floatingId:s,refs:f}),[t,d,h,i,s,f])}function t5e(e){e===void 0&&(e={});const{nodeId:t}=e,n=e5e({...e,elements:{reference:null,floating:null,...e.elements}}),r=e.rootContext||n,s=r.elements,[o,i]=D.useState(null),[a,l]=D.useState(null),d=(s==null?void 0:s.domReference)||o,f=D.useRef(null),h=QFe();RE(()=>{d&&(f.current=d)},[d]);const m=fz({...e,elements:{...s,...a&&{reference:a}}}),p=D.useCallback(v=>{const w=es(v)?{getBoundingClientRect:()=>v.getBoundingClientRect(),contextElement:v}:v;l(w),m.refs.setReference(w)},[m.refs]),g=D.useCallback(v=>{(es(v)||v===null)&&(f.current=v,i(v)),(es(m.refs.reference.current)||m.refs.reference.current===null||v!==null&&!es(v))&&m.refs.setReference(v)},[m.refs]),b=D.useMemo(()=>({...m.refs,setReference:g,setPositionReference:p,domReference:f}),[m.refs,g,p]),x=D.useMemo(()=>({...m.elements,domReference:d}),[m.elements,d]),y=D.useMemo(()=>({...m,...r,refs:b,elements:x,nodeId:t}),[m,b,x,t,r]);return RE(()=>{r.dataRef.current.floatingContext=y;const v=h==null?void 0:h.nodesRef.current.find(w=>w.id===t);v&&(v.context=y)}),D.useMemo(()=>({...m,context:y,refs:b,elements:x}),[m,b,x,y])}const i3="active",a3="selected";function wj(e,t,n){const r=new Map,s=n==="item";let o=e;if(s&&e){const{[i3]:i,[a3]:a,...l}=e;o=l}return{...n==="floating"&&{tabIndex:-1,[JFe]:""},...o,...t.map(i=>{const a=i?i[n]:null;return typeof a=="function"?e?a(e):null:a}).concat(e).reduce((i,a)=>(a&&Object.entries(a).forEach(l=>{let[u,d]=l;if(!(s&&[i3,a3].includes(u)))if(u.indexOf("on")===0){if(r.has(u)||r.set(u,[]),typeof d=="function"){var f;(f=r.get(u))==null||f.push(d),i[u]=function(){for(var h,m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];return(h=r.get(u))==null?void 0:h.map(b=>b(...p)).find(b=>b!==void 0)}}}else i[u]=d}),i),{})}}function n5e(e){e===void 0&&(e=[]);const t=e.map(a=>a==null?void 0:a.reference),n=e.map(a=>a==null?void 0:a.floating),r=e.map(a=>a==null?void 0:a.item),s=D.useCallback(a=>wj(a,e,"reference"),t),o=D.useCallback(a=>wj(a,e,"floating"),n),i=D.useCallback(a=>wj(a,e,"item"),r);return D.useMemo(()=>({getReferenceProps:s,getFloatingProps:o,getItemProps:i}),[s,o,i])}function l3(e,t){return{...e,rects:{...e.rects,floating:{...e.rects.floating,height:t}}}}const r5e=e=>({name:"inner",options:e,async fn(t){const{listRef:n,overflowRef:r,onFallbackChange:s,offset:o=0,index:i=0,minItemsVisible:a=4,referenceOverflowThreshold:l=0,scrollRef:u,...d}=ha(e,t),{rects:f,elements:{floating:h}}=t,m=n.current[i],p=(u==null?void 0:u.current)||h,g=h.clientTop||p.clientTop,b=h.clientTop!==0,x=p.clientTop!==0,y=h===p;if(process.env.NODE_ENV!=="production"&&(t.placement.startsWith("bottom")||qFe('`placement` side must be "bottom" when using the `inner`',"middleware.")),!m)return{};const v={...t,...await CD(-m.offsetTop-h.clientTop-f.reference.height/2-m.offsetHeight/2-o).fn(t)},w=await BC(l3(v,p.scrollHeight+g+h.clientTop),d),C=await BC(v,{...d,elementContext:"reference"}),S=Jr(0,w.top),N=v.y+S,k=(p.scrollHeight>p.clientHeight?M=>M:Ag)(Jr(0,p.scrollHeight+(b&&y||x?g*2:0)-S-Jr(0,w.bottom)));if(p.style.maxHeight=k+"px",p.scrollTop=S,s){const M=p.offsetHeight<m.offsetHeight*pl(a,n.current.length)-1||C.top>=-l||C.bottom>=-l;wc.flushSync(()=>s(M))}return r&&(r.current=await BC(l3({...v,y:N},p.offsetHeight+g+h.clientTop),d)),{y:N}}});function s5e(e,t){const{open:n,elements:r}=e,{enabled:s=!0,overflowRef:o,scrollRef:i,onChange:a}=t,l=TK(a),u=D.useRef(!1),d=D.useRef(null),f=D.useRef(null);D.useEffect(()=>{if(!s)return;function m(g){if(g.ctrlKey||!p||o.current==null)return;const b=g.deltaY,x=o.current.top>=-.5,y=o.current.bottom>=-.5,v=p.scrollHeight-p.clientHeight,w=b<0?-1:1,C=b<0?"max":"min";p.scrollHeight<=p.clientHeight||(!x&&b>0||!y&&b<0?(g.preventDefault(),wc.flushSync(()=>{l(S=>S+Math[C](b,v*w))})):/firefox/i.test(LFe())&&(p.scrollTop+=b))}const p=(i==null?void 0:i.current)||r.floating;if(n&&p)return p.addEventListener("wheel",m),requestAnimationFrame(()=>{d.current=p.scrollTop,o.current!=null&&(f.current={...o.current})}),()=>{d.current=null,f.current=null,p.removeEventListener("wheel",m)}},[s,n,r.floating,o,i,l]);const h=D.useMemo(()=>({onKeyDown(){u.current=!0},onWheel(){u.current=!1},onPointerMove(){u.current=!1},onScroll(){const m=(i==null?void 0:i.current)||r.floating;if(!(!o.current||!m||!u.current)){if(d.current!==null){const p=m.scrollTop-d.current;(o.current.bottom<-.5&&p<-1||o.current.top<-.5&&p>1)&&wc.flushSync(()=>l(g=>g+p))}requestAnimationFrame(()=>{d.current=m.scrollTop})}}}),[r.floating,l,o,i]);return D.useMemo(()=>s?{floating:h}:{},[s,h])}let wx=j.createContext({styles:void 0,setReference:()=>{},setFloating:()=>{},getReferenceProps:()=>({}),getFloatingProps:()=>({}),slot:{}});wx.displayName="FloatingContext";let CR=j.createContext(null);CR.displayName="PlacementContext";function o5e(e){return j.useMemo(()=>e?typeof e=="string"?{to:e}:e:null,[e])}function i5e(){return j.useContext(wx).setReference}function a5e(){let{getFloatingProps:e,slot:t}=j.useContext(wx);return j.useCallback((...n)=>Object.assign({},e(...n),{"data-anchor":t.anchor}),[e,t])}function l5e(e=null){e===!1&&(e=null),typeof e=="string"&&(e={to:e});let t=j.useContext(CR),n=j.useMemo(()=>e,[JSON.stringify(e,(s,o)=>{var i;return(i=o==null?void 0:o.outerHTML)!=null?i:o})]);Gn(()=>{t==null||t(n??null)},[t,n]);let r=j.useContext(wx);return j.useMemo(()=>[r.setFloating,e?r.styles:{}],[r.setFloating,e,r.styles])}let c3=4;function c5e({children:e,enabled:t=!0}){let[n,r]=j.useState(null),[s,o]=j.useState(0),i=j.useRef(null),[a,l]=j.useState(null);u5e(a);let u=t&&n!==null&&a!==null,{to:d="bottom",gap:f=0,offset:h=0,padding:m=0,inner:p}=d5e(n,a),[g,b="center"]=d.split(" ");Gn(()=>{u&&o(0)},[u]);let{refs:x,floatingStyles:y,context:v}=t5e({open:u,placement:g==="selection"?b==="center"?"bottom":`bottom-${b}`:b==="center"?`${g}`:`${g}-${b}`,strategy:"absolute",transform:!1,middleware:[CD({mainAxis:g==="selection"?0:f,crossAxis:h}),hz({padding:m}),g!=="selection"&&mz({padding:m}),g==="selection"&&p?r5e({...p,padding:m,overflowRef:i,offset:s,minItemsVisible:c3,referenceOverflowThreshold:m,onFallbackChange(M){var T,O;if(!M)return;let R=v.elements.floating;if(!R)return;let I=parseFloat(getComputedStyle(R).scrollPaddingBottom)||0,L=Math.min(c3,R.childElementCount),F=0,V=0;for(let $ of(O=(T=v.elements.floating)==null?void 0:T.childNodes)!=null?O:[])if($ instanceof HTMLElement){let P=$.offsetTop,U=P+$.clientHeight+I,B=R.scrollTop,A=B+R.clientHeight;if(P>=B&&U<=A)L--;else{V=Math.max(0,Math.min(U,A)-Math.max(P,B)),F=$.clientHeight;break}}L>=1&&o($=>{let P=F*L-V+I;return $>=P?$:P})}}):null,pz({padding:m,apply({availableWidth:M,availableHeight:T,elements:O}){Object.assign(O.floating.style,{overflow:"auto",maxWidth:`${M}px`,maxHeight:`min(var(--anchor-max-height, 100vh), ${T}px)`})}})].filter(Boolean),whileElementsMounted:uz}),[w=g,C=b]=v.placement.split("-");g==="selection"&&(w="selection");let S=j.useMemo(()=>({anchor:[w,C].filter(Boolean).join(" ")}),[w,C]),N=s5e(v,{overflowRef:i,onChange:o}),{getReferenceProps:_,getFloatingProps:E}=n5e([N]),k=Ct(M=>{l(M),x.setFloating(M)});return D.createElement(CR.Provider,{value:r},D.createElement(wx.Provider,{value:{setFloating:k,setReference:x.setReference,styles:y,getReferenceProps:_,getFloatingProps:E,slot:S}},e))}function u5e(e){Gn(()=>{if(!e)return;let t=new MutationObserver(()=>{let n=window.getComputedStyle(e).maxHeight,r=parseFloat(n);if(isNaN(r))return;let s=parseInt(n);isNaN(s)||r!==s&&(e.style.maxHeight=`${Math.ceil(r)}px`)});return t.observe(e,{attributes:!0,attributeFilter:["style"]}),()=>{t.disconnect()}},[e])}function d5e(e,t){var n,r,s;let o=Sj((n=e==null?void 0:e.gap)!=null?n:"var(--anchor-gap, 0)",t),i=Sj((r=e==null?void 0:e.offset)!=null?r:"var(--anchor-offset, 0)",t),a=Sj((s=e==null?void 0:e.padding)!=null?s:"var(--anchor-padding, 0)",t);return{...e,gap:o,offset:i,padding:a}}function Sj(e,t,n=void 0){let r=vx(),s=Ct((l,u)=>{if(l==null)return[n,null];if(typeof l=="number")return[l,null];if(typeof l=="string"){if(!u)return[n,null];let d=u3(l,u);return[d,f=>{let h=RK(l);{let m=h.map(p=>window.getComputedStyle(u).getPropertyValue(p));r.requestAnimationFrame(function p(){r.nextFrame(p);let g=!1;for(let[x,y]of h.entries()){let v=window.getComputedStyle(u).getPropertyValue(y);if(m[x]!==v){m[x]=v,g=!0;break}}if(!g)return;let b=u3(l,u);d!==b&&(f(b),d=b)})}return r.dispose}]}return[n,null]}),o=j.useMemo(()=>s(e,t)[0],[e,t]),[i=o,a]=j.useState();return Gn(()=>{let[l,u]=s(e,t);if(a(l),!!u)return u(a)},[e,t]),i}function RK(e){let t=/var\((.*)\)/.exec(e);if(t){let n=t[1].indexOf(",");if(n===-1)return[t[1]];let r=t[1].slice(0,n).trim(),s=t[1].slice(n+1).trim();return s?[r,...RK(s)]:[r]}return[]}function u3(e,t){let n=document.createElement("div");t.appendChild(n),n.style.setProperty("margin-top","0px","important"),n.style.setProperty("margin-top",e,"important");let r=parseFloat(window.getComputedStyle(n).marginTop)||0;return t.removeChild(n),r}function f5e({children:e,freeze:t}){let n=IE(t,e);return j.createElement(j.Fragment,null,n)}function IE(e,t){let[n,r]=j.useState(t);return!e&&n!==t&&r(t),e?n:t}let NR=j.createContext(null);NR.displayName="OpenClosedContext";var rb=(e=>(e[e.Open=1]="Open",e[e.Closed=2]="Closed",e[e.Closing=4]="Closing",e[e.Opening=8]="Opening",e))(rb||{});function h5e(){return j.useContext(NR)}function m5e({value:e,children:t}){return j.createElement(NR.Provider,{value:e},t)}function p5e(e){function t(){document.readyState!=="loading"&&(e(),document.removeEventListener("DOMContentLoaded",t))}typeof window<"u"&&typeof document<"u"&&(document.addEventListener("DOMContentLoaded",t),t())}let Mu=[];p5e(()=>{function e(t){if(!(t.target instanceof HTMLElement)||t.target===document.body||Mu[0]===t.target)return;let n=t.target;n=n.closest(TE),Mu.unshift(n??t.target),Mu=Mu.filter(r=>r!=null&&r.isConnected),Mu.splice(10)}window.addEventListener("click",e,{capture:!0}),window.addEventListener("mousedown",e,{capture:!0}),window.addEventListener("focus",e,{capture:!0}),document.body.addEventListener("click",e,{capture:!0}),document.body.addEventListener("mousedown",e,{capture:!0}),document.body.addEventListener("focus",e,{capture:!0})});function g5e(e){throw new Error("Unexpected object: "+e)}var yr=(e=>(e[e.First=0]="First",e[e.Previous=1]="Previous",e[e.Next=2]="Next",e[e.Last=3]="Last",e[e.Specific=4]="Specific",e[e.Nothing=5]="Nothing",e))(yr||{});function d3(e,t){let n=t.resolveItems();if(n.length<=0)return null;let r=t.resolveActiveIndex(),s=r??-1;switch(e.focus){case 0:{for(let o=0;o<n.length;++o)if(!t.resolveDisabled(n[o],o,n))return o;return r}case 1:{s===-1&&(s=n.length);for(let o=s-1;o>=0;--o)if(!t.resolveDisabled(n[o],o,n))return o;return r}case 2:{for(let o=s+1;o<n.length;++o)if(!t.resolveDisabled(n[o],o,n))return o;return r}case 3:{for(let o=n.length-1;o>=0;--o)if(!t.resolveDisabled(n[o],o,n))return o;return r}case 4:{for(let o=0;o<n.length;++o)if(t.resolveId(n[o],o,n)===e.id)return o;return r}case 5:return null;default:g5e(e)}}var jR=(e=>(e[e.Left=0]="Left",e[e.Right=2]="Right",e))(jR||{});function b5e(e){let t=Ct(e),n=j.useRef(!1);j.useEffect(()=>(n.current=!1,()=>{n.current=!0,mK(()=>{n.current&&t()})}),[t])}function x5e(){let e=typeof document>"u";return"useSyncExternalStore"in D?(t=>t.useSyncExternalStore)(D)(()=>()=>{},()=>!1,()=>!e):!1}function y5e(){let e=x5e(),[t,n]=D.useState(cd.isHandoffComplete);return t&&cd.isHandoffComplete===!1&&n(!1),D.useEffect(()=>{t!==!0&&n(!0)},[t]),D.useEffect(()=>cd.handoff(),[]),e?!1:t}let v5e=j.createContext(!1);function w5e(){return j.useContext(v5e)}function S5e(e){let t=w5e(),n=j.useContext(AK),r=vS(e),[s,o]=j.useState(()=>{var i;if(!t&&n!==null)return(i=n.current)!=null?i:null;if(cd.isServer)return null;let a=r==null?void 0:r.getElementById("headlessui-portal-root");if(a)return a;if(r===null)return null;let l=r.createElement("div");return l.setAttribute("id","headlessui-portal-root"),r.body.appendChild(l)});return j.useEffect(()=>{s!==null&&(r!=null&&r.body.contains(s)||r==null||r.body.appendChild(s))},[s,r]),j.useEffect(()=>{t||n!==null&&o(n.current)},[n,o,t]),s}let IK=j.Fragment,C5e=$i(function(e,t){let n=e,r=j.useRef(null),s=kl(ZOe(f=>{r.current=f}),t),o=vS(r),i=S5e(r),[a]=j.useState(()=>{var f;return cd.isServer?null:(f=o==null?void 0:o.createElement("div"))!=null?f:null}),l=j.useContext(E5e),u=y5e();Gn(()=>{!i||!a||i.contains(a)||(a.setAttribute("data-headlessui-portal",""),i.appendChild(a))},[i,a]),Gn(()=>{if(a&&l)return l.register(a)},[l,a]),b5e(()=>{var f;!i||!a||(a instanceof Node&&i.contains(a)&&i.removeChild(a),i.childNodes.length<=0&&((f=i.parentElement)==null||f.removeChild(i)))});let d=Fi();return u?!i||!a?null:Pn.createPortal(d({ourProps:{ref:s},theirProps:n,slot:{},defaultTag:IK,name:"Portal"}),a):null});function N5e(e,t){let n=kl(t),{enabled:r=!0,...s}=e,o=Fi();return r?j.createElement(C5e,{...s,ref:n}):o({ourProps:{ref:n},theirProps:s,slot:{},defaultTag:IK,name:"Portal"})}let j5e=j.Fragment,AK=j.createContext(null);function k5e(e,t){let{target:n,...r}=e,s={ref:kl(t)},o=Fi();return j.createElement(AK.Provider,{value:n},o({ourProps:s,theirProps:r,defaultTag:j5e,name:"Popover.Group"}))}let E5e=j.createContext(null),_5e=$i(N5e),D5e=$i(k5e),M5e=Object.assign(_5e,{Group:D5e});var T5e=(e=>(e[e.Open=0]="Open",e[e.Closed=1]="Closed",e))(T5e||{}),R5e=(e=>(e[e.Single=0]="Single",e[e.Multi=1]="Multi",e))(R5e||{}),I5e=(e=>(e[e.Pointer=0]="Pointer",e[e.Focus=1]="Focus",e[e.Other=2]="Other",e))(I5e||{}),A5e=(e=>(e[e.OpenCombobox=0]="OpenCombobox",e[e.CloseCombobox=1]="CloseCombobox",e[e.GoToOption=2]="GoToOption",e[e.SetTyping=3]="SetTyping",e[e.RegisterOption=4]="RegisterOption",e[e.UnregisterOption=5]="UnregisterOption",e[e.SetActivationTrigger=6]="SetActivationTrigger",e[e.UpdateVirtualConfiguration=7]="UpdateVirtualConfiguration",e[e.SetInputElement=8]="SetInputElement",e[e.SetButtonElement=9]="SetButtonElement",e[e.SetOptionsElement=10]="SetOptionsElement",e))(A5e||{});function Cj(e,t=n=>n){let n=e.activeOptionIndex!==null?e.options[e.activeOptionIndex]:null,r=t(e.options.slice()),s=r.length>0&&r[0].dataRef.current.order!==null?r.sort((i,a)=>i.dataRef.current.order-a.dataRef.current.order):xFe(r,i=>i.dataRef.current.domRef.current),o=n?s.indexOf(n):null;return o===-1&&(o=null),{options:s,activeOptionIndex:o}}let P5e={1(e){var t;return(t=e.dataRef.current)!=null&&t.disabled||e.comboboxState===1?e:{...e,activeOptionIndex:null,comboboxState:1,isTyping:!1,activationTrigger:2,__demoMode:!1}},0(e){var t,n;if((t=e.dataRef.current)!=null&&t.disabled||e.comboboxState===0)return e;if((n=e.dataRef.current)!=null&&n.value){let r=e.dataRef.current.calculateIndex(e.dataRef.current.value);if(r!==-1)return{...e,activeOptionIndex:r,comboboxState:0,__demoMode:!1}}return{...e,comboboxState:0,__demoMode:!1}},3(e,t){return e.isTyping===t.isTyping?e:{...e,isTyping:t.isTyping}},2(e,t){var n,r,s,o;if((n=e.dataRef.current)!=null&&n.disabled||e.optionsElement&&!((r=e.dataRef.current)!=null&&r.optionsPropsRef.current.static)&&e.comboboxState===1)return e;if(e.virtual){let{options:u,disabled:d}=e.virtual,f=t.focus===yr.Specific?t.idx:d3(t,{resolveItems:()=>u,resolveActiveIndex:()=>{var m,p;return(p=(m=e.activeOptionIndex)!=null?m:u.findIndex(g=>!d(g)))!=null?p:null},resolveDisabled:d,resolveId(){throw new Error("Function not implemented.")}}),h=(s=t.trigger)!=null?s:2;return e.activeOptionIndex===f&&e.activationTrigger===h?e:{...e,activeOptionIndex:f,activationTrigger:h,isTyping:!1,__demoMode:!1}}let i=Cj(e);if(i.activeOptionIndex===null){let u=i.options.findIndex(d=>!d.dataRef.current.disabled);u!==-1&&(i.activeOptionIndex=u)}let a=t.focus===yr.Specific?t.idx:d3(t,{resolveItems:()=>i.options,resolveActiveIndex:()=>i.activeOptionIndex,resolveId:u=>u.id,resolveDisabled:u=>u.dataRef.current.disabled}),l=(o=t.trigger)!=null?o:2;return e.activeOptionIndex===a&&e.activationTrigger===l?e:{...e,...i,isTyping:!1,activeOptionIndex:a,activationTrigger:l,__demoMode:!1}},4:(e,t)=>{var n,r,s;if((n=e.dataRef.current)!=null&&n.virtual)return{...e,options:[...e.options,t.payload]};let o=t.payload,i=Cj(e,l=>(l.push(o),l));e.activeOptionIndex===null&&(r=e.dataRef.current)!=null&&r.isSelected(t.payload.dataRef.current.value)&&(i.activeOptionIndex=i.options.indexOf(o));let a={...e,...i,activationTrigger:2};return(s=e.dataRef.current)!=null&&s.__demoMode&&e.dataRef.current.value===void 0&&(a.activeOptionIndex=0),a},5:(e,t)=>{var n;if((n=e.dataRef.current)!=null&&n.virtual)return{...e,options:e.options.filter(s=>s.id!==t.id)};let r=Cj(e,s=>{let o=s.findIndex(i=>i.id===t.id);return o!==-1&&s.splice(o,1),s});return{...e,...r,activationTrigger:2}},6:(e,t)=>e.activationTrigger===t.trigger?e:{...e,activationTrigger:t.trigger},7:(e,t)=>{var n,r;if(e.virtual===null)return{...e,virtual:{options:t.options,disabled:(n=t.disabled)!=null?n:()=>!1}};if(e.virtual.options===t.options&&e.virtual.disabled===t.disabled)return e;let s=e.activeOptionIndex;if(e.activeOptionIndex!==null){let o=t.options.indexOf(e.virtual.options[e.activeOptionIndex]);o!==-1?s=o:s=null}return{...e,activeOptionIndex:s,virtual:{options:t.options,disabled:(r=t.disabled)!=null?r:()=>!1}}},8:(e,t)=>e.inputElement===t.element?e:{...e,inputElement:t.element},9:(e,t)=>e.buttonElement===t.element?e:{...e,buttonElement:t.element},10:(e,t)=>e.optionsElement===t.element?e:{...e,optionsElement:t.element}},kR=j.createContext(null);kR.displayName="ComboboxActionsContext";function Sx(e){let t=j.useContext(kR);if(t===null){let n=new Error(`<${e} /> is missing a parent <Combobox /> component.`);throw Error.captureStackTrace&&Error.captureStackTrace(n,Sx),n}return t}let PK=j.createContext(null);function O5e(e){let t=Gm("VirtualProvider"),{options:n}=t.virtual,[r,s]=j.useMemo(()=>{let u=t.optionsElement;if(!u)return[0,0];let d=window.getComputedStyle(u);return[parseFloat(d.paddingBlockStart||d.paddingTop),parseFloat(d.paddingBlockEnd||d.paddingBottom)]},[t.optionsElement]),o=QT({enabled:n.length!==0,scrollPaddingStart:r,scrollPaddingEnd:s,count:n.length,estimateSize(){return 40},getScrollElement(){return t.optionsElement},overscan:12}),[i,a]=j.useState(0);Gn(()=>{a(u=>u+1)},[n]);let l=o.getVirtualItems();return l.length===0?null:j.createElement(PK.Provider,{value:o},j.createElement("div",{style:{position:"relative",width:"100%",height:`${o.getTotalSize()}px`},ref:u=>{u&&t.activationTrigger!==0&&t.activeOptionIndex!==null&&n.length>t.activeOptionIndex&&o.scrollToIndex(t.activeOptionIndex)}},l.map(u=>{var d;return j.createElement(j.Fragment,{key:u.key},j.cloneElement((d=e.children)==null?void 0:d.call(e,{...e.slot,option:n[u.index]}),{key:`${i}-${u.key}`,"data-index":u.index,"aria-setsize":n.length,"aria-posinset":u.index+1,style:{position:"absolute",top:0,left:0,transform:`translateY(${u.start}px)`,overflowAnchor:"none"}}))})))}let sb=j.createContext(null);sb.displayName="ComboboxDataContext";function Gm(e){let t=j.useContext(sb);if(t===null){let n=new Error(`<${e} /> is missing a parent <Combobox /> component.`);throw Error.captureStackTrace&&Error.captureStackTrace(n,Gm),n}return t}function F5e(e,t){return fl(t.type,P5e,e,t)}let $5e=j.Fragment;function L5e(e,t){var n,r;let s=xR(),{value:o,defaultValue:i,onChange:a,form:l,name:u,by:d,disabled:f=s||!1,onClose:h,__demoMode:m=!1,multiple:p=!1,immediate:g=!1,virtual:b=null,nullable:x,...y}=e,v=zOe(i),[w=p?[]:void 0,C]=LOe(o,a,v),[S,N]=j.useReducer(F5e,{dataRef:j.createRef(),comboboxState:m?0:1,isTyping:!1,options:[],virtual:b?{options:b.options,disabled:(n=b.disabled)!=null?n:()=>!1}:null,activeOptionIndex:null,activationTrigger:2,inputElement:null,buttonElement:null,optionsElement:null,__demoMode:m}),_=j.useRef(!1),E=j.useRef({static:!1,hold:!1}),k=aFe(d),M=Ct(se=>b?d===null?b.options.indexOf(se):b.options.findIndex(ce=>k(ce,se)):S.options.findIndex(ce=>k(ce.dataRef.current.value,se))),T=j.useCallback(se=>fl(R.mode,{1:()=>w.some(ce=>k(ce,se)),0:()=>k(w,se)}),[w]),O=Ct(se=>S.activeOptionIndex===M(se)),R=j.useMemo(()=>({...S,immediate:g,optionsPropsRef:E,value:w,defaultValue:v,disabled:f,mode:p?1:0,virtual:b?S.virtual:null,get activeOptionIndex(){if(_.current&&S.activeOptionIndex===null&&(b?b.options.length>0:S.options.length>0)){if(b){let ce=b.options.findIndex(re=>{var fe,Ce;return!((Ce=(fe=b.disabled)==null?void 0:fe.call(b,re))!=null&&Ce)});if(ce!==-1)return ce}let se=S.options.findIndex(ce=>!ce.dataRef.current.disabled);if(se!==-1)return se}return S.activeOptionIndex},calculateIndex:M,compare:k,isSelected:T,isActive:O}),[w,v,f,p,m,S,b]);Gn(()=>{var se;b&&N({type:7,options:b.options,disabled:(se=b.disabled)!=null?se:null})},[b,b==null?void 0:b.options,b==null?void 0:b.disabled]),Gn(()=>{S.dataRef.current=R},[R]);let I=R.comboboxState===0;wFe(I,[R.buttonElement,R.inputElement,R.optionsElement],()=>H.closeCombobox());let L=j.useMemo(()=>{var se,ce,re;return{open:R.comboboxState===0,disabled:f,activeIndex:R.activeOptionIndex,activeOption:R.activeOptionIndex===null?null:R.virtual?R.virtual.options[(se=R.activeOptionIndex)!=null?se:0]:(re=(ce=R.options[R.activeOptionIndex])==null?void 0:ce.dataRef.current.value)!=null?re:null,value:w}},[R,f,w]),F=Ct(()=>{if(R.activeOptionIndex!==null){if(H.setIsTyping(!1),R.virtual)A(R.virtual.options[R.activeOptionIndex]);else{let{dataRef:se}=R.options[R.activeOptionIndex];A(se.current.value)}H.goToOption(yr.Specific,R.activeOptionIndex)}}),V=Ct(()=>{N({type:0}),_.current=!0}),$=Ct(()=>{N({type:1}),_.current=!1,h==null||h()}),P=Ct(se=>{N({type:3,isTyping:se})}),U=Ct((se,ce,re)=>(_.current=!1,se===yr.Specific?N({type:2,focus:yr.Specific,idx:ce,trigger:re}):N({type:2,focus:se,trigger:re}))),B=Ct((se,ce)=>(N({type:4,payload:{id:se,dataRef:ce}}),()=>{R.isActive(ce.current.value)&&(_.current=!0),N({type:5,id:se})})),A=Ct(se=>fl(R.mode,{0(){return C==null?void 0:C(se)},1(){let ce=R.value.slice(),re=ce.findIndex(fe=>k(fe,se));return re===-1?ce.push(se):ce.splice(re,1),C==null?void 0:C(ce)}})),Y=Ct(se=>{N({type:6,trigger:se})}),z=Ct(se=>{N({type:8,element:se})}),q=Ct(se=>{N({type:9,element:se})}),W=Ct(se=>{N({type:10,element:se})}),H=j.useMemo(()=>({onChange:A,registerOption:B,goToOption:U,setIsTyping:P,closeCombobox:$,openCombobox:V,setActivationTrigger:Y,selectActiveOption:F,setInputElement:z,setButtonElement:q,setOptionsElement:W}),[]),[G,K]=tFe(),te=t===null?{}:{ref:t},Z=j.useCallback(()=>{if(v!==void 0)return C==null?void 0:C(v)},[C,v]),ee=Fi();return j.createElement(K,{value:G,props:{htmlFor:(r=R.inputElement)==null?void 0:r.id},slot:{open:R.comboboxState===0,disabled:f}},j.createElement(c5e,null,j.createElement(kR.Provider,{value:H},j.createElement(sb.Provider,{value:R},j.createElement(m5e,{value:fl(R.comboboxState,{0:rb.Open,1:rb.Closed})},u!=null&&j.createElement(WOe,{disabled:f,data:w!=null?{[u]:w}:{},form:l,onReset:Z}),ee({ourProps:te,theirProps:y,slot:L,defaultTag:$5e,name:"Combobox"}))))))}let z5e="input";function B5e(e,t){var n,r,s,o,i;let a=Gm("Combobox.Input"),l=Sx("Combobox.Input"),u=j.useId(),d=vK(),{id:f=d||`headlessui-combobox-input-${u}`,onChange:h,displayValue:m,disabled:p=a.disabled||!1,autoFocus:g=!1,type:b="text",...x}=e,y=j.useRef(null),v=kl(y,t,i5e(),l.setInputElement),w=vS(a.inputElement),C=vx(),S=Ct(()=>{l.onChange(null),a.optionsElement&&(a.optionsElement.scrollTop=0),l.goToOption(yr.Nothing)}),N=j.useMemo(()=>{var A;return typeof m=="function"&&a.value!==void 0?(A=m(a.value))!=null?A:"":typeof a.value=="string"?a.value:""},[a.value,m]);r3(([A,Y],[z,q])=>{if(a.isTyping)return;let W=y.current;W&&((q===0&&Y===1||A!==z)&&(W.value=A),requestAnimationFrame(()=>{if(a.isTyping||!W||(w==null?void 0:w.activeElement)!==W)return;let{selectionStart:H,selectionEnd:G}=W;Math.abs((G??0)-(H??0))===0&&H===0&&W.setSelectionRange(W.value.length,W.value.length)}))},[N,a.comboboxState,w,a.isTyping]),r3(([A],[Y])=>{if(A===0&&Y===1){if(a.isTyping)return;let z=y.current;if(!z)return;let q=z.value,{selectionStart:W,selectionEnd:H,selectionDirection:G}=z;z.value="",z.value=q,G!==null?z.setSelectionRange(W,H,G):z.setSelectionRange(W,H)}},[a.comboboxState]);let _=j.useRef(!1),E=Ct(()=>{_.current=!0}),k=Ct(()=>{C.nextFrame(()=>{_.current=!1})}),M=Ct(A=>{switch(l.setIsTyping(!0),A.key){case ys.Enter:if(a.comboboxState!==0||_.current)return;if(A.preventDefault(),A.stopPropagation(),a.activeOptionIndex===null){l.closeCombobox();return}l.selectActiveOption(),a.mode===0&&l.closeCombobox();break;case ys.ArrowDown:return A.preventDefault(),A.stopPropagation(),fl(a.comboboxState,{0:()=>l.goToOption(yr.Next),1:()=>l.openCombobox()});case ys.ArrowUp:return A.preventDefault(),A.stopPropagation(),fl(a.comboboxState,{0:()=>l.goToOption(yr.Previous),1:()=>{Pn.flushSync(()=>l.openCombobox()),a.value||l.goToOption(yr.Last)}});case ys.Home:if(A.shiftKey)break;return A.preventDefault(),A.stopPropagation(),l.goToOption(yr.First);case ys.PageUp:return A.preventDefault(),A.stopPropagation(),l.goToOption(yr.First);case ys.End:if(A.shiftKey)break;return A.preventDefault(),A.stopPropagation(),l.goToOption(yr.Last);case ys.PageDown:return A.preventDefault(),A.stopPropagation(),l.goToOption(yr.Last);case ys.Escape:return a.comboboxState!==0?void 0:(A.preventDefault(),a.optionsElement&&!a.optionsPropsRef.current.static&&A.stopPropagation(),a.mode===0&&a.value===null&&S(),l.closeCombobox());case ys.Tab:if(a.comboboxState!==0)return;a.mode===0&&a.activationTrigger!==1&&l.selectActiveOption(),l.closeCombobox();break}}),T=Ct(A=>{h==null||h(A),a.mode===0&&A.target.value===""&&S(),l.openCombobox()}),O=Ct(A=>{var Y,z,q;let W=(Y=A.relatedTarget)!=null?Y:Mu.find(H=>H!==A.currentTarget);if(!((z=a.optionsElement)!=null&&z.contains(W))&&!((q=a.buttonElement)!=null&&q.contains(W))&&a.comboboxState===0)return A.preventDefault(),a.mode===0&&a.value===null&&S(),l.closeCombobox()}),R=Ct(A=>{var Y,z,q;let W=(Y=A.relatedTarget)!=null?Y:Mu.find(H=>H!==A.currentTarget);(z=a.buttonElement)!=null&&z.contains(W)||(q=a.optionsElement)!=null&&q.contains(W)||a.disabled||a.immediate&&a.comboboxState!==0&&C.microTask(()=>{Pn.flushSync(()=>l.openCombobox()),l.setActivationTrigger(1)})}),I=yS(),L=XOe(),{isFocused:F,focusProps:V}=hK({autoFocus:g}),{isHovered:$,hoverProps:P}=fK({isDisabled:p}),U=j.useMemo(()=>({open:a.comboboxState===0,disabled:p,hover:$,focus:F,autofocus:g}),[a,$,F,g,p]),B=yR({ref:v,id:f,role:"combobox",type:b,"aria-controls":(n=a.optionsElement)==null?void 0:n.id,"aria-expanded":a.comboboxState===0,"aria-activedescendant":a.activeOptionIndex===null?void 0:a.virtual?(r=a.options.find(A=>!A.dataRef.current.disabled&&a.compare(A.dataRef.current.value,a.virtual.options[a.activeOptionIndex])))==null?void 0:r.id:(s=a.options[a.activeOptionIndex])==null?void 0:s.id,"aria-labelledby":I,"aria-describedby":L,"aria-autocomplete":"list",defaultValue:(i=(o=e.defaultValue)!=null?o:a.defaultValue!==void 0?m==null?void 0:m(a.defaultValue):null)!=null?i:a.defaultValue,disabled:p||void 0,autoFocus:g,onCompositionStart:E,onCompositionEnd:k,onKeyDown:M,onChange:T,onFocus:R,onBlur:O},V,P);return Fi()({ourProps:B,theirProps:x,slot:U,defaultTag:z5e,name:"Combobox.Input"})}let V5e="button";function H5e(e,t){var n;let r=Gm("Combobox.Button"),s=Sx("Combobox.Button"),o=kl(t,s.setButtonElement),i=j.useId(),{id:a=`headlessui-combobox-button-${i}`,disabled:l=r.disabled||!1,autoFocus:u=!1,...d}=e,f=DK(r.inputElement),h=Ct(N=>{switch(N.key){case ys.Space:case ys.Enter:N.preventDefault(),N.stopPropagation(),r.comboboxState===1&&Pn.flushSync(()=>s.openCombobox()),f();return;case ys.ArrowDown:N.preventDefault(),N.stopPropagation(),r.comboboxState===1&&(Pn.flushSync(()=>s.openCombobox()),r.value||s.goToOption(yr.First)),f();return;case ys.ArrowUp:N.preventDefault(),N.stopPropagation(),r.comboboxState===1&&(Pn.flushSync(()=>s.openCombobox()),r.value||s.goToOption(yr.Last)),f();return;case ys.Escape:if(r.comboboxState!==0)return;N.preventDefault(),r.optionsElement&&!r.optionsPropsRef.current.static&&N.stopPropagation(),Pn.flushSync(()=>s.closeCombobox()),f();return;default:return}}),m=Ct(N=>{N.preventDefault(),!GOe(N.currentTarget)&&(N.button===jR.Left&&(r.comboboxState===0?s.closeCombobox():s.openCombobox()),f())}),p=yS([a]),{isFocusVisible:g,focusProps:b}=hK({autoFocus:u}),{isHovered:x,hoverProps:y}=fK({isDisabled:l}),{pressed:v,pressProps:w}=ROe({disabled:l}),C=j.useMemo(()=>({open:r.comboboxState===0,active:v||r.comboboxState===0,disabled:l,value:r.value,hover:x,focus:g}),[r,x,g,v,l]),S=yR({ref:o,id:a,type:CFe(e,r.buttonElement),tabIndex:-1,"aria-haspopup":"listbox","aria-controls":(n=r.optionsElement)==null?void 0:n.id,"aria-expanded":r.comboboxState===0,"aria-labelledby":p,disabled:l||void 0,autoFocus:u,onMouseDown:m,onKeyDown:h},b,y,w);return Fi()({ourProps:S,theirProps:d,slot:C,defaultTag:V5e,name:"Combobox.Button"})}let U5e="div",W5e=DE.RenderStrategy|DE.Static;function q5e(e,t){var n,r,s;let o=j.useId(),{id:i=`headlessui-combobox-options-${o}`,hold:a=!1,anchor:l,portal:u=!1,modal:d=!0,transition:f=!1,...h}=e,m=Gm("Combobox.Options"),p=Sx("Combobox.Options"),g=o5e(l);g&&(u=!0);let[b,x]=l5e(g),[y,v]=j.useState(null),w=a5e(),C=kl(t,g?b:null,p.setOptionsElement,v),S=vS(m.optionsElement),N=h5e(),[_,E]=AFe(f,y,N!==null?(N&rb.Open)===rb.Open:m.comboboxState===0);fFe(_,m.inputElement,p.closeCombobox);let k=m.__demoMode?!1:d&&m.comboboxState===0;DFe(k,S);let M=m.__demoMode?!1:d&&m.comboboxState===0;dFe(M,{allowed:j.useCallback(()=>[m.inputElement,m.buttonElement,m.optionsElement],[m.inputElement,m.buttonElement,m.optionsElement])}),Gn(()=>{var B;m.optionsPropsRef.current.static=(B=e.static)!=null?B:!1},[m.optionsPropsRef,e.static]),Gn(()=>{m.optionsPropsRef.current.hold=a},[m.optionsPropsRef,a]),$Fe(m.comboboxState===0,{container:m.optionsElement,accept(B){return B.getAttribute("role")==="option"?NodeFilter.FILTER_REJECT:B.hasAttribute("role")?NodeFilter.FILTER_SKIP:NodeFilter.FILTER_ACCEPT},walk(B){B.setAttribute("role","none")}});let T=yS([(n=m.buttonElement)==null?void 0:n.id]),O=j.useMemo(()=>({open:m.comboboxState===0,option:void 0}),[m.comboboxState]),R=Ct(()=>{p.setActivationTrigger(0)}),I=Ct(B=>{B.preventDefault(),p.setActivationTrigger(0)}),L=yR(g?w():{},{"aria-labelledby":T,role:"listbox","aria-multiselectable":m.mode===1?!0:void 0,id:i,ref:C,style:{...h.style,...x,"--input-width":Z4(m.inputElement,!0).width,"--button-width":Z4(m.buttonElement,!0).width},onWheel:m.activationTrigger===0?void 0:R,onMouseDown:I,...IFe(E)}),F=_&&m.comboboxState===1,V=IE(F,(r=m.virtual)==null?void 0:r.options),$=IE(F,m.value),P=Ct(B=>m.compare($,B));if(m.virtual){if(V===void 0)throw new Error("Missing `options` in virtual mode");Object.assign(h,{children:j.createElement(sb.Provider,{value:V!==m.virtual.options?{...m,virtual:{...m.virtual,options:V}}:m},j.createElement(O5e,{slot:O},h.children))})}let U=Fi();return j.createElement(M5e,{enabled:u?e.static||_:!1},j.createElement(sb.Provider,{value:m.mode===1?m:{...m,isSelected:P}},U({ourProps:L,theirProps:{...h,children:j.createElement(f5e,{freeze:F},typeof h.children=="function"?(s=h.children)==null?void 0:s.call(h,O):h.children)},slot:O,defaultTag:U5e,features:W5e,visible:_,name:"Combobox.Options"})))}let Y5e="div";function G5e(e,t){var n,r,s,o;let i=Gm("Combobox.Option"),a=Sx("Combobox.Option"),l=j.useId(),{id:u=`headlessui-combobox-option-${l}`,value:d,disabled:f=(s=(r=(n=i.virtual)==null?void 0:n.disabled)==null?void 0:r.call(n,d))!=null?s:!1,order:h=null,...m}=e,p=DK(i.inputElement),g=i.virtual?i.activeOptionIndex===i.calculateIndex(d):i.activeOptionIndex===null?!1:((o=i.options[i.activeOptionIndex])==null?void 0:o.id)===u,b=i.isSelected(d),x=j.useRef(null),y=af({disabled:f,value:d,domRef:x,order:h}),v=j.useContext(PK),w=kl(t,x,v?v.measureElement:null),C=Ct(()=>{a.setIsTyping(!1),a.onChange(d)});Gn(()=>a.registerOption(u,y),[y,u]);let S=j.useRef(!(i.virtual||i.__demoMode));Gn(()=>{if(!i.virtual&&!i.__demoMode)return xa().requestAnimationFrame(()=>{S.current=!0})},[i.virtual,i.__demoMode]),Gn(()=>{if(S.current&&i.comboboxState===0&&g&&i.activationTrigger!==0)return xa().requestAnimationFrame(()=>{var I,L;(L=(I=x.current)==null?void 0:I.scrollIntoView)==null||L.call(I,{block:"nearest"})})},[x,g,i.comboboxState,i.activationTrigger,i.activeOptionIndex]);let N=Ct(I=>{I.preventDefault(),I.button===jR.Left&&(f||(C(),_K()||requestAnimationFrame(()=>p()),i.mode===0&&a.closeCombobox()))}),_=Ct(()=>{if(f)return a.goToOption(yr.Nothing);let I=i.calculateIndex(d);a.goToOption(yr.Specific,I)}),E=MFe(),k=Ct(I=>E.update(I)),M=Ct(I=>{if(!E.wasMoved(I)||f||g)return;let L=i.calculateIndex(d);a.goToOption(yr.Specific,L,0)}),T=Ct(I=>{E.wasMoved(I)&&(f||g&&(i.optionsPropsRef.current.hold||a.goToOption(yr.Nothing)))}),O=j.useMemo(()=>({active:g,focus:g,selected:b,disabled:f}),[g,b,f]),R={id:u,ref:w,role:"option",tabIndex:f===!0?void 0:-1,"aria-disabled":f===!0?!0:void 0,"aria-selected":b,disabled:void 0,onMouseDown:N,onFocus:_,onPointerEnter:k,onMouseEnter:k,onPointerMove:M,onMouseMove:M,onPointerLeave:T,onMouseLeave:T};return Fi()({ourProps:R,theirProps:m,slot:O,defaultTag:Y5e,name:"Combobox.Option"})}let K5e=$i(L5e),OK=$i(H5e),FK=$i(B5e),Z5e=oFe,$K=$i(q5e),LK=$i(G5e),X5e=Object.assign(K5e,{Input:FK,Button:OK,Label:Z5e,Options:$K,Option:LK});function Q5e({elementId:e}){const t=j.useRef(!1);return j.useEffect(()=>{if(t.current)return;const n=document.getElementById(e);return n&&(n.classList.add("semaphor-scope"),t.current=!0),()=>{n&&(n.classList.remove("semaphor-scope"),t.current=!1)}},[e]),null}const J5e=j.memo(({option:e,currentStyle:t})=>c.jsxs(LK,{style:{borderRadius:t==null?void 0:t.controlInputRadius},value:e,className:"group flex cursor-default select-none items-start gap-2 rounded-sm px-3 py-1.5 data-[focus]:bg-muted",children:[c.jsx($r,{className:"invisible size-4 shrink-0 group-data-[selected]:visible"}),e.value]},e.id),(e,t)=>e.option.id===t.option.id&&e.option.value===t.option.value);function e4e({options:e,onChange:t,selectedOptions:n,multiple:r=!0,externalFilteredOptions:s,selectAllChecked:o,onSelectAllCheckedChange:i,inputClassName:a,renderFilterModeButton:l,showNegativeIndicator:u,isSearching:d,resultSource:f="local",searchError:h,query:m,onQueryChange:p,filterDataType:g,onEnterKey:b,activeFilterValue:x}){const[y,v]=j.useState(""),w=m!==void 0?m:y,C=p||v,S=Q(R=>R.themeStyle),N=s||e;function _(R,I){if(I)return"";const L=[">","<",">=","<=","="];return(g?wi(g):!1)&&x&&L.includes(x.operation)?`${x.operation}${x.values[0]}`:R!=null&&R.length?R==null?void 0:R.map(V=>V.value).join(", "):""}function E(R){Array.isArray(R)||(R=[R]),t(R)}function k(){return d||N&&N.length>0?null:c.jsx("div",{className:"relative cursor-default select-none px-4 py-2",children:"No records found."})}function M(){return d?c.jsxs("div",{className:"flex items-center gap-2 border-b border-b-muted px-4 py-2 text-xs text-muted-foreground",children:[c.jsx("div",{className:"h-3 w-3 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Searching..."]}):h&&w?c.jsx("div",{className:"border-b border-b-muted px-4 py-2 text-xs text-amber-600",children:"Search unavailable. Showing available results."}):null}function T(){return w||!(e!=null&&e.length)?null:c.jsx("div",{className:"border-b border-b-muted px-4 py-2 text-xs text-muted-foreground",children:"Type to search more..."})}function O(){return!r||!(N!=null&&N.length)?null:c.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-b-muted px-4 py-2",children:[l==null?void 0:l(),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{children:"All"}),c.jsx(nn,{className:"border-muted-foreground/50",checked:o,onCheckedChange:i})]})]})}return c.jsx(X5e,{multiple:r,value:n,onChange:E,onClose:()=>{C("")},by:(R,I)=>Array.isArray(R)||Array.isArray(I)?!1:!R||!I?R===I:R.id===I.id,children:({open:R})=>c.jsxs("div",{children:[c.jsxs("div",{className:"relative flex items-center gap-0.5",children:[u&&c.jsx("div",{className:"h-8 w-0.5 bg-red-400"}),c.jsx(FK,{className:X("h-8 w-full rounded-sm border border-border bg-background py-1.5 pl-3 pr-8 text-sm","data-[focus]:outline-border-none focus:outline-none data-[focus]:outline-none data-[focus]:-outline-offset-2",a),style:{borderRadius:S==null?void 0:S.controlInputRadius},displayValue:I=>_(I,R),onChange:I=>C(I.target.value),onKeyDown:I=>{if(I.key==="Enter"&&b){const L=/^(>=|<=|>|<|=)/.test(w.trim()),F=g?wi(g):!1;L&&F&&(I.preventDefault(),b()&&I.target.blur())}}}),c.jsx(OK,{className:"group absolute inset-y-0 right-0 rounded-sm bg-muted/40 px-2.5 transition-colors hover:bg-muted/60",children:c.jsx(Ks,{className:"size-4 text-muted-foreground transition-colors group-hover:text-foreground"})})]}),c.jsxs($K,{anchor:"bottom",transition:!0,style:{borderRadius:S==null?void 0:S.controlInputRadius},className:fd("mt-1 !max-h-60 w-[var(--input-width)] overflow-y-auto rounded-sm border border-border bg-background p-1 text-sm [--anchor-gap:var(--spacing-1)] empty:invisible","transition duration-100 ease-in data-[leave]:data-[closed]:opacity-0"),children:[R&&c.jsx(Q5e,{elementId:"headlessui-portal-root"}),M(),T(),k(),O(),N==null?void 0:N.map(I=>c.jsx(J5e,{option:I,currentStyle:S},I.id))]})]})})}const f3=[{value:"=",label:"Equal to",symbol:"="},{value:">",label:"Greater than",symbol:">"},{value:">=",label:"Greater than or equal",symbol:"≥"},{value:"<",label:"Less than",symbol:"<"},{value:"<=",label:"Less than or equal",symbol:"≤"},{value:"between",label:"Between",symbol:"⟷"},{value:"not between",label:"Not Between",symbol:"⇎"}],t4e=new Set(["=",">","<",">=","<=","between","not between"]);function n4e(e){return t4e.has(e)?e:">="}function r4e({filter:e,storageOptions:t}){var T;const[n,r]=j.useState(">="),[s,o]=j.useState(""),[i,a]=j.useState(""),[l,u]=j.useState(""),[d,f]=j.useState(!0),h=j.useRef(null),m=j.useRef(!1),[,p]=j.useTransition(),g=ug(s,300),b=ug(i,300),x=ug(l,300),y=(t==null?void 0:t.storageTarget)==="card",v=Q(O=>O.filterValues),w=Q(O=>O.themeStyle),C=Q(O=>O.actions.setCardInlineFilterValue),S=Q(O=>O.actions.removeCardInlineFilterValue),{addOrUpdateFilterValue:N,removeFilterValues:_}=Gt(),E=y?t==null?void 0:t.inlineFilterValues:v,k=j.useCallback(O=>{y?C((t==null?void 0:t.cardId)??"",O):N(O)},[y,C,t==null?void 0:t.cardId,N]),M=j.useCallback(()=>{y?S((t==null?void 0:t.cardId)??"",e.id):_(e.id)},[y,e.id,S,t==null?void 0:t.cardId,_]);return j.useEffect(()=>()=>{h.current=null,m.current=!1},[]),j.useEffect(()=>{const O=E==null?void 0:E.find(R=>R.filterId===e.id);if(O&&O.operation!=="in"){const R=n4e(O.operation);if(h.current!==R&&(r(R),h.current=R,m.current=!1),R==="between"||R==="not between"){const L=O.values[0],F=O.values[1];a(L!=null?String(L):""),u(F!=null?String(F):""),o("")}else{const L=O.values[0];o(L!=null?String(L):""),a(""),u("")}}else h.current!==null&&(o(""),a(""),u(""),!m.current&&h.current!==n&&(r(">="),m.current=!1),h.current=null),f(!1)},[E,e.id]),j.useEffect(()=>{d&&(n==="between"||n==="not between"?b===i&&x===l&&f(!1):g===s&&f(!1))},[d,n,s,g,i,l,b,x]),j.useEffect(()=>{if(!d)if(n==="between"||n==="not between"){const O=b&&b.trim()!=="",R=x&&x.trim()!=="";if(!O||!R){!O&&!R&&(p(()=>{M()}),h.current=n);return}const I=Number(b),L=Number(x);if(isNaN(I)||isNaN(L))return;const F={filterId:e.id,connectionType:e.database==="NA"?"api":"database",name:e.column,valueType:hi(e),operation:n,values:[I,L]};p(()=>{k(F)}),h.current=n}else{if(!g||g.trim()===""){p(()=>{M()}),h.current=null;return}const O=Number(g);if(isNaN(O))return;const R={filterId:e.id,connectionType:e.database==="NA"?"api":"database",name:e.column,valueType:hi(e),operation:n,values:[O]};p(()=>{k(R)}),h.current=n}},[n,g,b,x,e.id,e.column,e.database,d,k,M,e]),c.jsxs("div",{className:"flex gap-2",children:[c.jsxs(rt,{value:n,onValueChange:O=>{m.current=!0,r(O)},children:[c.jsx(tt,{className:"h-8 w-16",style:{borderRadius:w==null?void 0:w.controlInputRadius},children:c.jsx("span",{className:"font-mono text-base",children:(T=f3.find(O=>O.value===n))==null?void 0:T.symbol})}),c.jsx(nt,{children:f3.map(O=>c.jsx(ge,{value:O.value,children:c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-mono",children:O.symbol}),c.jsx("span",{children:O.label})]})},O.value))})]}),n==="between"||n==="not between"?c.jsxs(c.Fragment,{children:[c.jsx(Nn,{type:"number",placeholder:"Min",value:i,onChange:O=>a(O.target.value),className:"h-8 flex-1",style:{borderRadius:w==null?void 0:w.controlInputRadius}}),c.jsx(Nn,{type:"number",placeholder:"Max",value:l,onChange:O=>u(O.target.value),className:"h-8 flex-1",style:{borderRadius:w==null?void 0:w.controlInputRadius}})]}):c.jsx(Nn,{type:"number",placeholder:"Value",value:s,onChange:O=>o(O.target.value),className:"h-8 flex-1",style:{borderRadius:w==null?void 0:w.controlInputRadius}})]})}function zK({filter:e,storageOptions:t}){const n=e.searchMode==="numeric",r=Q(w=>w.themeStyle),{filteredRecords:s,isSingleSelect:o,allSelected:i,handleChange:a,handleSelectAll:l,handleApplyOperatorExpression:u,query:d,setQuery:f,isLoading:h,isFetching:m,isError:p,selectedRecords:g,isSearching:b,searchError:x,resultSource:y,activeFilterValue:v}=gx(e,{enableServerSearch:!0,searchDebounceMs:300,minSearchLength:2,searchThreshold:5,...t});return h||m?c.jsx(Ns,{style:{borderRadius:r==null?void 0:r.controlInputRadius},className:"h-8 w-full bg-foreground/10"}):p?c.jsx("div",{className:"flex h-8 w-full items-center bg-muted px-2 text-sm",children:"Error"}):n?c.jsx(r4e,{filter:e,storageOptions:t}):c.jsx(e4e,{showNegativeIndicator:e.operation==="not in",renderFilterModeButton:()=>c.jsx(s4e,{filter:e,storageOptions:t}),inputClassName:"h-8",options:s,selectedOptions:g,onChange:a,multiple:!o,selectAllChecked:i,onSelectAllCheckedChange:l,isSearching:b,resultSource:y,searchError:x,query:d,onQueryChange:f,filterDataType:e.dataType,activeFilterValue:v,onEnterKey:u})}function s4e({filter:e,storageOptions:t}){const n=e.operation==="in"?"include":"exclude",r=(t==null?void 0:t.storageTarget)==="card",{setFilterMode:s,setFilterDefaultValues:o}=Gt(),i=Q(S=>S.isDashboardEditing),a=Q(S=>S.isVisualEditing),l=Q(S=>S.filterValues),u=Q(S=>S.actions.setCardInlineFilterMode),d=Q(S=>S.actions.setCardInlineFilterDefaultValues),f=Q(S=>S.inlineFilterValuesMap[(t==null?void 0:t.cardId)||""]),h=Q(S=>S.actions.setCardInlineFilterValue),m=Ee(S=>S.card),{setCard:p}=lr(),g=r?t==null?void 0:t.inlineFilterValues:l,b=g==null?void 0:g.find(S=>S.filterId===e.id);function x(){const S=n==="include"?"exclude":"include",N=S==="exclude"?"not in":"in";if(r)if(a){const _=(m.inlineFilters||[]).map(k=>k.id===e.id?{...k,operation:N}:k);p({...m,inlineFilters:_});const E=f==null?void 0:f.find(k=>k.filterId===e.id);(E&&E.operation==="in"||(E==null?void 0:E.operation)==="not in")&&h((t==null?void 0:t.cardId)??"",{...E,operation:N})}else u((t==null?void 0:t.sheetId)??"",(t==null?void 0:t.cardId)??"",e.id,S);else s(e.id,S)}function y(){if(!(b!=null&&b.values))return;const S=b.values;if(r)if(a){const N=(m.inlineFilters||[]).map(_=>_.id===e.id?{..._,defaultValues:S}:_);p({...m,inlineFilters:N})}else d((t==null?void 0:t.sheetId)??"",(t==null?void 0:t.cardId)??"",e.id,S);else o(e.id,S)}const v=(b==null?void 0:b.values)&&b.values.length>0,w=e.defaultValues&&e.defaultValues.length>0,C=i||a;return c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:x,variant:"secondary",size:"sm",className:X("h-6 text-xs hover:underline",{}),children:Mg(n)}),C&&c.jsx(oe,{onClick:y,variant:w?"default":"ghost",size:"sm",className:X("h-6 text-xs",{"opacity-50":!v}),disabled:!v,title:w?"Update default values":v?"Set current selection as default":"Select values to set as default",children:"Default"})]})}function BK({filter:e,storageOptions:t}){var i;const{filteredRecords:n,handleChange:r,selectedRecords:s}=gx(e,t);function o(a){r([{value:a,id:a}])}return c.jsx(gi,{onValueChange:o,value:((i=s==null?void 0:s[0])==null?void 0:i.value)||"",className:"mt-2 flex gap-3 overflow-x-auto",children:n==null?void 0:n.map(a=>c.jsxs("div",{className:"flex gap-2",children:[c.jsx(Jn,{value:a.value,id:"r1"}),c.jsx(de,{className:"text-muted-foreground",htmlFor:"r1",children:a.value})]},a.value))})}function VK({filter:e,storageOptions:t}){var f;const n=Q(h=>h.themeStyle),{filteredRecords:r,handleChange:s,selectedRecords:o,isLoading:i,isFetching:a,isError:l}=gx(e,t),u=r&&r.length>10;function d(h){s([{value:h,id:h}])}return i||a?c.jsx(Ns,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 w-full bg-foreground/10"}):l?c.jsx("div",{className:"flex h-8 w-full items-center bg-muted px-2 text-sm",children:"Error loading filter options"}):c.jsxs("div",{className:"space-y-2",children:[u&&c.jsx("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:c.jsx(On,{children:c.jsxs(un,{delayDuration:0,children:[c.jsx(dn,{asChild:!0,children:c.jsxs("div",{className:"flex items-center gap-1 rounded-sm bg-amber-500/10 px-2 py-1",children:[c.jsx(tr,{className:"h-3 w-3 text-amber-600"}),c.jsxs("span",{className:"text-amber-600",children:["Many options (",r.length,")"]})]})}),c.jsx(pn,{side:"bottom",className:"max-w-xs",children:c.jsxs("p",{className:"text-xs",children:["This filter has ",r.length," options. Consider using a dropdown for better usability with many options."]})})]})})}),c.jsx(As,{value:((f=o==null?void 0:o[0])==null?void 0:f.value)||"",onValueChange:d,className:"w-full",children:c.jsx(cs,{className:"h-9 flex-wrap justify-start overflow-x-auto",children:r==null?void 0:r.map(h=>c.jsx(qt,{className:"h-7",value:h.value,children:h.value},h.value))})})]})}const o4e=j.createContext(null),Nj={didCatch:!1,error:null};class Da extends j.Component{constructor(t){super(t),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=Nj}static getDerivedStateFromError(t){return{didCatch:!0,error:t}}resetErrorBoundary(){const{error:t}=this.state;if(t!==null){for(var n,r,s=arguments.length,o=new Array(s),i=0;i<s;i++)o[i]=arguments[i];(n=(r=this.props).onReset)===null||n===void 0||n.call(r,{args:o,reason:"imperative-api"}),this.setState(Nj)}}componentDidCatch(t,n){var r,s;(r=(s=this.props).onError)===null||r===void 0||r.call(s,t,n)}componentDidUpdate(t,n){const{didCatch:r}=this.state,{resetKeys:s}=this.props;if(r&&n.error!==null&&i4e(t.resetKeys,s)){var o,i;(o=(i=this.props).onReset)===null||o===void 0||o.call(i,{next:s,prev:t.resetKeys,reason:"keys"}),this.setState(Nj)}}render(){const{children:t,fallbackRender:n,FallbackComponent:r,fallback:s}=this.props,{didCatch:o,error:i}=this.state;let a=t;if(o){const l={error:i,resetErrorBoundary:this.resetErrorBoundary};if(typeof n=="function")a=n(l);else if(r)a=j.createElement(r,l);else if(s!==void 0)a=s;else throw i}return j.createElement(o4e.Provider,{value:{didCatch:o,error:i,resetErrorBoundary:this.resetErrorBoundary}},a)}}function i4e(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];return e.length!==t.length||e.some((n,r)=>!Object.is(n,t[r]))}function h3({filter:e,storageOptions:t}){return Si(e.dataType)?c.jsx(rK,{filter:e,storageOptions:t}):e.uiType==="radio"&&e.type==="single"?c.jsx(BK,{filter:e,storageOptions:t}):e.uiType==="tabs"&&e.type==="single"?c.jsx(VK,{filter:e,storageOptions:t}):c.jsx(zK,{filter:e,storageOptions:t})}function a4e({filter:e,CustomFilterComponent:t,theme:n,storageOptions:r}){var v;const{filteredRecords:s,selectedRecords:o,handleChange:i,handleClear:a,handleSelectAll:l,query:u,setQuery:d,isLoading:f,isFetching:h,isError:m,isSearching:p,isSingleSelect:g,allSelected:b,activeFilterValue:x}=gx(e,{enableServerSearch:!0,...r}),y={filter:e,options:s||[],selectedValues:o||[],onChange:i,onClear:a,onSelectAll:l,searchQuery:u,onSearchChange:d,isLoading:f,isFetching:h,isError:m,isSearching:p,isSingleSelect:g,allSelected:b,activeFilterValue:x,theme:n,settings:(v=e.customFilterPreferences)==null?void 0:v.settings};return c.jsx(j.Suspense,{fallback:c.jsx(Ns,{className:"h-8 w-full bg-foreground/10"}),children:c.jsx(t,{...y})})}function l4e({filter:e,CustomFilterComponent:t,theme:n,storageOptions:r}){var y;const s=(r==null?void 0:r.storageTarget)==="card",{dateRange:o,initialDateRange:i,handleChange:a,handleRelativeChange:l,handleClear:u,handleReset:d,isLoading:f,isFetching:h,isError:m}=gR(e,r),p=Q(v=>v.filterValues),g=s?r==null?void 0:r.inlineFilterValues:p,b=g==null?void 0:g.find(v=>v.filterId===e.id),x={filter:e,dateRange:o,initialDateRange:i,onDateChange:a,onRelativeDateChange:l,onClear:u,onReset:d,isLoading:f,isFetching:h,isError:m,activeFilterValue:b,theme:n,settings:(y=e.customFilterPreferences)==null?void 0:y.settings};return c.jsx(j.Suspense,{fallback:c.jsx(Ns,{className:"h-8 w-full bg-foreground/10"}),children:c.jsx(t,{...x})})}function c4e({filter:e,storageOptions:t}){var h,m,p,g,b;const{theme:n}=Ob(),r=Q(x=>x.themeStyle),s={colors:((m=(h=r==null?void 0:r.chart)==null?void 0:h.dataset)==null?void 0:m.backgroundColor)||[],mode:n||"system"},{getFilter:o,isLoading:i,isError:a}=pS(((p=e.customFilterPreferences)==null?void 0:p.url)||""),l=(g=e.customFilterPreferences)==null?void 0:g.componentName,u=l?o(l):null;if(!l||!((b=e.customFilterPreferences)!=null&&b.url)||a||!i&&!u)return c.jsx(h3,{filter:e,storageOptions:t});if(i||!u)return c.jsx(Ns,{className:"h-8 w-full bg-foreground/10"});const f=Si(e.dataType);return c.jsx(Da,{fallback:c.jsx(h3,{filter:e,storageOptions:t}),onError:x=>console.error("Custom filter runtime error:",x),children:f?c.jsx(l4e,{filter:e,CustomFilterComponent:u,theme:s,storageOptions:t}):c.jsx(a4e,{filter:e,CustomFilterComponent:u,theme:s,storageOptions:t})})}const u4e=j.memo(c4e);function Cx({filter:e,storageOptions:t}){var n,r;return(n=e.customFilterPreferences)!=null&&n.url&&((r=e.customFilterPreferences)!=null&&r.componentName)?c.jsx(u4e,{filter:e,storageOptions:t}):Si(e.dataType)?c.jsx(rK,{filter:e,storageOptions:t}):e.uiType==="radio"&&e.type==="single"?c.jsx(BK,{filter:e,storageOptions:t}):e.uiType==="tabs"&&e.type==="single"?c.jsx(VK,{filter:e,storageOptions:t}):c.jsx(zK,{filter:e,storageOptions:t})}function d4e(e){return{id:e.id,connectionId:e.connectionId,title:e.title,column:e.column,dataType:e.dataType,table:e.table,database:e.database,sql:e.sql,operation:e.operation,type:e.type,uiType:e.uiType,dateSelectionMode:e.dateSelectionMode,defaultValues:e.defaultValues,defaultDateFilter:e.defaultDateFilter,searchMode:e.searchMode,customFilterPreferences:e.customFilterPreferences}}function HK({inlineFilter:e,sheetId:t,cardId:n,inlineFilterValues:r}){const s=d4e(e),o={storageTarget:"card",sheetId:t,cardId:n,inlineFilterValues:r},i=e.width??250,a=e.showLabel??!0;return c.jsxs("div",{className:"inline-filter-item flex flex-col gap-0.5",style:{width:i},children:[a&&c.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:e.title}),c.jsx(Cx,{filter:s,storageOptions:o})]})}function UK({card:e,sheetId:t,inlineFilterValues:n}){return!e.inlineFilters||e.inlineFilters.length===0?[]:e.inlineFilters.map(r=>c.jsx(HK,{inlineFilter:r,sheetId:t,cardId:e.id,inlineFilterValues:n},r.id))}function f4e({card:e,frame:t}){var I,L,F,V,$,P,U,B,A,Y,z,q;const[n,r]=j.useState([]),{theme:s}=Ob(),{authToken:o}=Ge(),i=V6(o==null?void 0:o.accessToken),a=Q(W=>W.themeStyle),l={colors:((L=(I=a==null?void 0:a.chart)==null?void 0:I.dataset)==null?void 0:L.backgroundColor)||[],mode:s||"system"},[u,d]=j.useState(!1),{getCard:f}=pS(((F=e.customCardPreferences)==null?void 0:F.url)||""),h=((V=e.customCardPreferences)==null?void 0:V.visualType)||"single",m=($=e.customCardPreferences)==null?void 0:$.componentName,{data:p}=pa(e),g=Pt(W=>W.interactionStates),b=Q(W=>{var H;return(H=W.dashboard)==null?void 0:H.id}),x=Q(W=>W.dashboard.filters),y=Q(W=>W.filterValues),v=Q(W=>W.selectedSheetId),w=Q(W=>W.inlineFilterValuesMap[e.id]),C=j.useMemo(()=>UK({card:e,sheetId:v||"",inlineFilterValues:w}),[e,v,w]),{cardFilters:S,cardFilterValues:N,shouldApplyDashboardFilters:_,contextMode:E}=j.useMemo(()=>rM({card:e,interactionStates:g,currentDashboardId:b,filters:x,filterValues:y,selectedSheetId:v}),[e,g,b,x,y,v]),k=j.useCallback((W,H)=>{r(G=>({...G,[W]:H}))},[]);if(!m)return null;const M=f(m),T=Object.keys(((P=e.customCardPreferences)==null?void 0:P.dataInputCardIds)||{}).map(W=>{var K,te,Z;const H=(te=(K=e.customCardPreferences)==null?void 0:K.dataInputCardIds)==null?void 0:te[W].cardId,G=(Z=t==null?void 0:t.cards)==null?void 0:Z.find(ee=>ee.id===H);return G||null});function O(W){d(W)}const R=((B=(U=e.preferences)==null?void 0:U.displayOptions)==null?void 0:B.allowScroll)??!0;return c.jsx("div",{className:X("semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2",R?"overflow-y-auto":"h-full overflow-hidden"),children:c.jsxs(j.Suspense,{fallback:c.jsx(c.Fragment,{}),children:[M&&h==="single"&&c.jsx(M,{params:i,theme:l,chartSettings:(A=e.customCardPreferences)==null?void 0:A.settings,settings:(Y=e.customCardPreferences)==null?void 0:Y.settings,onDataChange:k,data:(p==null?void 0:p.records)||[],filters:S,filterValues:[...N||[],...w||[]],inlineFilters:C}),M&&h==="multiple"&&c.jsxs("div",{children:[Object.keys(((z=e.customCardPreferences)==null?void 0:z.dataInputCardIds)||{}).map(W=>{var K,te,Z;const H=(te=(K=e.customCardPreferences)==null?void 0:K.dataInputCardIds)==null?void 0:te[W].cardId,G=(Z=t==null?void 0:t.cards)==null?void 0:Z.find(ee=>ee.id===H);if(G)return c.jsx(xG,{onLoadingStatus:O,onDataChange:k,dataInputIndex:W,card:G},G.id+W)}),h==="multiple"&&c.jsx("div",{className:X("flex flex-col gap-2",{"opacity-50":u}),children:c.jsx(M,{params:i,theme:l,onDataChange:k,chartSettings:(q=e.customCardPreferences)==null?void 0:q.settings,settings:T.map(W=>{var H;return(H=W==null?void 0:W.customCardPreferences)==null?void 0:H.settings}),data:T.map(W=>W!=null&&W.id?n==null?void 0:n[W.id]:[]),filters:S,filterValues:[...N||[],...w||[]],inlineFilters:C})})]})]},e.id)})}const ER=j.memo(f4e,(e,t)=>{var n,r,s,o;return e.card.id===t.card.id&&e.frame.id===t.frame.id&&((n=e.card.customCardPreferences)==null?void 0:n.url)===((r=t.card.customCardPreferences)==null?void 0:r.url)&&((s=e.card.customCardPreferences)==null?void 0:s.componentName)===((o=t.card.customCardPreferences)==null?void 0:o.componentName)});function wS({customerFacingMessage:e,error:t,resetErrorBoundary:n}){return c.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center rounded-lg border border-dashed border-muted-foreground/25 bg-muted/30 p-6 text-center",children:[c.jsx("div",{className:"mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:c.jsx("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"})})}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"Chart Unavailable"}),c.jsx("p",{className:"mb-4 text-xs text-muted-foreground",children:e||"Couldn't display this chart right now. Please try refreshing or check your data configuration."}),c.jsxs("button",{onClick:n,className:"inline-flex items-center justify-center rounded-md bg-primary px-3 py-2 text-xs font-medium text-primary-foreground shadow-sm transition-colors hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",children:[c.jsx("svg",{className:"mr-1.5 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Try Again"]}),c.jsxs("details",{className:"mt-4 w-full text-left",children:[c.jsx("summary",{className:"cursor-pointer text-xs text-muted-foreground hover:text-foreground",children:"Show technical details"}),c.jsxs("div",{className:"mt-2 rounded border bg-background p-3",children:[c.jsx("p",{className:"mb-1 text-xs font-medium text-foreground",children:"Error Details:"}),c.jsx("pre",{className:"text-xs text-muted-foreground",children:t.message})]})]})]})}function SS({error:e}){return c.jsx("div",{className:"flex flex-col items-center justify-center",role:"alert",style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",width:"100%"},children:c.jsxs("div",{style:{backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",boxShadow:"0 2px 6px rgba(0, 0, 0, 0.08)",color:"#b91c1c",fontFamily:"sans-serif",padding:"16px",textAlign:"center",flexDirection:"column",whiteSpace:"pre-wrap",position:"relative"},className:"flex flex-col justify-center space-y-1 rounded-md bg-muted p-10",children:[c.jsx("p",{className:"text-sm",children:"Something went wrong:"}),c.jsx("pre",{className:"text-xs",children:e.message})]})})}function h4e({error:e,frame:t}){return c.jsxs("div",{className:"flex h-full flex-col items-center justify-center border",role:"alert",children:[c.jsx(nZ,{frame:t,isHovered:!1}),c.jsx("div",{className:"flex flex-col justify-center space-y-2 rounded-md p-10"}),c.jsxs("div",{className:"flex flex-col justify-center space-y-2 rounded-md p-10",children:[c.jsx("p",{className:"text-lg font-semibold",children:"Oops! Looks like we tripped on a loose wire!"}),c.jsx("p",{className:"text-sm",children:"Something went wrong:"}),c.jsx("pre",{className:"text-xs",children:e.message})]})]})}function m4e(e={},t){const{displayPreferences:n,shouldShowElement:r}=Uc(),s=n.mode==="table-print",o=e.enabled??!0,i=e.serverSide??!1,a=s?Number.MAX_SAFE_INTEGER:e.pageSize||50,l=e.currentPage!==void 0,[u,d]=j.useState(0),[f,h]=j.useState(a),m=l?(e.currentPage||1)-1:u,p=s?Number.MAX_SAFE_INTEGER:l?e.pageSize||a:f,g=j.useMemo(()=>o&&r("showPagination")&&!s,[o,r,s]),b=j.useMemo(()=>i?e.pageCount:Math.ceil(t/p),[i,e.pageCount,t,p]),x=j.useMemo(()=>i?e.totalCount||0:t,[i,e.totalCount,t]),y=j.useMemo(()=>i?(e.currentPage||1)>1:m>0,[i,e.currentPage,m]),v=j.useMemo(()=>i?(e.currentPage||1)<(e.pageCount||1):m<(b||1)-1,[i,e.currentPage,e.pageCount,m,b]);return{pageIndex:m,pageSize:p,isServerSidePagination:i,showPagination:g,paginationEnabled:o,isTablePrintDisplayMode:s,setPageIndex:_=>{var E;l?(E=e.onPageChange)==null||E.call(e,_+1,p):d(_)},setPageSize:_=>{var E;l?(E=e.onPageChange)==null||E.call(e,1,_):(d(0),h(_))},canPreviousPage:y,canNextPage:v,previousPage:()=>{var E;if(!y)return;const _=m-1;l?(E=e.onPageChange)==null||E.call(e,_+1,p):d(_)},nextPage:()=>{var E;if(!v)return;const _=m+1;l?(E=e.onPageChange)==null||E.call(e,_+1,p):d(_)},pageCount:b,totalCount:x}}function p4e(e,t,n){var l;if(!t.length)return e;const r=t[0].id,s=t[0].desc?-1:1,o=((l=n.groupByColumns)==null?void 0:l.length)||0,i=r.startsWith("rowLevel"),a=i?parseInt(r.replace("rowLevel","")):-1;return i?g4e(e,a,s):b4e(e,r,s,o,n)}function g4e(e,t,n){const r=[...e],s=new Map,o=[];r.forEach(l=>{if(l.isGrandTotal)return;const u=t>0?l.fieldValues.slice(0,t).join("|||"):"root";s.has(u)||(s.set(u,[]),o.push(u)),s.get(u).push(l)});const i=[];o.forEach(l=>{const u=s.get(l),d=u.filter(h=>!h.isSubtotal),f=u.filter(h=>h.isSubtotal);d.sort((h,m)=>{const p=h.fieldValues[t],g=m.fieldValues[t];return p===g?0:p==null?1:g==null?-1:String(p).localeCompare(String(g))*n}),i.push(...d),i.push(...f)});const a=e.find(l=>l.isGrandTotal);return a&&i.push(a),i}function b4e(e,t,n,r,s){const o={rows:[],children:new Map};let i;e.forEach(f=>{if(f.isGrandTotal){i=f;return}if(f.isSubtotal){let h=o;for(let m=0;m<r-1;m++){const p=f.fieldValues[m];h.children.has(p)||h.children.set(p,{rows:[],children:new Map}),h=h.children.get(p)}h.subtotal=f}else{let h=o;for(let m=0;m<r-1;m++){const p=f.fieldValues[m];h.children.has(p)||h.children.set(p,{rows:[],children:new Map}),h=h.children.get(p)}h.rows.push(f)}});function a(f){var h;return t==="rowTotal"?s.columnHeaders.reduce((m,p)=>{var b;const g=(b=f.cells[p])==null?void 0:b.value;return m+(typeof g=="number"?g:0)},0):(h=f.cells[t])==null?void 0:h.value}function l(f){let h=0;return f.rows.forEach(m=>{const p=a(m);typeof p=="number"&&(h+=p)}),f.children.forEach(m=>{if(m.subtotal){const p=a(m.subtotal);typeof p=="number"&&(h+=p)}else h+=l(m)}),h}function u(f){const h=[],m=[...f.rows].sort((g,b)=>{const x=a(g),y=a(b);return x===y?0:x==null?1:y==null?-1:x>y?n:-n});return h.push(...m),Array.from(f.children.entries()).sort(([,g],[,b])=>{const x=g.subtotal?a(g.subtotal):l(g),y=b.subtotal?a(b.subtotal):l(b);return x===y?0:x==null?1:y==null?-1:x>y?n:-n}).forEach(([,g])=>{h.push(...u(g))}),f.subtotal&&h.push(f.subtotal),h}const d=u(o);return i&&d.push(i),d}function x4e(e,t){const[n,r]=j.useState([]),s=j.useMemo(()=>p4e(e,n,t),[e,n,t]),o=j.useCallback(l=>{r(u=>{const d=u.find(f=>f.id===l);return d?d.desc?[]:[{id:l,desc:!0}]:[{id:l,desc:!1}]})},[]),i=j.useCallback(()=>{r([])},[]),a=j.useCallback(l=>{const u=n.find(d=>d.id===l);return u?u.desc?"desc":"asc":!1},[n]);return{sorting:n,setSorting:r,sortedTableData:s,toggleColumnSort:o,clearSorting:i,getSortDirection:a}}function ob(e,t,n,r){if(t){const s=el(e,t,n,r),o=lEe(e,t);return s==="-"||s===0?c.jsx("div",{className:"flex justify-end",children:c.jsx(Eu,{className:"h-3 w-3 text-muted-foreground"})}):o?c.jsx("span",{style:{backgroundColor:o.backgroundColor,color:o.color,padding:"0.125rem 0.25rem",borderRadius:"0.25rem"},children:s}):s}return typeof e=="object"&&(e==null?void 0:e.formattedValue)!==void 0?e.formattedValue==="-"||e.formattedValue===0?c.jsx("div",{className:"flex justify-end",children:c.jsx(Eu,{className:"h-3 w-3 text-muted-foreground"})}):e.formattedValue:typeof e=="number"?e===0||e===null?c.jsx("div",{className:"flex justify-end",children:c.jsx(Eu,{className:"h-3 w-3 text-muted-foreground"})}):e.toLocaleString():e==null?c.jsx("div",{className:"flex justify-end",children:c.jsx(Eu,{className:"h-3 w-3 text-muted-foreground"})}):(e==null?void 0:e.toString())||c.jsx("div",{className:"flex justify-end",children:c.jsx(Eu,{className:"h-3 w-3 text-muted-foreground"})})}function y4e(e){return(e==null?void 0:e.includes("_SUM_"))||(e==null?void 0:e.includes("_AVG_"))||(e==null?void 0:e.includes("_COUNT_"))||(e==null?void 0:e.includes("_MIN_"))||(e==null?void 0:e.includes("_MAX_"))}function v4e(e,t){const n=(e==null?void 0:e.includes("_SUM_ALL"))||(e==null?void 0:e.includes("_AVG_ALL"))||(e==null?void 0:e.includes("_COUNT_ALL"))||(e==null?void 0:e.includes("_MIN_ALL"))||(e==null?void 0:e.includes("_MAX_ALL")),r=(t==null?void 0:t.some(s=>s.columnName===e&&(s.subtotalLevel==="grandTotal"||s.subtotalLevel==="ALL")))??!1;return n||r}function w4e({data:e,card:t,table:n,sorting:r,setSorting:s,showRowTotals:o,onAggregationChange:i,onOpenColumnSettings:a}){const[l,u]=j.useState(null),d=Q(m=>m.isVisualEditing),f=j.useCallback(m=>{var p;return(p=n.getHeaderGroups()[0])==null?void 0:p.headers.find(g=>g.column.id===m)},[n]);return{buildColumnHeaderRows:j.useCallback(()=>{var N,_;const m=((N=t.config)==null?void 0:N.pivotByColumns)||[],p=m.length,g=((_=e.groupByColumns)==null?void 0:_.length)||1,b=e.columnHeaders.length;function x(E,k,M,T=[]){E.forEach((O,R)=>{var L,F,V;const I=O.level;if(I<p){const $=O.columnKey||`${I}-${T.join("-")}-${O.name}-${R}`,P=O.children?1:p-I,U=`pivot-${$}`,B=l===U;if(M[I].push(c.jsx(ao,{colSpan:O.colspan,rowSpan:P,className:"h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-center text-xs font-medium",children:c.jsxs("div",{className:"group/pivot-header relative flex items-center justify-center",children:[i&&c.jsx("div",{className:X("absolute left-0 overflow-hidden transition-all duration-200",B?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/pivot-header:h-6 group-hover/pivot-header:w-6 group-hover/pivot-header:opacity-100"),children:c.jsx(Vp,{columnName:O.name,groupByFields:e.groupByColumns||[],pivotByFields:((L=t.config)==null?void 0:L.pivotByColumns)||[],currentAggregation:{rowAggregates:(F=t.config)==null?void 0:F.rowAggregates,columnAggregates:(V=t.config)==null?void 0:V.columnAggregates},onAggregationChange:i,onOpenChange:A=>u(A?U:null)})}),c.jsx("span",{className:"whitespace-nowrap",children:O.name})]})},$)),O.children){const A=[...T,O.name];x(O.children,I+1,M,A)}}})}function y(E,k=[]){const M=[];return E.forEach((T,O)=>{var R,I,L,F,V;if(T.columnKey){const $=T.columnKey||`metric-${k.join("-")}-${T.name}-${O}`,P=y4e(T.columnKey),U=v4e(T.columnKey,e.columnSubtotalMeta),B=n.getColumn(T.columnKey),A=f(T.columnKey);M.push(c.jsx(ao,{"data-column-id":T.columnKey,className:X("group/header h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-right text-xs last:border-r-0",U?"bg-muted font-semibold":P?"bg-muted/70 font-medium":""),style:{width:A==null?void 0:A.getSize(),minWidth:A==null?void 0:A.getSize(),maxWidth:A==null?void 0:A.getSize(),position:"relative",transition:"none"},children:B?c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs(oe,{variant:"ghost",className:"h-auto flex-shrink-0 p-0 hover:bg-transparent",onClick:()=>{const Y=B.getIsSorted();s(Y?Y==="asc"?[{id:B.id,desc:!0}]:[]:[{id:B.id,desc:!1}])},"aria-label":`Sort ${((R=e.columnDisplayNames)==null?void 0:R[T.columnKey])||T.name||"Metric"}`,children:[c.jsx(Fo,{className:X("mr-1 h-3 w-3",B.getIsSorted()==="asc"?"hidden group-hover/header:block":"hidden")}),c.jsx(ta,{className:X("mr-1 h-3 w-3",B.getIsSorted()==="desc"?"hidden group-hover/header:block":"hidden")}),c.jsx(ku,{className:X("mr-1 h-3 w-3",B.getIsSorted()?"hidden":"hidden group-hover/header:block")})]}),c.jsx("span",{className:"min-w-0 truncate text-xs font-medium",title:((I=e.columnDisplayNames)==null?void 0:I[T.columnKey])||T.name||"Metric",children:((L=e.columnDisplayNames)==null?void 0:L[T.columnKey])||T.name||"Metric"}),d&&a&&c.jsx(oe,{variant:"ghost",size:"icon",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover/header:opacity-100",onClick:Y=>{Y.stopPropagation(),a(T.columnKey)},children:c.jsx(Ju,{className:"h-3 w-3"})}),A&&c.jsx(Du,{header:A,isResizing:A.column.getIsResizing()})]}):c.jsx("span",{className:"block truncate px-2",title:((F=e.columnDisplayNames)==null?void 0:F[T.columnKey])||T.name||"Metric",children:((V=e.columnDisplayNames)==null?void 0:V[T.columnKey])||T.name||"Metric"})},$))}else if(T.children){const $=[...k,T.name];M.push(...y(T.children,$))}}),M}const v=c.jsxs(fr,{"data-header-type":"pivot-hierarchy","data-header-row-index":"0","data-repeat-header":"true",children:[e.groupByColumns&&e.groupByColumns.length>0?e.groupByColumns.map((E,k)=>{var I,L,F,V,$;const M=(I=n.getHeaderGroups()[0])==null?void 0:I.headers.find(P=>P.column.id===`rowLevel${k}`),T=M==null?void 0:M.getSize(),O=`row-header-${k}`,R=l===O;return c.jsx(ao,{rowSpan:p+2,"data-column-id":`rowLevel${k}`,className:"group/rowheader h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-left align-bottom text-xs font-medium",style:{width:T,minWidth:T,maxWidth:T,position:"relative",transition:"none"},children:c.jsxs("div",{className:"flex h-full min-w-0 items-end justify-between pb-1",children:[c.jsxs("div",{className:"relative flex min-w-0 items-center",children:[i&&c.jsx("div",{className:X("absolute left-0 top-1/2 -translate-y-1/2 overflow-hidden transition-all duration-200",R?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/rowheader:h-6 group-hover/rowheader:w-6 group-hover/rowheader:opacity-100"),children:c.jsx(Vp,{columnName:E.label||E.name,groupByFields:e.groupByColumns||[],pivotByFields:m,currentAggregation:{rowAggregates:(L=t.config)==null?void 0:L.rowAggregates,columnAggregates:(F=t.config)==null?void 0:F.columnAggregates},onAggregationChange:i,onOpenChange:P=>u(P?O:null)})}),c.jsxs(oe,{variant:"ghost",className:X("flex h-auto min-w-0 items-center gap-1 p-0 transition-all duration-200 hover:bg-transparent",i&&(R?"pl-7":"group-hover/rowheader:pl-7")),onClick:P=>{P.stopPropagation(),P.preventDefault(),s(U=>{const B=U.find(A=>A.id===`rowLevel${k}`);return B?B.desc?[]:[{id:`rowLevel${k}`,desc:!0}]:[{id:`rowLevel${k}`,desc:!1}]})},children:[c.jsx("span",{className:"truncate text-xs font-medium",title:E.label||E.name,children:E.label||E.name}),c.jsx(Fo,{className:X("h-3 w-3 flex-shrink-0",((V=r.find(P=>P.id===`rowLevel${k}`))==null?void 0:V.desc)===!1?"hidden group-hover/rowheader:block":"hidden")}),c.jsx(ta,{className:X("h-3 w-3 flex-shrink-0",(($=r.find(P=>P.id===`rowLevel${k}`))==null?void 0:$.desc)===!0?"hidden group-hover/rowheader:block":"hidden")}),c.jsx(ku,{className:X("h-3 w-3 flex-shrink-0",r.find(P=>P.id===`rowLevel${k}`)?"hidden":"hidden group-hover/rowheader:block")})]})]}),M&&c.jsx(Du,{header:M,isResizing:M.column.getIsResizing()})]})},`row-header-corner-${k}`)}):c.jsx(ao,{colSpan:g,rowSpan:p+2,className:"h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-xs",children:""}),c.jsx(ao,{colSpan:b,className:"h-8 whitespace-nowrap border-b bg-muted px-3 py-1 text-xs font-bold",children:c.jsxs("div",{className:"group/pivot-main relative flex items-center",children:[i&&(()=>{var M,T;const E="pivot-main",k=l===E;return c.jsx("div",{className:X("absolute left-0 top-1/2 -translate-y-1/2 overflow-hidden transition-all duration-200",k?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/pivot-main:h-6 group-hover/pivot-main:w-6 group-hover/pivot-main:opacity-100"),children:c.jsx(Vp,{columnName:"Pivot Columns",groupByFields:e.groupByColumns||[],pivotByFields:m,currentAggregation:{rowAggregates:(M=t.config)==null?void 0:M.rowAggregates,columnAggregates:(T=t.config)==null?void 0:T.columnAggregates},onAggregationChange:i,onOpenChange:O=>u(O?E:null)})})})(),c.jsx("div",{className:X("transition-all duration-200",i&&(l==="pivot-main"?"pl-7":"group-hover/pivot-main:pl-7")),children:m.map((E,k)=>c.jsxs("span",{className:"inline-flex items-center",children:[E.label,k<m.length-1&&c.jsx(Go,{className:"mx-1 inline-block h-4 w-4 text-muted-foreground"})]},E.id))})]})},"pivot-hierarchy"),o&&(()=>{var M;const E=(M=n.getHeaderGroups()[0])==null?void 0:M.headers.find(T=>T.column.id==="rowTotal"),k=E==null?void 0:E.getSize();return c.jsx(ao,{"data-column-id":"rowTotal",className:"group/total h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-center text-xs",rowSpan:p+2,style:{width:k,minWidth:k,maxWidth:k,position:"relative",transition:"none"},children:(()=>{const T=n.getColumn("rowTotal");return T?c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs(oe,{variant:"ghost",className:"h-auto flex-shrink-0 p-0 hover:bg-transparent",onClick:()=>{const O=T.getIsSorted();s(O?O==="asc"?[{id:T.id,desc:!0}]:[]:[{id:T.id,desc:!1}])},"aria-label":"Sort Total",children:[c.jsx(Fo,{className:X("mr-1 h-3 w-3",T.getIsSorted()==="asc"?"hidden group-hover/total:block":"hidden")}),c.jsx(ta,{className:X("mr-1 h-3 w-3",T.getIsSorted()==="desc"?"hidden group-hover/total:block":"hidden")}),c.jsx(ku,{className:X("mr-1 h-3 w-3",T.getIsSorted()?"hidden":"hidden group-hover/total:block")})]}),c.jsx("span",{className:"truncate text-xs font-medium",title:"Total",children:"Total"}),E&&c.jsx(Du,{header:E,isResizing:E.column.getIsResizing()})]}):"Total"})()},"pivot-hierarchy-total")})()]},"pivot-hierarchy"),w=[];if(e.columnGroups&&e.columnGroups.length>0){const E=Array.from({length:p},()=>[]);x(e.columnGroups,0,E,[]);for(let k=0;k<p;k++)w.push(c.jsx(fr,{"data-header-type":"pivot-values","data-header-row-index":k+1,"data-repeat-header":"true",children:E[k]},`pivot-row-${k}`))}let C=[];e.columnGroups&&e.columnGroups.length>0?C=y(e.columnGroups,[]):e.columnHeaders.forEach(E=>{var T,O,R,I,L,F;const k=n.getColumn(E),M=(T=n.getHeaderGroups()[0])==null?void 0:T.headers.find(V=>V.column.id===E);C.push(c.jsx(ao,{"data-column-id":E,className:"group/colheader h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-right text-xs last:border-r-0",style:{width:M==null?void 0:M.getSize(),minWidth:M==null?void 0:M.getSize(),maxWidth:M==null?void 0:M.getSize(),position:"relative",transition:"none"},children:k?c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs(oe,{variant:"ghost",className:"h-auto flex-shrink-0 p-0 hover:bg-transparent",onClick:()=>{const V=k.getIsSorted();s(V?V==="asc"?[{id:k.id,desc:!0}]:[]:[{id:k.id,desc:!1}])},"aria-label":`Sort ${((O=e.columnDisplayNames)==null?void 0:O[E])||E}`,children:[c.jsx(Fo,{className:X("mr-1 h-3 w-3",k.getIsSorted()==="asc"?"hidden group-hover/colheader:block":"hidden")}),c.jsx(ta,{className:X("mr-1 h-3 w-3",k.getIsSorted()==="desc"?"hidden group-hover/colheader:block":"hidden")}),c.jsx(ku,{className:X("mr-1 h-3 w-3",k.getIsSorted()?"hidden":"hidden group-hover/colheader:block")})]}),c.jsx("span",{className:"min-w-0 truncate text-xs font-medium",title:((R=e.columnDisplayNames)==null?void 0:R[E])||E,children:((I=e.columnDisplayNames)==null?void 0:I[E])||E}),d&&a&&c.jsx(oe,{variant:"ghost",size:"icon",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover/colheader:opacity-100",onClick:V=>{V.stopPropagation(),a(E)},children:c.jsx(Ju,{className:"h-3 w-3"})}),M&&c.jsx(Du,{header:M,isResizing:M.column.getIsResizing()})]}):c.jsx("span",{className:"block truncate px-2",title:((L=e.columnDisplayNames)==null?void 0:L[E])||E,children:((F=e.columnDisplayNames)==null?void 0:F[E])||E})},E))});const S=c.jsxs(fr,{"data-header-type":"metrics","data-header-row-index":p>0?p+1:0,"data-repeat-header":"true",children:[p===0&&(e.groupByColumns&&e.groupByColumns.length>0?e.groupByColumns.map((E,k)=>{var I,L,F,V;const M=(I=n.getHeaderGroups()[0])==null?void 0:I.headers.find($=>$.column.id===`rowLevel${k}`),T=M==null?void 0:M.getSize(),O=`metric-row-${k}`,R=l===O;return c.jsx(ao,{"data-column-id":`rowLevel${k}`,className:"group/metricrow h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-left text-xs font-medium",style:{width:T,minWidth:T,maxWidth:T,position:"relative",transition:"none"},children:c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs("div",{className:"relative flex min-w-0 items-center",children:[i&&c.jsx("div",{className:X("absolute left-0 top-1/2 -translate-y-1/2 overflow-hidden transition-all duration-200",R?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/metricrow:h-6 group-hover/metricrow:w-6 group-hover/metricrow:opacity-100"),children:c.jsx(Vp,{columnName:E.label||E.name,groupByFields:e.groupByColumns||[],pivotByFields:((L=t.config)==null?void 0:L.pivotByColumns)||[],currentAggregation:{rowAggregates:(F=t.config)==null?void 0:F.rowAggregates,columnAggregates:(V=t.config)==null?void 0:V.columnAggregates},onAggregationChange:i,onOpenChange:$=>u($?O:null)})}),c.jsxs(oe,{variant:"ghost",className:X("flex h-auto min-w-0 items-center gap-1 p-0 transition-all duration-200 hover:bg-transparent",i&&(R?"pl-7":"group-hover/metricrow:pl-7")),onClick:()=>{s($=>{const P=$.find(U=>U.id===`rowLevel${k}`);return P?P.desc===!1?[{id:`rowLevel${k}`,desc:!0}]:[]:[{id:`rowLevel${k}`,desc:!1}]})},children:[c.jsx("span",{className:"truncate text-xs font-medium",title:E.label||E.name,children:E.label||E.name}),(()=>{const $=r.find(P=>P.id===`rowLevel${k}`);return c.jsxs(c.Fragment,{children:[c.jsx(ku,{className:X("h-3 w-3 flex-shrink-0",$?"hidden":"hidden group-hover/metricrow:block")}),c.jsx(ta,{className:X("h-3 w-3 flex-shrink-0",($==null?void 0:$.desc)===!0?"hidden group-hover/metricrow:block":"hidden")}),c.jsx(Fo,{className:X("h-3 w-3 flex-shrink-0",($==null?void 0:$.desc)===!1?"hidden group-hover/metricrow:block":"hidden")})]})})()]})]}),M&&c.jsx(Du,{header:M,isResizing:M.column.getIsResizing()})]})},`row-header-title-${k}`)}):Array.from({length:g}).map((E,k)=>c.jsx(ao,{className:"h-8 whitespace-nowrap border-b border-r bg-muted py-1 text-left text-xs font-medium",children:`Level ${k+1}`},`empty-header-metric-${k}`))),C]},"metric-row");return p>0?[v,...w,S]:[S]},[e,t,n,r,s,o,i,f,l,u,d,a])}}function S4e(e,t,n){var v,w;const r=Q(C=>C.isVisualEditing);Q(C=>C.isDashboardEditing),Q(C=>C.selectedSheetId);const{updateCurrentDashboardCard:s,updateFrame:o}=Gt(),i=Ee(C=>{var S;return(S=C.actions)==null?void 0:S.setCardPreferences}),a=Ee(C=>C.card),l=j.useMemo(()=>{var C,S;return((S=(C=e==null?void 0:e.preferences)==null?void 0:C.tablePrefs)==null?void 0:S.columnSettingsMap)||{}},[(w=(v=e==null?void 0:e.preferences)==null?void 0:v.tablePrefs)==null?void 0:w.columnSettingsMap]),[u,d]=j.useState(!1),[f,h]=j.useState(null),[m,p]=j.useState(Bo()),g=j.useCallback(C=>{h(C);let S=l[C];if(!S){const N=t==null?void 0:t.map(_=>{var E,k;return{[C]:(k=(E=_.cells)==null?void 0:E[C])==null?void 0:k.value}});S=N&&N.length>0?Xg(C,N,n):Bo()}p(S),d(!0)},[l,t,n]),b=j.useCallback(()=>{var C,S;if(f&&m){const N={...l,[f]:m};if(r&&i){const _={...a.preferences,tablePrefs:{...(C=a.preferences)==null?void 0:C.tablePrefs,columnSettingsMap:N}};i(_)}else if(s){const _={...e,preferences:{...e.preferences,tablePrefs:{...(S=e.preferences)==null?void 0:S.tablePrefs,columnSettingsMap:N}}};s(_)}}d(!1)},[f,m,l,r,i,a,s,e]),x=j.useCallback(()=>{f&&p(Bo())},[f]),y=j.useCallback(()=>{var C,S;if(r&&i){const N={...a.preferences,tablePrefs:{...(C=a.preferences)==null?void 0:C.tablePrefs,columnSettingsMap:{}}};i(N)}else if(s){const N={...e,preferences:{...e.preferences,tablePrefs:{...(S=e.preferences)==null?void 0:S.tablePrefs,columnSettingsMap:{}}}};s(N)}d(!1)},[r,i,a,s,e]);return{columnSettings:l,columnSettingsOpen:u,activeColumnId:f,tempColumnSettings:m,isVisualEditing:r,openColumnSettings:g,applyColumnSettings:b,resetColumnSettings:x,resetAllColumnSettings:y,setColumnSettingsOpen:d,setTempColumnSettings:p}}function C4e({table:e,data:t,columns:n,subtotalColumnKeys:r,grandTotalColumnKeys:s,isTablePrintDisplayMode:o=!1,columnSettings:i,shouldVirtualizeRows:a=!1,virtualRows:l,paddingTop:u=0,paddingBottom:d=0,measureElement:f}){var x;const h=e.getRowModel().rows,m=((x=t.groupByColumns)==null?void 0:x.length)||1,g=a&&l&&l.length>0?l:h,b=n.length||1;return h!=null&&h.length?c.jsxs(c.Fragment,{children:[a&&u>0&&c.jsx(fr,{"aria-hidden":!0,className:"pointer-events-none border-none",children:c.jsx(yn,{colSpan:b,style:{height:u,padding:0,border:"none"}})}),g.map((y,v)=>{const w=a?y.index:v,C=a?h[w]:y;if(!C)return null;const S=C.original,N=e.getRowModel().rows,_=w===N.length-1;return c.jsx(fr,{ref:a&&f?E=>f(E):void 0,className:X("h-8 border-b-0",S.isSubtotal&&"border-t border-t-border/50 bg-muted/70 font-medium"),"data-row-type":S.isSubtotal?"subtotal":"data","data-row-index":w,...S.isSubtotal&&{"data-subtotal-level":S.subtotalLevel},children:C.getVisibleCells().map(E=>{var O;const k=E.column.id;if(k.startsWith("rowLevel")){const R=parseInt(k.replace("rowLevel",""));if(S.isSubtotal&&S.subtotalLevel){const L=((O=t.groupByColumns)==null?void 0:O.findIndex(F=>(F.alias||F.name)===S.subtotalLevel))??-1;return R===L?c.jsx(yn,{colSpan:o?1:m-R,className:X("h-8 whitespace-nowrap border-r px-3 py-1 text-xs font-medium",!_&&"border-b"),children:Gs(E.column.columnDef.cell,E.getContext())},E.id):R<L?c.jsx(yn,{className:X("h-8 whitespace-nowrap border-r px-3 py-1 text-xs font-medium",!_&&"border-b"),children:Gs(E.column.columnDef.cell,E.getContext())},E.id):o?c.jsx(yn,{className:X("h-8 whitespace-nowrap border-r px-3 py-1 text-xs",!_&&"border-b")},E.id):null}if(!a&&!o&&w>0)for(let L=w-1;L>=0;L--){const F=N[L].original;if(F.isSubtotal||F.isGrandTotal)break;let V=!0;for(let $=0;$<=R;$++)if(S.fieldValues[$]!==F.fieldValues[$]){V=!1;break}if(V)return null}let I=1;if(!a&&!o)for(let L=w+1;L<N.length;L++){const F=N[L].original;if(F.isSubtotal||F.isGrandTotal)break;let V=!0;for(let $=0;$<=R;$++)if(S.fieldValues[$]!==F.fieldValues[$]){V=!1;break}if(V)I++;else break}return c.jsx(yn,{rowSpan:a?void 0:I,className:X("h-8 whitespace-nowrap border-r px-3 py-1 text-xs",!_&&"border-b"),children:Gs(E.column.columnDef.cell,E.getContext())},E.id)}const M=s.has(k),T=r.has(k);return c.jsx(yn,{"data-column-id":k,className:X("h-8 border-r px-3 py-1 text-xs last:border-r-0",!_&&"border-b",M?"bg-muted/50":T?"bg-muted/30":void 0),style:{width:E.column.getSize(),minWidth:E.column.getSize(),maxWidth:E.column.getSize(),transition:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.isSubtotal&&(i!=null&&i[k])?ob(E.getValue(),i[k]):Gs(E.column.columnDef.cell,E.getContext())},E.id)})},C.id)}),a&&d>0&&c.jsx(fr,{"aria-hidden":!0,className:"pointer-events-none border-none",children:c.jsx(yn,{colSpan:b,style:{height:d,padding:0,border:"none"}})})]}):c.jsx(fr,{className:"h-8",children:c.jsx(yn,{colSpan:n.length,className:"text-center",children:"No results."})})}function Wo({value:e,displayTitle:t=!0,onSave:n,placeholder:r,inputClassName:s,displayClassName:o,isEditable:i=!0,isPending:a=!1}){const[l,u]=j.useState(!1),[d,f]=j.useState(e||""),h=()=>{u(!1),d!==e&&n(d)},m=p=>{p.key==="Enter"?(u(!1),n(d)):p.key==="Escape"&&(u(!1),f(e||""))};return l?c.jsx("div",{className:"flex",children:c.jsx("input",{type:"text",value:d,onChange:p=>f(p.target.value),onBlur:h,onKeyDown:m,onMouseDown:p=>p.stopPropagation(),className:X("w-full border-b border-dashed focus:border-primary focus:outline-none",s),autoFocus:!0})}):c.jsxs("div",{className:X("relative cursor-pointer truncate",o,{"cursor-default":!i,"hover:text-primary":i}),onClick:()=>{!i||a||(u(!0),f(e||""))},title:t?e||r:void 0,children:[c.jsx("div",{className:"flex items-center justify-between gap-2",children:c.jsx("span",{className:X("truncate",{"text-muted-foreground":a}),children:e||c.jsx("span",{className:"text-muted-foreground",children:r})})}),a&&c.jsx("div",{className:"absolute inset-0 animate-pulse rounded bg-gradient-to-r from-transparent via-blue-100/30 to-transparent"})]})}function N4e({grandTotalRows:e,data:t,card:n,table:r,showRowTotals:s,columnSettings:o,onAggregationLabelChange:i}){return e.length===0?null:c.jsx(c.Fragment,{children:e.map((a,l)=>{var u;return c.jsxs(fr,{className:"h-8 font-semibold","data-row-type":"grandtotal","data-grandtotal":"true","data-grandtotal-index":l,children:[c.jsx(yn,{colSpan:((u=t.groupByColumns)==null?void 0:u.length)||1,className:"h-8 whitespace-nowrap border-r px-3 py-1 text-xs font-semibold",children:i?c.jsx(Wo,{value:(()=>{var h,m,p;const d=a.aggregateFunction||"SUM";return((p=(m=(h=n.config)==null?void 0:h.rowAggregates)==null?void 0:m.find(g=>g.function===d&&g.groupLevel==="ALL"))==null?void 0:p.label)||a.fieldValues[0]})(),placeholder:a.fieldValues[0],onSave:d=>{const f=a.aggregateFunction||"SUM";i({type:"row",level:"ALL",function:f,label:d})},displayClassName:"text-right"}):a.fieldValues[0]}),t.columnHeaders.map(d=>{var h,m;const f=(h=r.getHeaderGroups()[0])==null?void 0:h.headers.find(p=>p.column.id===d);return c.jsx(yn,{"data-column-id":d,className:"h-8 border-r px-3 py-1 text-right text-xs last:border-r-0",style:{width:f==null?void 0:f.getSize(),minWidth:f==null?void 0:f.getSize(),maxWidth:f==null?void 0:f.getSize(),transition:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ob((m=a.cells[d])==null?void 0:m.value,o==null?void 0:o[d])},d)}),s&&(()=>{var h;const d=(h=r.getHeaderGroups()[0])==null?void 0:h.headers.find(m=>m.column.id==="rowTotal"),f=d==null?void 0:d.getSize();return c.jsx(yn,{className:"h-8 px-3 py-1 text-right text-xs font-medium","data-column-id":"rowTotal",style:{width:f,minWidth:f,maxWidth:f,transition:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ob(Bq(a,t.columnHeaders))})})()]},a.id)})})}function j4e({groupByColumns:e,numRowLevels:t,onAggregationLabelChange:n,isTablePrintDisplayMode:r=!1}){const s=[];return e&&e.length>0?e.forEach((o,i)=>{s.push({id:`rowLevel${i}`,header:()=>c.jsx("div",{className:"group border border-border px-3 py-1 text-left font-medium text-muted-foreground",children:c.jsx("div",{className:"flex items-center gap-1",children:c.jsx("span",{className:"whitespace-nowrap",children:o.label||o.name})})}),accessorFn:a=>a.fieldValues[i],cell:({row:a,table:l})=>{const u=a.original;if(u.isSubtotal&&u.subtotalLevel){const m=(e==null?void 0:e.findIndex(p=>(p.alias||p.name)===u.subtotalLevel))??-1;if(i===m){const p=u.fieldValues[i];return c.jsx("div",{className:"whitespace-nowrap px-3 py-1 align-top text-xs font-medium",style:{gridColumn:`span ${t-i}`},children:p.includes(" Total")&&n?c.jsx(Wo,{value:p,placeholder:p,onSave:g=>{const b=u.aggregateFunction||"SUM";if(u.subtotalLevel&&e){const x=e.find(y=>(y.alias||y.name)===u.subtotalLevel);x&&n({type:"row",level:x.id,function:b,label:g})}},displayClassName:"text-left"}):p})}else if(i<m)return c.jsx("div",{className:"whitespace-nowrap px-3 py-1 align-top text-xs font-medium",children:u.fieldValues[i]});return r?c.jsx("div",{className:"whitespace-nowrap px-3 py-1 align-top text-xs"}):null}const d=l.getRowModel().rows,f=d.findIndex(m=>m.id===a.id);if(!r&&f>0)for(let m=f-1;m>=0;m--){const p=d[m].original;if(p.isSubtotal||p.isGrandTotal)break;let g=!0;for(let b=0;b<=i;b++)if(u.fieldValues[b]!==p.fieldValues[b]){g=!1;break}if(g)return null}let h=1;if(!r)for(let m=f+1;m<d.length;m++){const p=d[m].original;if(p.isSubtotal||p.isGrandTotal)break;let g=!0;for(let b=0;b<=i;b++)if(u.fieldValues[b]!==p.fieldValues[b]){g=!1;break}if(g)h++;else break}return c.jsx("div",{className:"whitespace-nowrap px-0 py-1 align-top text-xs",style:{gridRow:r?void 0:`span ${h}`},children:u.fieldValues[i]})}})}):s.push({id:"rowHeader",header:()=>c.jsx("div",{className:"px-3 py-1 text-left font-medium",children:"Row"}),accessorFn:o=>o.rowKey,cell:({getValue:o})=>c.jsx("div",{className:"min-w-[150px] max-w-[300px] border-x border-y border-border px-3 py-1",children:String(o())})}),s}function k4e({columnHeaders:e,columnDisplayNames:t,setSorting:n,columnSettings:r,contextTimezone:s,browserTimezone:o}){return e.map(i=>({id:i,accessorFn:a=>{var l;return(l=a.cells[i])==null?void 0:l.value},header:({column:a})=>{const l=(t==null?void 0:t[i])||i;return c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsx(oe,{variant:"ghost",className:"h-auto p-0 hover:bg-transparent",onClick:()=>{const u=a.getIsSorted();n(u?u==="asc"?[{id:a.id,desc:!0}]:[]:[{id:a.id,desc:!1}])},"aria-label":`Sort ${l}`,children:a.getIsSorted()==="asc"?c.jsx(Fo,{className:"mr-1 h-3 w-3"}):a.getIsSorted()==="desc"?c.jsx(ta,{className:"mr-1 h-3 w-3"}):c.jsx(ku,{className:"mr-1 h-3 w-3 opacity-0 group-hover:opacity-100"})}),c.jsx("span",{className:"text-xs font-medium",children:l})]})},cell:({getValue:a})=>{const l=a(),u=r==null?void 0:r[i],d=(u==null?void 0:u.textAlign)||"right",f=d==="left"?"text-left":d==="center"?"text-center":"text-right";return c.jsx("div",{className:`text-xs ${f}`,children:ob(l,u,s,o)})}}))}function E4e({columnHeaders:e,setSorting:t}){return{id:"rowTotal",header:({column:n})=>c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsx(oe,{variant:"ghost",className:"h-auto p-0 hover:bg-transparent",onClick:()=>{const r=n.getIsSorted();t(r?r==="asc"?[{id:n.id,desc:!0}]:[]:[{id:n.id,desc:!1}])},"aria-label":"Sort Total",children:n.getIsSorted()==="asc"?c.jsx(Fo,{className:"mr-1 h-3 w-3"}):n.getIsSorted()==="desc"?c.jsx(ta,{className:"mr-1 h-3 w-3"}):c.jsx(ku,{className:"mr-1 h-3 w-3 opacity-0 group-hover:opacity-100"})}),c.jsx("span",{className:"text-xs font-medium",children:"Total"})]}),cell:({row:n})=>{const r=n.original,s=Bq(r,e);return c.jsx("div",{className:"text-right text-xs font-medium",children:ob(s)})}}}function Nx({data:e,card:t,options:n={},onAggregationChange:r,onAggregationLabelChange:s}){var W,H,G;const o=Q(K=>K.themeStyle),{displayPreferences:i,shouldShowElement:a}=Uc(),l=i.mode==="table-print",u=j.useRef(null),d=n.showRowTotals??!1,{columnSizing:f,onColumnSizingChange:h}=XT({card:t}),{subtotalColumnKeys:m,grandTotalColumnKeys:p}=j.useMemo(()=>rEe(e.columnSubtotalMeta),[e.columnSubtotalMeta]),{tableData:g,grandTotalRows:b}=j.useMemo(()=>OT(e),[e]),{sorting:x,setSorting:y,sortedTableData:v}=x4e(g,e),{columnSettings:w,columnSettingsOpen:C,activeColumnId:S,tempColumnSettings:N,openColumnSettings:_,applyColumnSettings:E,resetColumnSettings:k,resetAllColumnSettings:M,setColumnSettingsOpen:T,setTempColumnSettings:O}=S4e(t,v,e.columnMetadata),R={...n.pagination},I=m4e(R,v.length),L=j.useMemo(()=>{var se;const K=[],te=((se=e.groupByColumns)==null?void 0:se.length)||1,Z=j4e({groupByColumns:e.groupByColumns,numRowLevels:te,onAggregationLabelChange:s,isTablePrintDisplayMode:l});K.push(...Z);const ee=k4e({columnHeaders:e.columnHeaders,columnDisplayNames:e.columnDisplayNames,setSorting:y,columnSettings:w,contextTimezone:void 0,browserTimezone:typeof window<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0});if(K.push(...ee),d){const ce=E4e({columnHeaders:e.columnHeaders,setSorting:y});K.push(ce)}return K},[e,d,s,y,l,w]),F=GT({data:v,columns:L,state:{sorting:x,columnSizing:f,pagination:{pageIndex:I.pageIndex,pageSize:I.pageSize}},onSortingChange:y,onPaginationChange:void 0,getCoreRowModel:qT(),getPaginationRowModel:!I.isServerSidePagination&&!I.isTablePrintDisplayMode?YT():void 0,manualPagination:I.isServerSidePagination||I.isTablePrintDisplayMode,manualSorting:!0,pageCount:I.pageCount,enableColumnResizing:!0,columnResizeMode:"onChange",onColumnSizingChange:h}),V=F.getRowModel().rows,P=!l&&V.length>75,U=QT({count:P?V.length:0,getScrollElement:()=>u.current,estimateSize:()=>32,overscan:10}),B=P?U.getVirtualItems():[],A=P&&B.length>0?B[0].start:0,Y=P&&B.length>0?U.getTotalSize()-B[B.length-1].end:0,{buildColumnHeaderRows:z}=w4e({data:e,card:t,table:F,sorting:x,setSorting:y,showRowTotals:d,onAggregationChange:r,onOpenColumnSettings:_}),q=z();return c.jsxs("div",{className:"flex h-full w-full flex-col gap-4",children:[c.jsxs(Cl,{ref:u,style:{borderRadius:o==null?void 0:o.cardBorderRadius},className:"relative h-full rounded-none border",onMouseDown:K=>K.stopPropagation(),children:[c.jsxs("table",{className:"w-full border-separate border-spacing-0 bg-background text-sm",onMouseDown:K=>K.stopPropagation(),"data-pivot-table":"true","data-row-levels":((W=e.groupByColumns)==null?void 0:W.length)||1,"data-pivot-levels":e.columnGroups&&((G=(H=t.config)==null?void 0:H.pivotByColumns)==null?void 0:G.length)||0,children:[c.jsx(ax,{className:"sticky top-0 z-20 bg-background",children:q}),c.jsx(Yh,{children:c.jsx(C4e,{table:F,data:e,columns:L,subtotalColumnKeys:m,grandTotalColumnKeys:p,isTablePrintDisplayMode:l,columnSettings:w,shouldVirtualizeRows:P,virtualRows:B,paddingTop:A,paddingBottom:Y,measureElement:P?U.measureElement:void 0})}),b.length>0&&c.jsx("tfoot",{className:"sticky bottom-0 z-10 border-t-2 border-t-border bg-muted","data-grandtotal":"true",children:c.jsx(N4e,{grandTotalRows:b,data:e,card:t,table:F,showRowTotals:d,columnSettings:w,onAggregationLabelChange:s})})]}),c.jsx(Zo,{orientation:"horizontal"}),c.jsx(Zo,{orientation:"vertical"})]}),I.showPagination&&c.jsx(KT,{totalColumns:L.length,pageCount:I.pageCount||F.getPageCount(),pageIndex:I.pageIndex,pageSize:I.pageSize,rowCount:I.totalCount,selectedRowCount:0,setPageIndex:I.setPageIndex,setPageSize:I.setPageSize,canPreviousPage:I.canPreviousPage,canNextPage:I.canNextPage,previousPage:I.previousPage,nextPage:I.nextPage,onClearSelection:()=>{}}),S&&c.jsx(ZT,{column:F.getColumn(S)||null,settings:N,onSettingsChange:O,onApply:E,onReset:k,onResetAll:M,open:C,onOpenChange:T,tableType:"pivot"})]})}function _4e({isOpen:e,onClose:t,frame:n,card:r,data:s}){var _;const[o,i]=j.useState(!1),a=Q(E=>E.isDownloadingPdf),{isError:l,isLoading:u,isFetching:d,cfg:f,data:h,handleDatapointClick:m,pagination:p}=ex(r),{customCards:g,placeholders:b}=Ge(),x=zm(r,h),y=j.useMemo(()=>(h==null?void 0:h.records)||[],[h==null?void 0:h.records]),v=()=>{var k,M,T,O,R,I,L;const E=h||s;if(E!=null&&E.records&&E.records.length>0)if((r==null?void 0:r.type)==="aggregateTable"){const F=E.records.find(P=>P.isGrandTotal),V=E.records.filter(P=>!P.isGrandTotal),$=Fq(V,F,E.groupByColumns||[],E.pivotSchema||[],r,(M=(k=r==null?void 0:r.preferences)==null?void 0:k.tablePrefs)==null?void 0:M.columnSettingsMap);sw($,`${(r==null?void 0:r.title)||"export"}.csv`)}else if((r==null?void 0:r.type)==="pivotTable"&&x)Vq(x.data,r,`${(r==null?void 0:r.title)||"export"}.csv`,{includeHeaders:!0,includeSubtotals:!0,includeGrandTotal:!0,showRowTotals:(T=x.options)==null?void 0:T.showRowTotals});else if((r==null?void 0:r.type)==="table"){const F=((R=(O=r==null?void 0:r.preferences)==null?void 0:O.tablePrefs)==null?void 0:R.columnSettingsMap)||{},V=((L=(I=r==null?void 0:r.preferences)==null?void 0:I.tablePrefs)==null?void 0:L.columnVisibility)||{},P=Object.keys(E.records[0]||{}).filter(U=>V[U]!==!1);kEe(E.records,F,P,`${(r==null?void 0:r.title)||"export"}.csv`,void 0,Intl.DateTimeFormat().resolvedOptions().timeZone)}else{const F=[],V=Object.keys(E.records[0]);F.push(V.join(","));for(const P of E.records){const U=V.map(B=>`"${(""+P[B]).replace(/"/g,'""')}"`);F.push(U.join(","))}const $=F.join(`
973
+ `)),[]});var RFe=(e=>(e[e.None=0]="None",e[e.Closed=1]="Closed",e[e.Enter=2]="Enter",e[e.Leave=4]="Leave",e))(RFe||{});function IFe(e){let t={};for(let n in e)e[n]===!0&&(t[`data-${n}`]="");return t}function AFe(e,t,n,r){let[s,o]=j.useState(n),{hasFlag:i,addFlag:a,removeFlag:l}=TFe(e&&s?3:0),u=j.useRef(!1),d=j.useRef(!1),f=vx();return Gn(()=>{var h;if(e){if(n&&o(!0),!t){n&&a(3);return}return(h=void 0)==null||h.call(r,n),PFe(t,{inFlight:u,prepare(){d.current?d.current=!1:d.current=u.current,u.current=!0,!d.current&&(n?(a(3),l(4)):(a(4),l(2)))},run(){d.current?n?(l(3),a(4)):(l(4),a(3)):n?l(1):a(1)},done(){var m;d.current&&typeof t.getAnimations=="function"&&t.getAnimations().length>0||(u.current=!1,l(7),n||o(!1),(m=void 0)==null||m.call(r,n))}})}},[e,n,t,f]),e?[s,{closed:i(1),enter:i(2),leave:i(4),transition:i(2)||i(4)}]:[n,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}function PFe(e,{prepare:t,run:n,done:r,inFlight:s}){let o=xa();return FFe(e,{prepare:t,inFlight:s}),o.nextFrame(()=>{n(),o.requestAnimationFrame(()=>{o.add(OFe(e,r))})}),o.dispose}function OFe(e,t){var n,r;let s=xa();if(!e)return s.dispose;let o=!1;s.add(()=>{o=!0});let i=(r=(n=e.getAnimations)==null?void 0:n.call(e).filter(a=>a instanceof CSSTransition))!=null?r:[];return i.length===0?(t(),s.dispose):(Promise.allSettled(i.map(a=>a.finished)).then(()=>{o||t()}),s.dispose)}function FFe(e,{inFlight:t,prepare:n}){if(t!=null&&t.current){n();return}let r=e.style.transition;e.style.transition="none",n(),e.offsetHeight,e.style.transition=r}function $Fe(e,{container:t,accept:n,walk:r}){let s=j.useRef(n),o=j.useRef(r);j.useEffect(()=>{s.current=n,o.current=r},[n,r]),Gn(()=>{if(!t||!e)return;let i=yx(t);if(!i)return;let a=s.current,l=o.current,u=Object.assign(f=>a(f),{acceptNode:a}),d=i.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,u,!1);for(;d.nextNode();)l(d.currentNode)},[t,e,s,o])}function r3(e,t){let n=j.useRef([]),r=Ct(e);j.useEffect(()=>{let s=[...n.current];for(let[o,i]of t.entries())if(n.current[o]!==i){let a=r(t,s);return n.current=t,a}},[r,...t])}function LFe(){const e=navigator.userAgentData;return e&&Array.isArray(e.brands)?e.brands.map(t=>{let{brand:n,version:r}=t;return n+"/"+r}).join(" "):navigator.userAgent}const MK={...D},zFe=MK.useInsertionEffect,BFe=zFe||(e=>e());function TK(e){const t=D.useRef(()=>{if(process.env.NODE_ENV!=="production")throw new Error("Cannot call an event handler while rendering.")});return BFe(()=>{t.current=e}),D.useCallback(function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];return t.current==null?void 0:t.current(...r)},[])}var RE=typeof document<"u"?j.useLayoutEffect:j.useEffect;let s3=!1,VFe=0;const o3=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+VFe++;function HFe(){const[e,t]=D.useState(()=>s3?o3():void 0);return RE(()=>{e==null&&t(o3())},[]),D.useEffect(()=>{s3=!0},[]),e}const UFe=MK.useId,WFe=UFe||HFe;let nb;process.env.NODE_ENV!=="production"&&(nb=new Set);function qFe(){for(var e,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];const s="Floating UI: "+n.join(" ");if(!((e=nb)!=null&&e.has(s))){var o;(o=nb)==null||o.add(s),console.warn(s)}}function YFe(){for(var e,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];const s="Floating UI: "+n.join(" ");if(!((e=nb)!=null&&e.has(s))){var o;(o=nb)==null||o.add(s),console.error(s)}}function GFe(){const e=new Map;return{emit(t,n){var r;(r=e.get(t))==null||r.forEach(s=>s(n))},on(t,n){e.set(t,[...e.get(t)||[],n])},off(t,n){var r;e.set(t,((r=e.get(t))==null?void 0:r.filter(s=>s!==n))||[])}}}const KFe=D.createContext(null),ZFe=D.createContext(null),XFe=()=>{var e;return((e=D.useContext(KFe))==null?void 0:e.id)||null},QFe=()=>D.useContext(ZFe),JFe="data-floating-ui-focusable";function e5e(e){const{open:t=!1,onOpenChange:n,elements:r}=e,s=WFe(),o=D.useRef({}),[i]=D.useState(()=>GFe()),a=XFe()!=null;if(process.env.NODE_ENV!=="production"){const m=r.reference;m&&!es(m)&&YFe("Cannot pass a virtual element to the `elements.reference` option,","as it must be a real DOM element. Use `refs.setPositionReference()`","instead.")}const[l,u]=D.useState(r.reference),d=TK((m,p,g)=>{o.current.openEvent=m?p:void 0,i.emit("openchange",{open:m,event:p,reason:g,nested:a}),n==null||n(m,p,g)}),f=D.useMemo(()=>({setPositionReference:u}),[]),h=D.useMemo(()=>({reference:l||r.reference||null,floating:r.floating||null,domReference:r.reference}),[l,r.reference,r.floating]);return D.useMemo(()=>({dataRef:o,open:t,onOpenChange:d,elements:h,events:i,floatingId:s,refs:f}),[t,d,h,i,s,f])}function t5e(e){e===void 0&&(e={});const{nodeId:t}=e,n=e5e({...e,elements:{reference:null,floating:null,...e.elements}}),r=e.rootContext||n,s=r.elements,[o,i]=D.useState(null),[a,l]=D.useState(null),d=(s==null?void 0:s.domReference)||o,f=D.useRef(null),h=QFe();RE(()=>{d&&(f.current=d)},[d]);const m=fz({...e,elements:{...s,...a&&{reference:a}}}),p=D.useCallback(v=>{const w=es(v)?{getBoundingClientRect:()=>v.getBoundingClientRect(),contextElement:v}:v;l(w),m.refs.setReference(w)},[m.refs]),g=D.useCallback(v=>{(es(v)||v===null)&&(f.current=v,i(v)),(es(m.refs.reference.current)||m.refs.reference.current===null||v!==null&&!es(v))&&m.refs.setReference(v)},[m.refs]),b=D.useMemo(()=>({...m.refs,setReference:g,setPositionReference:p,domReference:f}),[m.refs,g,p]),x=D.useMemo(()=>({...m.elements,domReference:d}),[m.elements,d]),y=D.useMemo(()=>({...m,...r,refs:b,elements:x,nodeId:t}),[m,b,x,t,r]);return RE(()=>{r.dataRef.current.floatingContext=y;const v=h==null?void 0:h.nodesRef.current.find(w=>w.id===t);v&&(v.context=y)}),D.useMemo(()=>({...m,context:y,refs:b,elements:x}),[m,b,x,y])}const i3="active",a3="selected";function wj(e,t,n){const r=new Map,s=n==="item";let o=e;if(s&&e){const{[i3]:i,[a3]:a,...l}=e;o=l}return{...n==="floating"&&{tabIndex:-1,[JFe]:""},...o,...t.map(i=>{const a=i?i[n]:null;return typeof a=="function"?e?a(e):null:a}).concat(e).reduce((i,a)=>(a&&Object.entries(a).forEach(l=>{let[u,d]=l;if(!(s&&[i3,a3].includes(u)))if(u.indexOf("on")===0){if(r.has(u)||r.set(u,[]),typeof d=="function"){var f;(f=r.get(u))==null||f.push(d),i[u]=function(){for(var h,m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];return(h=r.get(u))==null?void 0:h.map(b=>b(...p)).find(b=>b!==void 0)}}}else i[u]=d}),i),{})}}function n5e(e){e===void 0&&(e=[]);const t=e.map(a=>a==null?void 0:a.reference),n=e.map(a=>a==null?void 0:a.floating),r=e.map(a=>a==null?void 0:a.item),s=D.useCallback(a=>wj(a,e,"reference"),t),o=D.useCallback(a=>wj(a,e,"floating"),n),i=D.useCallback(a=>wj(a,e,"item"),r);return D.useMemo(()=>({getReferenceProps:s,getFloatingProps:o,getItemProps:i}),[s,o,i])}function l3(e,t){return{...e,rects:{...e.rects,floating:{...e.rects.floating,height:t}}}}const r5e=e=>({name:"inner",options:e,async fn(t){const{listRef:n,overflowRef:r,onFallbackChange:s,offset:o=0,index:i=0,minItemsVisible:a=4,referenceOverflowThreshold:l=0,scrollRef:u,...d}=ha(e,t),{rects:f,elements:{floating:h}}=t,m=n.current[i],p=(u==null?void 0:u.current)||h,g=h.clientTop||p.clientTop,b=h.clientTop!==0,x=p.clientTop!==0,y=h===p;if(process.env.NODE_ENV!=="production"&&(t.placement.startsWith("bottom")||qFe('`placement` side must be "bottom" when using the `inner`',"middleware.")),!m)return{};const v={...t,...await CD(-m.offsetTop-h.clientTop-f.reference.height/2-m.offsetHeight/2-o).fn(t)},w=await BC(l3(v,p.scrollHeight+g+h.clientTop),d),C=await BC(v,{...d,elementContext:"reference"}),S=Jr(0,w.top),N=v.y+S,k=(p.scrollHeight>p.clientHeight?M=>M:Ag)(Jr(0,p.scrollHeight+(b&&y||x?g*2:0)-S-Jr(0,w.bottom)));if(p.style.maxHeight=k+"px",p.scrollTop=S,s){const M=p.offsetHeight<m.offsetHeight*pl(a,n.current.length)-1||C.top>=-l||C.bottom>=-l;wc.flushSync(()=>s(M))}return r&&(r.current=await BC(l3({...v,y:N},p.offsetHeight+g+h.clientTop),d)),{y:N}}});function s5e(e,t){const{open:n,elements:r}=e,{enabled:s=!0,overflowRef:o,scrollRef:i,onChange:a}=t,l=TK(a),u=D.useRef(!1),d=D.useRef(null),f=D.useRef(null);D.useEffect(()=>{if(!s)return;function m(g){if(g.ctrlKey||!p||o.current==null)return;const b=g.deltaY,x=o.current.top>=-.5,y=o.current.bottom>=-.5,v=p.scrollHeight-p.clientHeight,w=b<0?-1:1,C=b<0?"max":"min";p.scrollHeight<=p.clientHeight||(!x&&b>0||!y&&b<0?(g.preventDefault(),wc.flushSync(()=>{l(S=>S+Math[C](b,v*w))})):/firefox/i.test(LFe())&&(p.scrollTop+=b))}const p=(i==null?void 0:i.current)||r.floating;if(n&&p)return p.addEventListener("wheel",m),requestAnimationFrame(()=>{d.current=p.scrollTop,o.current!=null&&(f.current={...o.current})}),()=>{d.current=null,f.current=null,p.removeEventListener("wheel",m)}},[s,n,r.floating,o,i,l]);const h=D.useMemo(()=>({onKeyDown(){u.current=!0},onWheel(){u.current=!1},onPointerMove(){u.current=!1},onScroll(){const m=(i==null?void 0:i.current)||r.floating;if(!(!o.current||!m||!u.current)){if(d.current!==null){const p=m.scrollTop-d.current;(o.current.bottom<-.5&&p<-1||o.current.top<-.5&&p>1)&&wc.flushSync(()=>l(g=>g+p))}requestAnimationFrame(()=>{d.current=m.scrollTop})}}}),[r.floating,l,o,i]);return D.useMemo(()=>s?{floating:h}:{},[s,h])}let wx=j.createContext({styles:void 0,setReference:()=>{},setFloating:()=>{},getReferenceProps:()=>({}),getFloatingProps:()=>({}),slot:{}});wx.displayName="FloatingContext";let CR=j.createContext(null);CR.displayName="PlacementContext";function o5e(e){return j.useMemo(()=>e?typeof e=="string"?{to:e}:e:null,[e])}function i5e(){return j.useContext(wx).setReference}function a5e(){let{getFloatingProps:e,slot:t}=j.useContext(wx);return j.useCallback((...n)=>Object.assign({},e(...n),{"data-anchor":t.anchor}),[e,t])}function l5e(e=null){e===!1&&(e=null),typeof e=="string"&&(e={to:e});let t=j.useContext(CR),n=j.useMemo(()=>e,[JSON.stringify(e,(s,o)=>{var i;return(i=o==null?void 0:o.outerHTML)!=null?i:o})]);Gn(()=>{t==null||t(n??null)},[t,n]);let r=j.useContext(wx);return j.useMemo(()=>[r.setFloating,e?r.styles:{}],[r.setFloating,e,r.styles])}let c3=4;function c5e({children:e,enabled:t=!0}){let[n,r]=j.useState(null),[s,o]=j.useState(0),i=j.useRef(null),[a,l]=j.useState(null);u5e(a);let u=t&&n!==null&&a!==null,{to:d="bottom",gap:f=0,offset:h=0,padding:m=0,inner:p}=d5e(n,a),[g,b="center"]=d.split(" ");Gn(()=>{u&&o(0)},[u]);let{refs:x,floatingStyles:y,context:v}=t5e({open:u,placement:g==="selection"?b==="center"?"bottom":`bottom-${b}`:b==="center"?`${g}`:`${g}-${b}`,strategy:"absolute",transform:!1,middleware:[CD({mainAxis:g==="selection"?0:f,crossAxis:h}),hz({padding:m}),g!=="selection"&&mz({padding:m}),g==="selection"&&p?r5e({...p,padding:m,overflowRef:i,offset:s,minItemsVisible:c3,referenceOverflowThreshold:m,onFallbackChange(M){var T,O;if(!M)return;let R=v.elements.floating;if(!R)return;let I=parseFloat(getComputedStyle(R).scrollPaddingBottom)||0,L=Math.min(c3,R.childElementCount),F=0,V=0;for(let $ of(O=(T=v.elements.floating)==null?void 0:T.childNodes)!=null?O:[])if($ instanceof HTMLElement){let P=$.offsetTop,U=P+$.clientHeight+I,B=R.scrollTop,A=B+R.clientHeight;if(P>=B&&U<=A)L--;else{V=Math.max(0,Math.min(U,A)-Math.max(P,B)),F=$.clientHeight;break}}L>=1&&o($=>{let P=F*L-V+I;return $>=P?$:P})}}):null,pz({padding:m,apply({availableWidth:M,availableHeight:T,elements:O}){Object.assign(O.floating.style,{overflow:"auto",maxWidth:`${M}px`,maxHeight:`min(var(--anchor-max-height, 100vh), ${T}px)`})}})].filter(Boolean),whileElementsMounted:uz}),[w=g,C=b]=v.placement.split("-");g==="selection"&&(w="selection");let S=j.useMemo(()=>({anchor:[w,C].filter(Boolean).join(" ")}),[w,C]),N=s5e(v,{overflowRef:i,onChange:o}),{getReferenceProps:_,getFloatingProps:E}=n5e([N]),k=Ct(M=>{l(M),x.setFloating(M)});return D.createElement(CR.Provider,{value:r},D.createElement(wx.Provider,{value:{setFloating:k,setReference:x.setReference,styles:y,getReferenceProps:_,getFloatingProps:E,slot:S}},e))}function u5e(e){Gn(()=>{if(!e)return;let t=new MutationObserver(()=>{let n=window.getComputedStyle(e).maxHeight,r=parseFloat(n);if(isNaN(r))return;let s=parseInt(n);isNaN(s)||r!==s&&(e.style.maxHeight=`${Math.ceil(r)}px`)});return t.observe(e,{attributes:!0,attributeFilter:["style"]}),()=>{t.disconnect()}},[e])}function d5e(e,t){var n,r,s;let o=Sj((n=e==null?void 0:e.gap)!=null?n:"var(--anchor-gap, 0)",t),i=Sj((r=e==null?void 0:e.offset)!=null?r:"var(--anchor-offset, 0)",t),a=Sj((s=e==null?void 0:e.padding)!=null?s:"var(--anchor-padding, 0)",t);return{...e,gap:o,offset:i,padding:a}}function Sj(e,t,n=void 0){let r=vx(),s=Ct((l,u)=>{if(l==null)return[n,null];if(typeof l=="number")return[l,null];if(typeof l=="string"){if(!u)return[n,null];let d=u3(l,u);return[d,f=>{let h=RK(l);{let m=h.map(p=>window.getComputedStyle(u).getPropertyValue(p));r.requestAnimationFrame(function p(){r.nextFrame(p);let g=!1;for(let[x,y]of h.entries()){let v=window.getComputedStyle(u).getPropertyValue(y);if(m[x]!==v){m[x]=v,g=!0;break}}if(!g)return;let b=u3(l,u);d!==b&&(f(b),d=b)})}return r.dispose}]}return[n,null]}),o=j.useMemo(()=>s(e,t)[0],[e,t]),[i=o,a]=j.useState();return Gn(()=>{let[l,u]=s(e,t);if(a(l),!!u)return u(a)},[e,t]),i}function RK(e){let t=/var\((.*)\)/.exec(e);if(t){let n=t[1].indexOf(",");if(n===-1)return[t[1]];let r=t[1].slice(0,n).trim(),s=t[1].slice(n+1).trim();return s?[r,...RK(s)]:[r]}return[]}function u3(e,t){let n=document.createElement("div");t.appendChild(n),n.style.setProperty("margin-top","0px","important"),n.style.setProperty("margin-top",e,"important");let r=parseFloat(window.getComputedStyle(n).marginTop)||0;return t.removeChild(n),r}function f5e({children:e,freeze:t}){let n=IE(t,e);return j.createElement(j.Fragment,null,n)}function IE(e,t){let[n,r]=j.useState(t);return!e&&n!==t&&r(t),e?n:t}let NR=j.createContext(null);NR.displayName="OpenClosedContext";var rb=(e=>(e[e.Open=1]="Open",e[e.Closed=2]="Closed",e[e.Closing=4]="Closing",e[e.Opening=8]="Opening",e))(rb||{});function h5e(){return j.useContext(NR)}function m5e({value:e,children:t}){return j.createElement(NR.Provider,{value:e},t)}function p5e(e){function t(){document.readyState!=="loading"&&(e(),document.removeEventListener("DOMContentLoaded",t))}typeof window<"u"&&typeof document<"u"&&(document.addEventListener("DOMContentLoaded",t),t())}let Mu=[];p5e(()=>{function e(t){if(!(t.target instanceof HTMLElement)||t.target===document.body||Mu[0]===t.target)return;let n=t.target;n=n.closest(TE),Mu.unshift(n??t.target),Mu=Mu.filter(r=>r!=null&&r.isConnected),Mu.splice(10)}window.addEventListener("click",e,{capture:!0}),window.addEventListener("mousedown",e,{capture:!0}),window.addEventListener("focus",e,{capture:!0}),document.body.addEventListener("click",e,{capture:!0}),document.body.addEventListener("mousedown",e,{capture:!0}),document.body.addEventListener("focus",e,{capture:!0})});function g5e(e){throw new Error("Unexpected object: "+e)}var yr=(e=>(e[e.First=0]="First",e[e.Previous=1]="Previous",e[e.Next=2]="Next",e[e.Last=3]="Last",e[e.Specific=4]="Specific",e[e.Nothing=5]="Nothing",e))(yr||{});function d3(e,t){let n=t.resolveItems();if(n.length<=0)return null;let r=t.resolveActiveIndex(),s=r??-1;switch(e.focus){case 0:{for(let o=0;o<n.length;++o)if(!t.resolveDisabled(n[o],o,n))return o;return r}case 1:{s===-1&&(s=n.length);for(let o=s-1;o>=0;--o)if(!t.resolveDisabled(n[o],o,n))return o;return r}case 2:{for(let o=s+1;o<n.length;++o)if(!t.resolveDisabled(n[o],o,n))return o;return r}case 3:{for(let o=n.length-1;o>=0;--o)if(!t.resolveDisabled(n[o],o,n))return o;return r}case 4:{for(let o=0;o<n.length;++o)if(t.resolveId(n[o],o,n)===e.id)return o;return r}case 5:return null;default:g5e(e)}}var jR=(e=>(e[e.Left=0]="Left",e[e.Right=2]="Right",e))(jR||{});function b5e(e){let t=Ct(e),n=j.useRef(!1);j.useEffect(()=>(n.current=!1,()=>{n.current=!0,mK(()=>{n.current&&t()})}),[t])}function x5e(){let e=typeof document>"u";return"useSyncExternalStore"in D?(t=>t.useSyncExternalStore)(D)(()=>()=>{},()=>!1,()=>!e):!1}function y5e(){let e=x5e(),[t,n]=D.useState(cd.isHandoffComplete);return t&&cd.isHandoffComplete===!1&&n(!1),D.useEffect(()=>{t!==!0&&n(!0)},[t]),D.useEffect(()=>cd.handoff(),[]),e?!1:t}let v5e=j.createContext(!1);function w5e(){return j.useContext(v5e)}function S5e(e){let t=w5e(),n=j.useContext(AK),r=vS(e),[s,o]=j.useState(()=>{var i;if(!t&&n!==null)return(i=n.current)!=null?i:null;if(cd.isServer)return null;let a=r==null?void 0:r.getElementById("headlessui-portal-root");if(a)return a;if(r===null)return null;let l=r.createElement("div");return l.setAttribute("id","headlessui-portal-root"),r.body.appendChild(l)});return j.useEffect(()=>{s!==null&&(r!=null&&r.body.contains(s)||r==null||r.body.appendChild(s))},[s,r]),j.useEffect(()=>{t||n!==null&&o(n.current)},[n,o,t]),s}let IK=j.Fragment,C5e=$i(function(e,t){let n=e,r=j.useRef(null),s=kl(ZOe(f=>{r.current=f}),t),o=vS(r),i=S5e(r),[a]=j.useState(()=>{var f;return cd.isServer?null:(f=o==null?void 0:o.createElement("div"))!=null?f:null}),l=j.useContext(E5e),u=y5e();Gn(()=>{!i||!a||i.contains(a)||(a.setAttribute("data-headlessui-portal",""),i.appendChild(a))},[i,a]),Gn(()=>{if(a&&l)return l.register(a)},[l,a]),b5e(()=>{var f;!i||!a||(a instanceof Node&&i.contains(a)&&i.removeChild(a),i.childNodes.length<=0&&((f=i.parentElement)==null||f.removeChild(i)))});let d=Fi();return u?!i||!a?null:Pn.createPortal(d({ourProps:{ref:s},theirProps:n,slot:{},defaultTag:IK,name:"Portal"}),a):null});function N5e(e,t){let n=kl(t),{enabled:r=!0,...s}=e,o=Fi();return r?j.createElement(C5e,{...s,ref:n}):o({ourProps:{ref:n},theirProps:s,slot:{},defaultTag:IK,name:"Portal"})}let j5e=j.Fragment,AK=j.createContext(null);function k5e(e,t){let{target:n,...r}=e,s={ref:kl(t)},o=Fi();return j.createElement(AK.Provider,{value:n},o({ourProps:s,theirProps:r,defaultTag:j5e,name:"Popover.Group"}))}let E5e=j.createContext(null),_5e=$i(N5e),D5e=$i(k5e),M5e=Object.assign(_5e,{Group:D5e});var T5e=(e=>(e[e.Open=0]="Open",e[e.Closed=1]="Closed",e))(T5e||{}),R5e=(e=>(e[e.Single=0]="Single",e[e.Multi=1]="Multi",e))(R5e||{}),I5e=(e=>(e[e.Pointer=0]="Pointer",e[e.Focus=1]="Focus",e[e.Other=2]="Other",e))(I5e||{}),A5e=(e=>(e[e.OpenCombobox=0]="OpenCombobox",e[e.CloseCombobox=1]="CloseCombobox",e[e.GoToOption=2]="GoToOption",e[e.SetTyping=3]="SetTyping",e[e.RegisterOption=4]="RegisterOption",e[e.UnregisterOption=5]="UnregisterOption",e[e.SetActivationTrigger=6]="SetActivationTrigger",e[e.UpdateVirtualConfiguration=7]="UpdateVirtualConfiguration",e[e.SetInputElement=8]="SetInputElement",e[e.SetButtonElement=9]="SetButtonElement",e[e.SetOptionsElement=10]="SetOptionsElement",e))(A5e||{});function Cj(e,t=n=>n){let n=e.activeOptionIndex!==null?e.options[e.activeOptionIndex]:null,r=t(e.options.slice()),s=r.length>0&&r[0].dataRef.current.order!==null?r.sort((i,a)=>i.dataRef.current.order-a.dataRef.current.order):xFe(r,i=>i.dataRef.current.domRef.current),o=n?s.indexOf(n):null;return o===-1&&(o=null),{options:s,activeOptionIndex:o}}let P5e={1(e){var t;return(t=e.dataRef.current)!=null&&t.disabled||e.comboboxState===1?e:{...e,activeOptionIndex:null,comboboxState:1,isTyping:!1,activationTrigger:2,__demoMode:!1}},0(e){var t,n;if((t=e.dataRef.current)!=null&&t.disabled||e.comboboxState===0)return e;if((n=e.dataRef.current)!=null&&n.value){let r=e.dataRef.current.calculateIndex(e.dataRef.current.value);if(r!==-1)return{...e,activeOptionIndex:r,comboboxState:0,__demoMode:!1}}return{...e,comboboxState:0,__demoMode:!1}},3(e,t){return e.isTyping===t.isTyping?e:{...e,isTyping:t.isTyping}},2(e,t){var n,r,s,o;if((n=e.dataRef.current)!=null&&n.disabled||e.optionsElement&&!((r=e.dataRef.current)!=null&&r.optionsPropsRef.current.static)&&e.comboboxState===1)return e;if(e.virtual){let{options:u,disabled:d}=e.virtual,f=t.focus===yr.Specific?t.idx:d3(t,{resolveItems:()=>u,resolveActiveIndex:()=>{var m,p;return(p=(m=e.activeOptionIndex)!=null?m:u.findIndex(g=>!d(g)))!=null?p:null},resolveDisabled:d,resolveId(){throw new Error("Function not implemented.")}}),h=(s=t.trigger)!=null?s:2;return e.activeOptionIndex===f&&e.activationTrigger===h?e:{...e,activeOptionIndex:f,activationTrigger:h,isTyping:!1,__demoMode:!1}}let i=Cj(e);if(i.activeOptionIndex===null){let u=i.options.findIndex(d=>!d.dataRef.current.disabled);u!==-1&&(i.activeOptionIndex=u)}let a=t.focus===yr.Specific?t.idx:d3(t,{resolveItems:()=>i.options,resolveActiveIndex:()=>i.activeOptionIndex,resolveId:u=>u.id,resolveDisabled:u=>u.dataRef.current.disabled}),l=(o=t.trigger)!=null?o:2;return e.activeOptionIndex===a&&e.activationTrigger===l?e:{...e,...i,isTyping:!1,activeOptionIndex:a,activationTrigger:l,__demoMode:!1}},4:(e,t)=>{var n,r,s;if((n=e.dataRef.current)!=null&&n.virtual)return{...e,options:[...e.options,t.payload]};let o=t.payload,i=Cj(e,l=>(l.push(o),l));e.activeOptionIndex===null&&(r=e.dataRef.current)!=null&&r.isSelected(t.payload.dataRef.current.value)&&(i.activeOptionIndex=i.options.indexOf(o));let a={...e,...i,activationTrigger:2};return(s=e.dataRef.current)!=null&&s.__demoMode&&e.dataRef.current.value===void 0&&(a.activeOptionIndex=0),a},5:(e,t)=>{var n;if((n=e.dataRef.current)!=null&&n.virtual)return{...e,options:e.options.filter(s=>s.id!==t.id)};let r=Cj(e,s=>{let o=s.findIndex(i=>i.id===t.id);return o!==-1&&s.splice(o,1),s});return{...e,...r,activationTrigger:2}},6:(e,t)=>e.activationTrigger===t.trigger?e:{...e,activationTrigger:t.trigger},7:(e,t)=>{var n,r;if(e.virtual===null)return{...e,virtual:{options:t.options,disabled:(n=t.disabled)!=null?n:()=>!1}};if(e.virtual.options===t.options&&e.virtual.disabled===t.disabled)return e;let s=e.activeOptionIndex;if(e.activeOptionIndex!==null){let o=t.options.indexOf(e.virtual.options[e.activeOptionIndex]);o!==-1?s=o:s=null}return{...e,activeOptionIndex:s,virtual:{options:t.options,disabled:(r=t.disabled)!=null?r:()=>!1}}},8:(e,t)=>e.inputElement===t.element?e:{...e,inputElement:t.element},9:(e,t)=>e.buttonElement===t.element?e:{...e,buttonElement:t.element},10:(e,t)=>e.optionsElement===t.element?e:{...e,optionsElement:t.element}},kR=j.createContext(null);kR.displayName="ComboboxActionsContext";function Sx(e){let t=j.useContext(kR);if(t===null){let n=new Error(`<${e} /> is missing a parent <Combobox /> component.`);throw Error.captureStackTrace&&Error.captureStackTrace(n,Sx),n}return t}let PK=j.createContext(null);function O5e(e){let t=Gm("VirtualProvider"),{options:n}=t.virtual,[r,s]=j.useMemo(()=>{let u=t.optionsElement;if(!u)return[0,0];let d=window.getComputedStyle(u);return[parseFloat(d.paddingBlockStart||d.paddingTop),parseFloat(d.paddingBlockEnd||d.paddingBottom)]},[t.optionsElement]),o=QT({enabled:n.length!==0,scrollPaddingStart:r,scrollPaddingEnd:s,count:n.length,estimateSize(){return 40},getScrollElement(){return t.optionsElement},overscan:12}),[i,a]=j.useState(0);Gn(()=>{a(u=>u+1)},[n]);let l=o.getVirtualItems();return l.length===0?null:j.createElement(PK.Provider,{value:o},j.createElement("div",{style:{position:"relative",width:"100%",height:`${o.getTotalSize()}px`},ref:u=>{u&&t.activationTrigger!==0&&t.activeOptionIndex!==null&&n.length>t.activeOptionIndex&&o.scrollToIndex(t.activeOptionIndex)}},l.map(u=>{var d;return j.createElement(j.Fragment,{key:u.key},j.cloneElement((d=e.children)==null?void 0:d.call(e,{...e.slot,option:n[u.index]}),{key:`${i}-${u.key}`,"data-index":u.index,"aria-setsize":n.length,"aria-posinset":u.index+1,style:{position:"absolute",top:0,left:0,transform:`translateY(${u.start}px)`,overflowAnchor:"none"}}))})))}let sb=j.createContext(null);sb.displayName="ComboboxDataContext";function Gm(e){let t=j.useContext(sb);if(t===null){let n=new Error(`<${e} /> is missing a parent <Combobox /> component.`);throw Error.captureStackTrace&&Error.captureStackTrace(n,Gm),n}return t}function F5e(e,t){return fl(t.type,P5e,e,t)}let $5e=j.Fragment;function L5e(e,t){var n,r;let s=xR(),{value:o,defaultValue:i,onChange:a,form:l,name:u,by:d,disabled:f=s||!1,onClose:h,__demoMode:m=!1,multiple:p=!1,immediate:g=!1,virtual:b=null,nullable:x,...y}=e,v=zOe(i),[w=p?[]:void 0,C]=LOe(o,a,v),[S,N]=j.useReducer(F5e,{dataRef:j.createRef(),comboboxState:m?0:1,isTyping:!1,options:[],virtual:b?{options:b.options,disabled:(n=b.disabled)!=null?n:()=>!1}:null,activeOptionIndex:null,activationTrigger:2,inputElement:null,buttonElement:null,optionsElement:null,__demoMode:m}),_=j.useRef(!1),E=j.useRef({static:!1,hold:!1}),k=aFe(d),M=Ct(se=>b?d===null?b.options.indexOf(se):b.options.findIndex(ce=>k(ce,se)):S.options.findIndex(ce=>k(ce.dataRef.current.value,se))),T=j.useCallback(se=>fl(R.mode,{1:()=>w.some(ce=>k(ce,se)),0:()=>k(w,se)}),[w]),O=Ct(se=>S.activeOptionIndex===M(se)),R=j.useMemo(()=>({...S,immediate:g,optionsPropsRef:E,value:w,defaultValue:v,disabled:f,mode:p?1:0,virtual:b?S.virtual:null,get activeOptionIndex(){if(_.current&&S.activeOptionIndex===null&&(b?b.options.length>0:S.options.length>0)){if(b){let ce=b.options.findIndex(re=>{var fe,Ce;return!((Ce=(fe=b.disabled)==null?void 0:fe.call(b,re))!=null&&Ce)});if(ce!==-1)return ce}let se=S.options.findIndex(ce=>!ce.dataRef.current.disabled);if(se!==-1)return se}return S.activeOptionIndex},calculateIndex:M,compare:k,isSelected:T,isActive:O}),[w,v,f,p,m,S,b]);Gn(()=>{var se;b&&N({type:7,options:b.options,disabled:(se=b.disabled)!=null?se:null})},[b,b==null?void 0:b.options,b==null?void 0:b.disabled]),Gn(()=>{S.dataRef.current=R},[R]);let I=R.comboboxState===0;wFe(I,[R.buttonElement,R.inputElement,R.optionsElement],()=>H.closeCombobox());let L=j.useMemo(()=>{var se,ce,re;return{open:R.comboboxState===0,disabled:f,activeIndex:R.activeOptionIndex,activeOption:R.activeOptionIndex===null?null:R.virtual?R.virtual.options[(se=R.activeOptionIndex)!=null?se:0]:(re=(ce=R.options[R.activeOptionIndex])==null?void 0:ce.dataRef.current.value)!=null?re:null,value:w}},[R,f,w]),F=Ct(()=>{if(R.activeOptionIndex!==null){if(H.setIsTyping(!1),R.virtual)A(R.virtual.options[R.activeOptionIndex]);else{let{dataRef:se}=R.options[R.activeOptionIndex];A(se.current.value)}H.goToOption(yr.Specific,R.activeOptionIndex)}}),V=Ct(()=>{N({type:0}),_.current=!0}),$=Ct(()=>{N({type:1}),_.current=!1,h==null||h()}),P=Ct(se=>{N({type:3,isTyping:se})}),U=Ct((se,ce,re)=>(_.current=!1,se===yr.Specific?N({type:2,focus:yr.Specific,idx:ce,trigger:re}):N({type:2,focus:se,trigger:re}))),B=Ct((se,ce)=>(N({type:4,payload:{id:se,dataRef:ce}}),()=>{R.isActive(ce.current.value)&&(_.current=!0),N({type:5,id:se})})),A=Ct(se=>fl(R.mode,{0(){return C==null?void 0:C(se)},1(){let ce=R.value.slice(),re=ce.findIndex(fe=>k(fe,se));return re===-1?ce.push(se):ce.splice(re,1),C==null?void 0:C(ce)}})),Y=Ct(se=>{N({type:6,trigger:se})}),z=Ct(se=>{N({type:8,element:se})}),q=Ct(se=>{N({type:9,element:se})}),W=Ct(se=>{N({type:10,element:se})}),H=j.useMemo(()=>({onChange:A,registerOption:B,goToOption:U,setIsTyping:P,closeCombobox:$,openCombobox:V,setActivationTrigger:Y,selectActiveOption:F,setInputElement:z,setButtonElement:q,setOptionsElement:W}),[]),[G,K]=tFe(),te=t===null?{}:{ref:t},Z=j.useCallback(()=>{if(v!==void 0)return C==null?void 0:C(v)},[C,v]),ee=Fi();return j.createElement(K,{value:G,props:{htmlFor:(r=R.inputElement)==null?void 0:r.id},slot:{open:R.comboboxState===0,disabled:f}},j.createElement(c5e,null,j.createElement(kR.Provider,{value:H},j.createElement(sb.Provider,{value:R},j.createElement(m5e,{value:fl(R.comboboxState,{0:rb.Open,1:rb.Closed})},u!=null&&j.createElement(WOe,{disabled:f,data:w!=null?{[u]:w}:{},form:l,onReset:Z}),ee({ourProps:te,theirProps:y,slot:L,defaultTag:$5e,name:"Combobox"}))))))}let z5e="input";function B5e(e,t){var n,r,s,o,i;let a=Gm("Combobox.Input"),l=Sx("Combobox.Input"),u=j.useId(),d=vK(),{id:f=d||`headlessui-combobox-input-${u}`,onChange:h,displayValue:m,disabled:p=a.disabled||!1,autoFocus:g=!1,type:b="text",...x}=e,y=j.useRef(null),v=kl(y,t,i5e(),l.setInputElement),w=vS(a.inputElement),C=vx(),S=Ct(()=>{l.onChange(null),a.optionsElement&&(a.optionsElement.scrollTop=0),l.goToOption(yr.Nothing)}),N=j.useMemo(()=>{var A;return typeof m=="function"&&a.value!==void 0?(A=m(a.value))!=null?A:"":typeof a.value=="string"?a.value:""},[a.value,m]);r3(([A,Y],[z,q])=>{if(a.isTyping)return;let W=y.current;W&&((q===0&&Y===1||A!==z)&&(W.value=A),requestAnimationFrame(()=>{if(a.isTyping||!W||(w==null?void 0:w.activeElement)!==W)return;let{selectionStart:H,selectionEnd:G}=W;Math.abs((G??0)-(H??0))===0&&H===0&&W.setSelectionRange(W.value.length,W.value.length)}))},[N,a.comboboxState,w,a.isTyping]),r3(([A],[Y])=>{if(A===0&&Y===1){if(a.isTyping)return;let z=y.current;if(!z)return;let q=z.value,{selectionStart:W,selectionEnd:H,selectionDirection:G}=z;z.value="",z.value=q,G!==null?z.setSelectionRange(W,H,G):z.setSelectionRange(W,H)}},[a.comboboxState]);let _=j.useRef(!1),E=Ct(()=>{_.current=!0}),k=Ct(()=>{C.nextFrame(()=>{_.current=!1})}),M=Ct(A=>{switch(l.setIsTyping(!0),A.key){case ys.Enter:if(a.comboboxState!==0||_.current)return;if(A.preventDefault(),A.stopPropagation(),a.activeOptionIndex===null){l.closeCombobox();return}l.selectActiveOption(),a.mode===0&&l.closeCombobox();break;case ys.ArrowDown:return A.preventDefault(),A.stopPropagation(),fl(a.comboboxState,{0:()=>l.goToOption(yr.Next),1:()=>l.openCombobox()});case ys.ArrowUp:return A.preventDefault(),A.stopPropagation(),fl(a.comboboxState,{0:()=>l.goToOption(yr.Previous),1:()=>{Pn.flushSync(()=>l.openCombobox()),a.value||l.goToOption(yr.Last)}});case ys.Home:if(A.shiftKey)break;return A.preventDefault(),A.stopPropagation(),l.goToOption(yr.First);case ys.PageUp:return A.preventDefault(),A.stopPropagation(),l.goToOption(yr.First);case ys.End:if(A.shiftKey)break;return A.preventDefault(),A.stopPropagation(),l.goToOption(yr.Last);case ys.PageDown:return A.preventDefault(),A.stopPropagation(),l.goToOption(yr.Last);case ys.Escape:return a.comboboxState!==0?void 0:(A.preventDefault(),a.optionsElement&&!a.optionsPropsRef.current.static&&A.stopPropagation(),a.mode===0&&a.value===null&&S(),l.closeCombobox());case ys.Tab:if(a.comboboxState!==0)return;a.mode===0&&a.activationTrigger!==1&&l.selectActiveOption(),l.closeCombobox();break}}),T=Ct(A=>{h==null||h(A),a.mode===0&&A.target.value===""&&S(),l.openCombobox()}),O=Ct(A=>{var Y,z,q;let W=(Y=A.relatedTarget)!=null?Y:Mu.find(H=>H!==A.currentTarget);if(!((z=a.optionsElement)!=null&&z.contains(W))&&!((q=a.buttonElement)!=null&&q.contains(W))&&a.comboboxState===0)return A.preventDefault(),a.mode===0&&a.value===null&&S(),l.closeCombobox()}),R=Ct(A=>{var Y,z,q;let W=(Y=A.relatedTarget)!=null?Y:Mu.find(H=>H!==A.currentTarget);(z=a.buttonElement)!=null&&z.contains(W)||(q=a.optionsElement)!=null&&q.contains(W)||a.disabled||a.immediate&&a.comboboxState!==0&&C.microTask(()=>{Pn.flushSync(()=>l.openCombobox()),l.setActivationTrigger(1)})}),I=yS(),L=XOe(),{isFocused:F,focusProps:V}=hK({autoFocus:g}),{isHovered:$,hoverProps:P}=fK({isDisabled:p}),U=j.useMemo(()=>({open:a.comboboxState===0,disabled:p,hover:$,focus:F,autofocus:g}),[a,$,F,g,p]),B=yR({ref:v,id:f,role:"combobox",type:b,"aria-controls":(n=a.optionsElement)==null?void 0:n.id,"aria-expanded":a.comboboxState===0,"aria-activedescendant":a.activeOptionIndex===null?void 0:a.virtual?(r=a.options.find(A=>!A.dataRef.current.disabled&&a.compare(A.dataRef.current.value,a.virtual.options[a.activeOptionIndex])))==null?void 0:r.id:(s=a.options[a.activeOptionIndex])==null?void 0:s.id,"aria-labelledby":I,"aria-describedby":L,"aria-autocomplete":"list",defaultValue:(i=(o=e.defaultValue)!=null?o:a.defaultValue!==void 0?m==null?void 0:m(a.defaultValue):null)!=null?i:a.defaultValue,disabled:p||void 0,autoFocus:g,onCompositionStart:E,onCompositionEnd:k,onKeyDown:M,onChange:T,onFocus:R,onBlur:O},V,P);return Fi()({ourProps:B,theirProps:x,slot:U,defaultTag:z5e,name:"Combobox.Input"})}let V5e="button";function H5e(e,t){var n;let r=Gm("Combobox.Button"),s=Sx("Combobox.Button"),o=kl(t,s.setButtonElement),i=j.useId(),{id:a=`headlessui-combobox-button-${i}`,disabled:l=r.disabled||!1,autoFocus:u=!1,...d}=e,f=DK(r.inputElement),h=Ct(N=>{switch(N.key){case ys.Space:case ys.Enter:N.preventDefault(),N.stopPropagation(),r.comboboxState===1&&Pn.flushSync(()=>s.openCombobox()),f();return;case ys.ArrowDown:N.preventDefault(),N.stopPropagation(),r.comboboxState===1&&(Pn.flushSync(()=>s.openCombobox()),r.value||s.goToOption(yr.First)),f();return;case ys.ArrowUp:N.preventDefault(),N.stopPropagation(),r.comboboxState===1&&(Pn.flushSync(()=>s.openCombobox()),r.value||s.goToOption(yr.Last)),f();return;case ys.Escape:if(r.comboboxState!==0)return;N.preventDefault(),r.optionsElement&&!r.optionsPropsRef.current.static&&N.stopPropagation(),Pn.flushSync(()=>s.closeCombobox()),f();return;default:return}}),m=Ct(N=>{N.preventDefault(),!GOe(N.currentTarget)&&(N.button===jR.Left&&(r.comboboxState===0?s.closeCombobox():s.openCombobox()),f())}),p=yS([a]),{isFocusVisible:g,focusProps:b}=hK({autoFocus:u}),{isHovered:x,hoverProps:y}=fK({isDisabled:l}),{pressed:v,pressProps:w}=ROe({disabled:l}),C=j.useMemo(()=>({open:r.comboboxState===0,active:v||r.comboboxState===0,disabled:l,value:r.value,hover:x,focus:g}),[r,x,g,v,l]),S=yR({ref:o,id:a,type:CFe(e,r.buttonElement),tabIndex:-1,"aria-haspopup":"listbox","aria-controls":(n=r.optionsElement)==null?void 0:n.id,"aria-expanded":r.comboboxState===0,"aria-labelledby":p,disabled:l||void 0,autoFocus:u,onMouseDown:m,onKeyDown:h},b,y,w);return Fi()({ourProps:S,theirProps:d,slot:C,defaultTag:V5e,name:"Combobox.Button"})}let U5e="div",W5e=DE.RenderStrategy|DE.Static;function q5e(e,t){var n,r,s;let o=j.useId(),{id:i=`headlessui-combobox-options-${o}`,hold:a=!1,anchor:l,portal:u=!1,modal:d=!0,transition:f=!1,...h}=e,m=Gm("Combobox.Options"),p=Sx("Combobox.Options"),g=o5e(l);g&&(u=!0);let[b,x]=l5e(g),[y,v]=j.useState(null),w=a5e(),C=kl(t,g?b:null,p.setOptionsElement,v),S=vS(m.optionsElement),N=h5e(),[_,E]=AFe(f,y,N!==null?(N&rb.Open)===rb.Open:m.comboboxState===0);fFe(_,m.inputElement,p.closeCombobox);let k=m.__demoMode?!1:d&&m.comboboxState===0;DFe(k,S);let M=m.__demoMode?!1:d&&m.comboboxState===0;dFe(M,{allowed:j.useCallback(()=>[m.inputElement,m.buttonElement,m.optionsElement],[m.inputElement,m.buttonElement,m.optionsElement])}),Gn(()=>{var B;m.optionsPropsRef.current.static=(B=e.static)!=null?B:!1},[m.optionsPropsRef,e.static]),Gn(()=>{m.optionsPropsRef.current.hold=a},[m.optionsPropsRef,a]),$Fe(m.comboboxState===0,{container:m.optionsElement,accept(B){return B.getAttribute("role")==="option"?NodeFilter.FILTER_REJECT:B.hasAttribute("role")?NodeFilter.FILTER_SKIP:NodeFilter.FILTER_ACCEPT},walk(B){B.setAttribute("role","none")}});let T=yS([(n=m.buttonElement)==null?void 0:n.id]),O=j.useMemo(()=>({open:m.comboboxState===0,option:void 0}),[m.comboboxState]),R=Ct(()=>{p.setActivationTrigger(0)}),I=Ct(B=>{B.preventDefault(),p.setActivationTrigger(0)}),L=yR(g?w():{},{"aria-labelledby":T,role:"listbox","aria-multiselectable":m.mode===1?!0:void 0,id:i,ref:C,style:{...h.style,...x,"--input-width":Z4(m.inputElement,!0).width,"--button-width":Z4(m.buttonElement,!0).width},onWheel:m.activationTrigger===0?void 0:R,onMouseDown:I,...IFe(E)}),F=_&&m.comboboxState===1,V=IE(F,(r=m.virtual)==null?void 0:r.options),$=IE(F,m.value),P=Ct(B=>m.compare($,B));if(m.virtual){if(V===void 0)throw new Error("Missing `options` in virtual mode");Object.assign(h,{children:j.createElement(sb.Provider,{value:V!==m.virtual.options?{...m,virtual:{...m.virtual,options:V}}:m},j.createElement(O5e,{slot:O},h.children))})}let U=Fi();return j.createElement(M5e,{enabled:u?e.static||_:!1},j.createElement(sb.Provider,{value:m.mode===1?m:{...m,isSelected:P}},U({ourProps:L,theirProps:{...h,children:j.createElement(f5e,{freeze:F},typeof h.children=="function"?(s=h.children)==null?void 0:s.call(h,O):h.children)},slot:O,defaultTag:U5e,features:W5e,visible:_,name:"Combobox.Options"})))}let Y5e="div";function G5e(e,t){var n,r,s,o;let i=Gm("Combobox.Option"),a=Sx("Combobox.Option"),l=j.useId(),{id:u=`headlessui-combobox-option-${l}`,value:d,disabled:f=(s=(r=(n=i.virtual)==null?void 0:n.disabled)==null?void 0:r.call(n,d))!=null?s:!1,order:h=null,...m}=e,p=DK(i.inputElement),g=i.virtual?i.activeOptionIndex===i.calculateIndex(d):i.activeOptionIndex===null?!1:((o=i.options[i.activeOptionIndex])==null?void 0:o.id)===u,b=i.isSelected(d),x=j.useRef(null),y=af({disabled:f,value:d,domRef:x,order:h}),v=j.useContext(PK),w=kl(t,x,v?v.measureElement:null),C=Ct(()=>{a.setIsTyping(!1),a.onChange(d)});Gn(()=>a.registerOption(u,y),[y,u]);let S=j.useRef(!(i.virtual||i.__demoMode));Gn(()=>{if(!i.virtual&&!i.__demoMode)return xa().requestAnimationFrame(()=>{S.current=!0})},[i.virtual,i.__demoMode]),Gn(()=>{if(S.current&&i.comboboxState===0&&g&&i.activationTrigger!==0)return xa().requestAnimationFrame(()=>{var I,L;(L=(I=x.current)==null?void 0:I.scrollIntoView)==null||L.call(I,{block:"nearest"})})},[x,g,i.comboboxState,i.activationTrigger,i.activeOptionIndex]);let N=Ct(I=>{I.preventDefault(),I.button===jR.Left&&(f||(C(),_K()||requestAnimationFrame(()=>p()),i.mode===0&&a.closeCombobox()))}),_=Ct(()=>{if(f)return a.goToOption(yr.Nothing);let I=i.calculateIndex(d);a.goToOption(yr.Specific,I)}),E=MFe(),k=Ct(I=>E.update(I)),M=Ct(I=>{if(!E.wasMoved(I)||f||g)return;let L=i.calculateIndex(d);a.goToOption(yr.Specific,L,0)}),T=Ct(I=>{E.wasMoved(I)&&(f||g&&(i.optionsPropsRef.current.hold||a.goToOption(yr.Nothing)))}),O=j.useMemo(()=>({active:g,focus:g,selected:b,disabled:f}),[g,b,f]),R={id:u,ref:w,role:"option",tabIndex:f===!0?void 0:-1,"aria-disabled":f===!0?!0:void 0,"aria-selected":b,disabled:void 0,onMouseDown:N,onFocus:_,onPointerEnter:k,onMouseEnter:k,onPointerMove:M,onMouseMove:M,onPointerLeave:T,onMouseLeave:T};return Fi()({ourProps:R,theirProps:m,slot:O,defaultTag:Y5e,name:"Combobox.Option"})}let K5e=$i(L5e),OK=$i(H5e),FK=$i(B5e),Z5e=oFe,$K=$i(q5e),LK=$i(G5e),X5e=Object.assign(K5e,{Input:FK,Button:OK,Label:Z5e,Options:$K,Option:LK});function Q5e({elementId:e}){const t=j.useRef(!1);return j.useEffect(()=>{if(t.current)return;const n=document.getElementById(e);return n&&(n.classList.add("semaphor-scope"),t.current=!0),()=>{n&&(n.classList.remove("semaphor-scope"),t.current=!1)}},[e]),null}const J5e=j.memo(({option:e,currentStyle:t})=>c.jsxs(LK,{style:{borderRadius:t==null?void 0:t.controlInputRadius},value:e,className:"group flex cursor-default select-none items-start gap-2 rounded-sm px-3 py-1.5 data-[focus]:bg-muted",children:[c.jsx($r,{className:"invisible size-4 shrink-0 group-data-[selected]:visible"}),e.value]},e.id),(e,t)=>e.option.id===t.option.id&&e.option.value===t.option.value);function e4e({options:e,onChange:t,selectedOptions:n,multiple:r=!0,externalFilteredOptions:s,selectAllChecked:o,onSelectAllCheckedChange:i,inputClassName:a,renderFilterModeButton:l,showNegativeIndicator:u,isSearching:d,resultSource:f="local",searchError:h,query:m,onQueryChange:p,filterDataType:g,onEnterKey:b,activeFilterValue:x}){const[y,v]=j.useState(""),w=m!==void 0?m:y,C=p||v,S=Q(R=>R.themeStyle),N=s||e;function _(R,I){if(I)return"";const L=[">","<",">=","<=","="];return(g?wi(g):!1)&&x&&L.includes(x.operation)?`${x.operation}${x.values[0]}`:R!=null&&R.length?R==null?void 0:R.map(V=>V.value).join(", "):""}function E(R){Array.isArray(R)||(R=[R]),t(R)}function k(){return d||N&&N.length>0?null:c.jsx("div",{className:"relative cursor-default select-none px-4 py-2",children:"No records found."})}function M(){return d?c.jsxs("div",{className:"flex items-center gap-2 border-b border-b-muted px-4 py-2 text-xs text-muted-foreground",children:[c.jsx("div",{className:"h-3 w-3 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Searching..."]}):h&&w?c.jsx("div",{className:"border-b border-b-muted px-4 py-2 text-xs text-amber-600",children:"Search unavailable. Showing available results."}):null}function T(){return w||!(e!=null&&e.length)?null:c.jsx("div",{className:"border-b border-b-muted px-4 py-2 text-xs text-muted-foreground",children:"Type to search more..."})}function O(){return!r||!(N!=null&&N.length)?null:c.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-b-muted px-4 py-2",children:[l==null?void 0:l(),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{children:"All"}),c.jsx(nn,{className:"border-muted-foreground/50",checked:o,onCheckedChange:i})]})]})}return c.jsx(X5e,{multiple:r,value:n,onChange:E,onClose:()=>{C("")},by:(R,I)=>Array.isArray(R)||Array.isArray(I)?!1:!R||!I?R===I:R.id===I.id,children:({open:R})=>c.jsxs("div",{children:[c.jsxs("div",{className:"relative flex items-center gap-0.5",children:[u&&c.jsx("div",{className:"h-8 w-0.5 bg-red-400"}),c.jsx(FK,{className:X("h-8 w-full rounded-sm border border-border bg-background py-1.5 pl-3 pr-8 text-sm","data-[focus]:outline-border-none focus:outline-none data-[focus]:outline-none data-[focus]:-outline-offset-2",a),style:{borderRadius:S==null?void 0:S.controlInputRadius},displayValue:I=>_(I,R),onChange:I=>C(I.target.value),onKeyDown:I=>{if(I.key==="Enter"&&b){const L=/^(>=|<=|>|<|=)/.test(w.trim()),F=g?wi(g):!1;L&&F&&(I.preventDefault(),b()&&I.target.blur())}}}),c.jsx(OK,{className:"group absolute inset-y-0 right-0 rounded-sm bg-muted/40 px-2.5 transition-colors hover:bg-muted/60",children:c.jsx(Ks,{className:"size-4 text-muted-foreground transition-colors group-hover:text-foreground"})})]}),c.jsxs($K,{anchor:"bottom",transition:!0,style:{borderRadius:S==null?void 0:S.controlInputRadius},className:fd("mt-1 !max-h-60 w-[var(--input-width)] overflow-y-auto rounded-sm border border-border bg-background p-1 text-sm [--anchor-gap:var(--spacing-1)] empty:invisible","transition duration-100 ease-in data-[leave]:data-[closed]:opacity-0"),children:[R&&c.jsx(Q5e,{elementId:"headlessui-portal-root"}),M(),T(),k(),O(),N==null?void 0:N.map(I=>c.jsx(J5e,{option:I,currentStyle:S},I.id))]})]})})}const f3=[{value:"=",label:"Equal to",symbol:"="},{value:">",label:"Greater than",symbol:">"},{value:">=",label:"Greater than or equal",symbol:"≥"},{value:"<",label:"Less than",symbol:"<"},{value:"<=",label:"Less than or equal",symbol:"≤"},{value:"between",label:"Between",symbol:"⟷"},{value:"not between",label:"Not Between",symbol:"⇎"}],t4e=new Set(["=",">","<",">=","<=","between","not between"]);function n4e(e){return t4e.has(e)?e:">="}function r4e({filter:e,storageOptions:t}){var T;const[n,r]=j.useState(">="),[s,o]=j.useState(""),[i,a]=j.useState(""),[l,u]=j.useState(""),[d,f]=j.useState(!0),h=j.useRef(null),m=j.useRef(!1),[,p]=j.useTransition(),g=ug(s,300),b=ug(i,300),x=ug(l,300),y=(t==null?void 0:t.storageTarget)==="card",v=Q(O=>O.filterValues),w=Q(O=>O.themeStyle),C=Q(O=>O.actions.setCardInlineFilterValue),S=Q(O=>O.actions.removeCardInlineFilterValue),{addOrUpdateFilterValue:N,removeFilterValues:_}=Gt(),E=y?t==null?void 0:t.inlineFilterValues:v,k=j.useCallback(O=>{y?C((t==null?void 0:t.cardId)??"",O):N(O)},[y,C,t==null?void 0:t.cardId,N]),M=j.useCallback(()=>{y?S((t==null?void 0:t.cardId)??"",e.id):_(e.id)},[y,e.id,S,t==null?void 0:t.cardId,_]);return j.useEffect(()=>()=>{h.current=null,m.current=!1},[]),j.useEffect(()=>{const O=E==null?void 0:E.find(R=>R.filterId===e.id);if(O&&O.operation!=="in"){const R=n4e(O.operation);if(h.current!==R&&(r(R),h.current=R,m.current=!1),R==="between"||R==="not between"){const L=O.values[0],F=O.values[1];a(L!=null?String(L):""),u(F!=null?String(F):""),o("")}else{const L=O.values[0];o(L!=null?String(L):""),a(""),u("")}}else h.current!==null&&(o(""),a(""),u(""),!m.current&&h.current!==n&&(r(">="),m.current=!1),h.current=null),f(!1)},[E,e.id]),j.useEffect(()=>{d&&(n==="between"||n==="not between"?b===i&&x===l&&f(!1):g===s&&f(!1))},[d,n,s,g,i,l,b,x]),j.useEffect(()=>{if(!d)if(n==="between"||n==="not between"){const O=b&&b.trim()!=="",R=x&&x.trim()!=="";if(!O||!R){!O&&!R&&(p(()=>{M()}),h.current=n);return}const I=Number(b),L=Number(x);if(isNaN(I)||isNaN(L))return;const F={filterId:e.id,connectionType:e.database==="NA"?"api":"database",name:e.column,valueType:hi(e),operation:n,values:[I,L]};p(()=>{k(F)}),h.current=n}else{if(!g||g.trim()===""){p(()=>{M()}),h.current=null;return}const O=Number(g);if(isNaN(O))return;const R={filterId:e.id,connectionType:e.database==="NA"?"api":"database",name:e.column,valueType:hi(e),operation:n,values:[O]};p(()=>{k(R)}),h.current=n}},[n,g,b,x,e.id,e.column,e.database,d,k,M,e]),c.jsxs("div",{className:"flex gap-2",children:[c.jsxs(rt,{value:n,onValueChange:O=>{m.current=!0,r(O)},children:[c.jsx(tt,{className:"h-8 w-16",style:{borderRadius:w==null?void 0:w.controlInputRadius},children:c.jsx("span",{className:"font-mono text-base",children:(T=f3.find(O=>O.value===n))==null?void 0:T.symbol})}),c.jsx(nt,{children:f3.map(O=>c.jsx(ge,{value:O.value,children:c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-mono",children:O.symbol}),c.jsx("span",{children:O.label})]})},O.value))})]}),n==="between"||n==="not between"?c.jsxs(c.Fragment,{children:[c.jsx(Nn,{type:"number",placeholder:"Min",value:i,onChange:O=>a(O.target.value),className:"h-8 flex-1",style:{borderRadius:w==null?void 0:w.controlInputRadius}}),c.jsx(Nn,{type:"number",placeholder:"Max",value:l,onChange:O=>u(O.target.value),className:"h-8 flex-1",style:{borderRadius:w==null?void 0:w.controlInputRadius}})]}):c.jsx(Nn,{type:"number",placeholder:"Value",value:s,onChange:O=>o(O.target.value),className:"h-8 flex-1",style:{borderRadius:w==null?void 0:w.controlInputRadius}})]})}function zK({filter:e,storageOptions:t}){const n=e.searchMode==="numeric",r=Q(w=>w.themeStyle),{filteredRecords:s,isSingleSelect:o,allSelected:i,handleChange:a,handleSelectAll:l,handleApplyOperatorExpression:u,query:d,setQuery:f,isLoading:h,isFetching:m,isError:p,selectedRecords:g,isSearching:b,searchError:x,resultSource:y,activeFilterValue:v}=gx(e,{enableServerSearch:!0,searchDebounceMs:300,minSearchLength:2,searchThreshold:5,...t});return h||m?c.jsx(Ns,{style:{borderRadius:r==null?void 0:r.controlInputRadius},className:"h-8 w-full bg-foreground/10"}):p?c.jsx("div",{className:"flex h-8 w-full items-center bg-muted px-2 text-sm",children:"Error"}):n?c.jsx(r4e,{filter:e,storageOptions:t}):c.jsx(e4e,{showNegativeIndicator:e.operation==="not in",renderFilterModeButton:()=>c.jsx(s4e,{filter:e,storageOptions:t}),inputClassName:"h-8",options:s,selectedOptions:g,onChange:a,multiple:!o,selectAllChecked:i,onSelectAllCheckedChange:l,isSearching:b,resultSource:y,searchError:x,query:d,onQueryChange:f,filterDataType:e.dataType,activeFilterValue:v,onEnterKey:u})}function s4e({filter:e,storageOptions:t}){const n=e.operation==="in"?"include":"exclude",r=(t==null?void 0:t.storageTarget)==="card",{setFilterMode:s,setFilterDefaultValues:o}=Gt(),i=Q(S=>S.isDashboardEditing),a=Q(S=>S.isVisualEditing),l=Q(S=>S.filterValues),u=Q(S=>S.actions.setCardInlineFilterMode),d=Q(S=>S.actions.setCardInlineFilterDefaultValues),f=Q(S=>S.inlineFilterValuesMap[(t==null?void 0:t.cardId)||""]),h=Q(S=>S.actions.setCardInlineFilterValue),m=Ee(S=>S.card),{setCard:p}=lr(),g=r?t==null?void 0:t.inlineFilterValues:l,b=g==null?void 0:g.find(S=>S.filterId===e.id);function x(){const S=n==="include"?"exclude":"include",N=S==="exclude"?"not in":"in";if(r)if(a){const _=(m.inlineFilters||[]).map(k=>k.id===e.id?{...k,operation:N}:k);p({...m,inlineFilters:_});const E=f==null?void 0:f.find(k=>k.filterId===e.id);(E&&E.operation==="in"||(E==null?void 0:E.operation)==="not in")&&h((t==null?void 0:t.cardId)??"",{...E,operation:N})}else u((t==null?void 0:t.sheetId)??"",(t==null?void 0:t.cardId)??"",e.id,S);else s(e.id,S)}function y(){if(!(b!=null&&b.values))return;const S=b.values;if(r)if(a){const N=(m.inlineFilters||[]).map(_=>_.id===e.id?{..._,defaultValues:S}:_);p({...m,inlineFilters:N})}else d((t==null?void 0:t.sheetId)??"",(t==null?void 0:t.cardId)??"",e.id,S);else o(e.id,S)}const v=(b==null?void 0:b.values)&&b.values.length>0,w=e.defaultValues&&e.defaultValues.length>0,C=i||a;return c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:x,variant:"secondary",size:"sm",className:X("h-6 text-xs hover:underline",{}),children:Mg(n)}),C&&c.jsx(oe,{onClick:y,variant:w?"default":"ghost",size:"sm",className:X("h-6 text-xs",{"opacity-50":!v}),disabled:!v,title:w?"Update default values":v?"Set current selection as default":"Select values to set as default",children:"Default"})]})}function BK({filter:e,storageOptions:t}){var i;const{filteredRecords:n,handleChange:r,selectedRecords:s}=gx(e,t);function o(a){r([{value:a,id:a}])}return c.jsx(gi,{onValueChange:o,value:((i=s==null?void 0:s[0])==null?void 0:i.value)||"",className:"mt-2 flex gap-3 overflow-x-auto",children:n==null?void 0:n.map(a=>c.jsxs("div",{className:"flex gap-2",children:[c.jsx(Jn,{value:a.value,id:"r1"}),c.jsx(de,{className:"text-muted-foreground",htmlFor:"r1",children:a.value})]},a.value))})}function VK({filter:e,storageOptions:t}){var f;const n=Q(h=>h.themeStyle),{filteredRecords:r,handleChange:s,selectedRecords:o,isLoading:i,isFetching:a,isError:l}=gx(e,t),u=r&&r.length>10;function d(h){s([{value:h,id:h}])}return i||a?c.jsx(Ns,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 w-full bg-foreground/10"}):l?c.jsx("div",{className:"flex h-8 w-full items-center bg-muted px-2 text-sm",children:"Error loading filter options"}):c.jsxs("div",{className:"space-y-2",children:[u&&c.jsx("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:c.jsx(On,{children:c.jsxs(un,{delayDuration:0,children:[c.jsx(dn,{asChild:!0,children:c.jsxs("div",{className:"flex items-center gap-1 rounded-sm bg-amber-500/10 px-2 py-1",children:[c.jsx(tr,{className:"h-3 w-3 text-amber-600"}),c.jsxs("span",{className:"text-amber-600",children:["Many options (",r.length,")"]})]})}),c.jsx(pn,{side:"bottom",className:"max-w-xs",children:c.jsxs("p",{className:"text-xs",children:["This filter has ",r.length," options. Consider using a dropdown for better usability with many options."]})})]})})}),c.jsx(As,{value:((f=o==null?void 0:o[0])==null?void 0:f.value)||"",onValueChange:d,className:"w-full",children:c.jsx(cs,{className:"h-9 flex-wrap justify-start overflow-x-auto",children:r==null?void 0:r.map(h=>c.jsx(qt,{className:"h-7",value:h.value,children:h.value},h.value))})})]})}const o4e=j.createContext(null),Nj={didCatch:!1,error:null};class Da extends j.Component{constructor(t){super(t),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=Nj}static getDerivedStateFromError(t){return{didCatch:!0,error:t}}resetErrorBoundary(){const{error:t}=this.state;if(t!==null){for(var n,r,s=arguments.length,o=new Array(s),i=0;i<s;i++)o[i]=arguments[i];(n=(r=this.props).onReset)===null||n===void 0||n.call(r,{args:o,reason:"imperative-api"}),this.setState(Nj)}}componentDidCatch(t,n){var r,s;(r=(s=this.props).onError)===null||r===void 0||r.call(s,t,n)}componentDidUpdate(t,n){const{didCatch:r}=this.state,{resetKeys:s}=this.props;if(r&&n.error!==null&&i4e(t.resetKeys,s)){var o,i;(o=(i=this.props).onReset)===null||o===void 0||o.call(i,{next:s,prev:t.resetKeys,reason:"keys"}),this.setState(Nj)}}render(){const{children:t,fallbackRender:n,FallbackComponent:r,fallback:s}=this.props,{didCatch:o,error:i}=this.state;let a=t;if(o){const l={error:i,resetErrorBoundary:this.resetErrorBoundary};if(typeof n=="function")a=n(l);else if(r)a=j.createElement(r,l);else if(s!==void 0)a=s;else throw i}return j.createElement(o4e.Provider,{value:{didCatch:o,error:i,resetErrorBoundary:this.resetErrorBoundary}},a)}}function i4e(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];return e.length!==t.length||e.some((n,r)=>!Object.is(n,t[r]))}function h3({filter:e,storageOptions:t}){return Si(e.dataType)?c.jsx(rK,{filter:e,storageOptions:t}):e.uiType==="radio"&&e.type==="single"?c.jsx(BK,{filter:e,storageOptions:t}):e.uiType==="tabs"&&e.type==="single"?c.jsx(VK,{filter:e,storageOptions:t}):c.jsx(zK,{filter:e,storageOptions:t})}function a4e({filter:e,CustomFilterComponent:t,theme:n,storageOptions:r}){var v;const{filteredRecords:s,selectedRecords:o,handleChange:i,handleClear:a,handleSelectAll:l,query:u,setQuery:d,isLoading:f,isFetching:h,isError:m,isSearching:p,isSingleSelect:g,allSelected:b,activeFilterValue:x}=gx(e,{enableServerSearch:!0,...r}),y={filter:e,options:s||[],selectedValues:o||[],onChange:i,onClear:a,onSelectAll:l,searchQuery:u,onSearchChange:d,isLoading:f,isFetching:h,isError:m,isSearching:p,isSingleSelect:g,allSelected:b,activeFilterValue:x,theme:n,settings:(v=e.customFilterPreferences)==null?void 0:v.settings};return c.jsx(j.Suspense,{fallback:c.jsx(Ns,{className:"h-8 w-full bg-foreground/10"}),children:c.jsx(t,{...y})})}function l4e({filter:e,CustomFilterComponent:t,theme:n,storageOptions:r}){var y;const s=(r==null?void 0:r.storageTarget)==="card",{dateRange:o,initialDateRange:i,handleChange:a,handleRelativeChange:l,handleClear:u,handleReset:d,isLoading:f,isFetching:h,isError:m}=gR(e,r),p=Q(v=>v.filterValues),g=s?r==null?void 0:r.inlineFilterValues:p,b=g==null?void 0:g.find(v=>v.filterId===e.id),x={filter:e,dateRange:o,initialDateRange:i,onDateChange:a,onRelativeDateChange:l,onClear:u,onReset:d,isLoading:f,isFetching:h,isError:m,activeFilterValue:b,theme:n,settings:(y=e.customFilterPreferences)==null?void 0:y.settings};return c.jsx(j.Suspense,{fallback:c.jsx(Ns,{className:"h-8 w-full bg-foreground/10"}),children:c.jsx(t,{...x})})}function c4e({filter:e,storageOptions:t}){var h,m,p,g,b;const{theme:n}=Ob(),r=Q(x=>x.themeStyle),s={colors:((m=(h=r==null?void 0:r.chart)==null?void 0:h.dataset)==null?void 0:m.backgroundColor)||[],mode:n||"system"},{getFilter:o,isLoading:i,isError:a}=pS(((p=e.customFilterPreferences)==null?void 0:p.url)||""),l=(g=e.customFilterPreferences)==null?void 0:g.componentName,u=l?o(l):null;if(!l||!((b=e.customFilterPreferences)!=null&&b.url)||a||!i&&!u)return c.jsx(h3,{filter:e,storageOptions:t});if(i||!u)return c.jsx(Ns,{className:"h-8 w-full bg-foreground/10"});const f=Si(e.dataType);return c.jsx(Da,{fallback:c.jsx(h3,{filter:e,storageOptions:t}),onError:x=>console.error("Custom filter runtime error:",x),children:f?c.jsx(l4e,{filter:e,CustomFilterComponent:u,theme:s,storageOptions:t}):c.jsx(a4e,{filter:e,CustomFilterComponent:u,theme:s,storageOptions:t})})}const u4e=j.memo(c4e);function Cx({filter:e,storageOptions:t}){var n,r;return(n=e.customFilterPreferences)!=null&&n.url&&((r=e.customFilterPreferences)!=null&&r.componentName)?c.jsx(u4e,{filter:e,storageOptions:t}):Si(e.dataType)?c.jsx(rK,{filter:e,storageOptions:t}):e.uiType==="radio"&&e.type==="single"?c.jsx(BK,{filter:e,storageOptions:t}):e.uiType==="tabs"&&e.type==="single"?c.jsx(VK,{filter:e,storageOptions:t}):c.jsx(zK,{filter:e,storageOptions:t})}function d4e(e){return{id:e.id,connectionId:e.connectionId,title:e.title,column:e.column,dataType:e.dataType,table:e.table,database:e.database,sql:e.sql,operation:e.operation,type:e.type,uiType:e.uiType,dateSelectionMode:e.dateSelectionMode,defaultValues:e.defaultValues,defaultDateFilter:e.defaultDateFilter,searchMode:e.searchMode,customFilterPreferences:e.customFilterPreferences}}function HK({inlineFilter:e,sheetId:t,cardId:n,inlineFilterValues:r}){const s=d4e(e),o={storageTarget:"card",sheetId:t,cardId:n,inlineFilterValues:r},i=e.width??250,a=e.showLabel??!0;return c.jsxs("div",{className:"inline-filter-item flex flex-col gap-0.5",style:{width:i},children:[a&&c.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:e.title}),c.jsx(Cx,{filter:s,storageOptions:o})]})}function UK({card:e,sheetId:t,inlineFilterValues:n}){return!e.inlineFilters||e.inlineFilters.length===0?[]:e.inlineFilters.map(r=>c.jsx(HK,{inlineFilter:r,sheetId:t,cardId:e.id,inlineFilterValues:n},r.id))}function f4e({card:e,frame:t}){var I,L,F,V,$,P,U,B,A,Y,z,q;const[n,r]=j.useState([]),{theme:s}=Ob(),{authToken:o}=Ge(),i=V6(o==null?void 0:o.accessToken),a=Q(W=>W.themeStyle),l={colors:((L=(I=a==null?void 0:a.chart)==null?void 0:I.dataset)==null?void 0:L.backgroundColor)||[],mode:s||"system"},[u,d]=j.useState(!1),{getCard:f}=pS(((F=e.customCardPreferences)==null?void 0:F.url)||""),h=((V=e.customCardPreferences)==null?void 0:V.visualType)||"single",m=($=e.customCardPreferences)==null?void 0:$.componentName,{data:p}=pa(e),g=Pt(W=>W.interactionStates),b=Q(W=>{var H;return(H=W.dashboard)==null?void 0:H.id}),x=Q(W=>W.dashboard.filters),y=Q(W=>W.filterValues),v=Q(W=>W.selectedSheetId),w=Q(W=>W.inlineFilterValuesMap[e.id]),C=j.useMemo(()=>UK({card:e,sheetId:v||"",inlineFilterValues:w}),[e,v,w]),{cardFilters:S,cardFilterValues:N,shouldApplyDashboardFilters:_,contextMode:E}=j.useMemo(()=>rM({card:e,interactionStates:g,currentDashboardId:b,filters:x,filterValues:y,selectedSheetId:v}),[e,g,b,x,y,v]),k=j.useCallback((W,H)=>{r(G=>({...G,[W]:H}))},[]);if(!m)return null;const M=f(m),T=Object.keys(((P=e.customCardPreferences)==null?void 0:P.dataInputCardIds)||{}).map(W=>{var K,te,Z;const H=(te=(K=e.customCardPreferences)==null?void 0:K.dataInputCardIds)==null?void 0:te[W].cardId,G=(Z=t==null?void 0:t.cards)==null?void 0:Z.find(ee=>ee.id===H);return G||null});function O(W){d(W)}const R=((B=(U=e.preferences)==null?void 0:U.displayOptions)==null?void 0:B.allowScroll)??!0;return c.jsx("div",{className:X("semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2",R?"overflow-y-auto":"h-full overflow-hidden"),children:c.jsxs(j.Suspense,{fallback:c.jsx(c.Fragment,{}),children:[M&&h==="single"&&c.jsx(M,{params:i,theme:l,chartSettings:(A=e.customCardPreferences)==null?void 0:A.settings,settings:(Y=e.customCardPreferences)==null?void 0:Y.settings,onDataChange:k,data:(p==null?void 0:p.records)||[],filters:S,filterValues:[...N||[],...w||[]],inlineFilters:C}),M&&h==="multiple"&&c.jsxs("div",{children:[Object.keys(((z=e.customCardPreferences)==null?void 0:z.dataInputCardIds)||{}).map(W=>{var K,te,Z;const H=(te=(K=e.customCardPreferences)==null?void 0:K.dataInputCardIds)==null?void 0:te[W].cardId,G=(Z=t==null?void 0:t.cards)==null?void 0:Z.find(ee=>ee.id===H);if(G)return c.jsx(xG,{onLoadingStatus:O,onDataChange:k,dataInputIndex:W,card:G},G.id+W)}),h==="multiple"&&c.jsx("div",{className:X("flex flex-col gap-2",{"opacity-50":u}),children:c.jsx(M,{params:i,theme:l,onDataChange:k,chartSettings:(q=e.customCardPreferences)==null?void 0:q.settings,settings:T.map(W=>{var H;return(H=W==null?void 0:W.customCardPreferences)==null?void 0:H.settings}),data:T.map(W=>W!=null&&W.id?n==null?void 0:n[W.id]:[]),filters:S,filterValues:[...N||[],...w||[]],inlineFilters:C})})]})]},e.id)})}const ER=j.memo(f4e,(e,t)=>{var n,r,s,o;return e.card.id===t.card.id&&e.card.inlineFilters===t.card.inlineFilters&&e.frame.id===t.frame.id&&((n=e.card.customCardPreferences)==null?void 0:n.url)===((r=t.card.customCardPreferences)==null?void 0:r.url)&&((s=e.card.customCardPreferences)==null?void 0:s.componentName)===((o=t.card.customCardPreferences)==null?void 0:o.componentName)});function wS({customerFacingMessage:e,error:t,resetErrorBoundary:n}){return c.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center rounded-lg border border-dashed border-muted-foreground/25 bg-muted/30 p-6 text-center",children:[c.jsx("div",{className:"mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:c.jsx("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"})})}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"Chart Unavailable"}),c.jsx("p",{className:"mb-4 text-xs text-muted-foreground",children:e||"Couldn't display this chart right now. Please try refreshing or check your data configuration."}),c.jsxs("button",{onClick:n,className:"inline-flex items-center justify-center rounded-md bg-primary px-3 py-2 text-xs font-medium text-primary-foreground shadow-sm transition-colors hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",children:[c.jsx("svg",{className:"mr-1.5 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Try Again"]}),c.jsxs("details",{className:"mt-4 w-full text-left",children:[c.jsx("summary",{className:"cursor-pointer text-xs text-muted-foreground hover:text-foreground",children:"Show technical details"}),c.jsxs("div",{className:"mt-2 rounded border bg-background p-3",children:[c.jsx("p",{className:"mb-1 text-xs font-medium text-foreground",children:"Error Details:"}),c.jsx("pre",{className:"text-xs text-muted-foreground",children:t.message})]})]})]})}function SS({error:e}){return c.jsx("div",{className:"flex flex-col items-center justify-center",role:"alert",style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",width:"100%"},children:c.jsxs("div",{style:{backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",boxShadow:"0 2px 6px rgba(0, 0, 0, 0.08)",color:"#b91c1c",fontFamily:"sans-serif",padding:"16px",textAlign:"center",flexDirection:"column",whiteSpace:"pre-wrap",position:"relative"},className:"flex flex-col justify-center space-y-1 rounded-md bg-muted p-10",children:[c.jsx("p",{className:"text-sm",children:"Something went wrong:"}),c.jsx("pre",{className:"text-xs",children:e.message})]})})}function h4e({error:e,frame:t}){return c.jsxs("div",{className:"flex h-full flex-col items-center justify-center border",role:"alert",children:[c.jsx(nZ,{frame:t,isHovered:!1}),c.jsx("div",{className:"flex flex-col justify-center space-y-2 rounded-md p-10"}),c.jsxs("div",{className:"flex flex-col justify-center space-y-2 rounded-md p-10",children:[c.jsx("p",{className:"text-lg font-semibold",children:"Oops! Looks like we tripped on a loose wire!"}),c.jsx("p",{className:"text-sm",children:"Something went wrong:"}),c.jsx("pre",{className:"text-xs",children:e.message})]})]})}function m4e(e={},t){const{displayPreferences:n,shouldShowElement:r}=Uc(),s=n.mode==="table-print",o=e.enabled??!0,i=e.serverSide??!1,a=s?Number.MAX_SAFE_INTEGER:e.pageSize||50,l=e.currentPage!==void 0,[u,d]=j.useState(0),[f,h]=j.useState(a),m=l?(e.currentPage||1)-1:u,p=s?Number.MAX_SAFE_INTEGER:l?e.pageSize||a:f,g=j.useMemo(()=>o&&r("showPagination")&&!s,[o,r,s]),b=j.useMemo(()=>i?e.pageCount:Math.ceil(t/p),[i,e.pageCount,t,p]),x=j.useMemo(()=>i?e.totalCount||0:t,[i,e.totalCount,t]),y=j.useMemo(()=>i?(e.currentPage||1)>1:m>0,[i,e.currentPage,m]),v=j.useMemo(()=>i?(e.currentPage||1)<(e.pageCount||1):m<(b||1)-1,[i,e.currentPage,e.pageCount,m,b]);return{pageIndex:m,pageSize:p,isServerSidePagination:i,showPagination:g,paginationEnabled:o,isTablePrintDisplayMode:s,setPageIndex:_=>{var E;l?(E=e.onPageChange)==null||E.call(e,_+1,p):d(_)},setPageSize:_=>{var E;l?(E=e.onPageChange)==null||E.call(e,1,_):(d(0),h(_))},canPreviousPage:y,canNextPage:v,previousPage:()=>{var E;if(!y)return;const _=m-1;l?(E=e.onPageChange)==null||E.call(e,_+1,p):d(_)},nextPage:()=>{var E;if(!v)return;const _=m+1;l?(E=e.onPageChange)==null||E.call(e,_+1,p):d(_)},pageCount:b,totalCount:x}}function p4e(e,t,n){var l;if(!t.length)return e;const r=t[0].id,s=t[0].desc?-1:1,o=((l=n.groupByColumns)==null?void 0:l.length)||0,i=r.startsWith("rowLevel"),a=i?parseInt(r.replace("rowLevel","")):-1;return i?g4e(e,a,s):b4e(e,r,s,o,n)}function g4e(e,t,n){const r=[...e],s=new Map,o=[];r.forEach(l=>{if(l.isGrandTotal)return;const u=t>0?l.fieldValues.slice(0,t).join("|||"):"root";s.has(u)||(s.set(u,[]),o.push(u)),s.get(u).push(l)});const i=[];o.forEach(l=>{const u=s.get(l),d=u.filter(h=>!h.isSubtotal),f=u.filter(h=>h.isSubtotal);d.sort((h,m)=>{const p=h.fieldValues[t],g=m.fieldValues[t];return p===g?0:p==null?1:g==null?-1:String(p).localeCompare(String(g))*n}),i.push(...d),i.push(...f)});const a=e.find(l=>l.isGrandTotal);return a&&i.push(a),i}function b4e(e,t,n,r,s){const o={rows:[],children:new Map};let i;e.forEach(f=>{if(f.isGrandTotal){i=f;return}if(f.isSubtotal){let h=o;for(let m=0;m<r-1;m++){const p=f.fieldValues[m];h.children.has(p)||h.children.set(p,{rows:[],children:new Map}),h=h.children.get(p)}h.subtotal=f}else{let h=o;for(let m=0;m<r-1;m++){const p=f.fieldValues[m];h.children.has(p)||h.children.set(p,{rows:[],children:new Map}),h=h.children.get(p)}h.rows.push(f)}});function a(f){var h;return t==="rowTotal"?s.columnHeaders.reduce((m,p)=>{var b;const g=(b=f.cells[p])==null?void 0:b.value;return m+(typeof g=="number"?g:0)},0):(h=f.cells[t])==null?void 0:h.value}function l(f){let h=0;return f.rows.forEach(m=>{const p=a(m);typeof p=="number"&&(h+=p)}),f.children.forEach(m=>{if(m.subtotal){const p=a(m.subtotal);typeof p=="number"&&(h+=p)}else h+=l(m)}),h}function u(f){const h=[],m=[...f.rows].sort((g,b)=>{const x=a(g),y=a(b);return x===y?0:x==null?1:y==null?-1:x>y?n:-n});return h.push(...m),Array.from(f.children.entries()).sort(([,g],[,b])=>{const x=g.subtotal?a(g.subtotal):l(g),y=b.subtotal?a(b.subtotal):l(b);return x===y?0:x==null?1:y==null?-1:x>y?n:-n}).forEach(([,g])=>{h.push(...u(g))}),f.subtotal&&h.push(f.subtotal),h}const d=u(o);return i&&d.push(i),d}function x4e(e,t){const[n,r]=j.useState([]),s=j.useMemo(()=>p4e(e,n,t),[e,n,t]),o=j.useCallback(l=>{r(u=>{const d=u.find(f=>f.id===l);return d?d.desc?[]:[{id:l,desc:!0}]:[{id:l,desc:!1}]})},[]),i=j.useCallback(()=>{r([])},[]),a=j.useCallback(l=>{const u=n.find(d=>d.id===l);return u?u.desc?"desc":"asc":!1},[n]);return{sorting:n,setSorting:r,sortedTableData:s,toggleColumnSort:o,clearSorting:i,getSortDirection:a}}function ob(e,t,n,r){if(t){const s=el(e,t,n,r),o=lEe(e,t);return s==="-"||s===0?c.jsx("div",{className:"flex justify-end",children:c.jsx(Eu,{className:"h-3 w-3 text-muted-foreground"})}):o?c.jsx("span",{style:{backgroundColor:o.backgroundColor,color:o.color,padding:"0.125rem 0.25rem",borderRadius:"0.25rem"},children:s}):s}return typeof e=="object"&&(e==null?void 0:e.formattedValue)!==void 0?e.formattedValue==="-"||e.formattedValue===0?c.jsx("div",{className:"flex justify-end",children:c.jsx(Eu,{className:"h-3 w-3 text-muted-foreground"})}):e.formattedValue:typeof e=="number"?e===0||e===null?c.jsx("div",{className:"flex justify-end",children:c.jsx(Eu,{className:"h-3 w-3 text-muted-foreground"})}):e.toLocaleString():e==null?c.jsx("div",{className:"flex justify-end",children:c.jsx(Eu,{className:"h-3 w-3 text-muted-foreground"})}):(e==null?void 0:e.toString())||c.jsx("div",{className:"flex justify-end",children:c.jsx(Eu,{className:"h-3 w-3 text-muted-foreground"})})}function y4e(e){return(e==null?void 0:e.includes("_SUM_"))||(e==null?void 0:e.includes("_AVG_"))||(e==null?void 0:e.includes("_COUNT_"))||(e==null?void 0:e.includes("_MIN_"))||(e==null?void 0:e.includes("_MAX_"))}function v4e(e,t){const n=(e==null?void 0:e.includes("_SUM_ALL"))||(e==null?void 0:e.includes("_AVG_ALL"))||(e==null?void 0:e.includes("_COUNT_ALL"))||(e==null?void 0:e.includes("_MIN_ALL"))||(e==null?void 0:e.includes("_MAX_ALL")),r=(t==null?void 0:t.some(s=>s.columnName===e&&(s.subtotalLevel==="grandTotal"||s.subtotalLevel==="ALL")))??!1;return n||r}function w4e({data:e,card:t,table:n,sorting:r,setSorting:s,showRowTotals:o,onAggregationChange:i,onOpenColumnSettings:a}){const[l,u]=j.useState(null),d=Q(m=>m.isVisualEditing),f=j.useCallback(m=>{var p;return(p=n.getHeaderGroups()[0])==null?void 0:p.headers.find(g=>g.column.id===m)},[n]);return{buildColumnHeaderRows:j.useCallback(()=>{var N,_;const m=((N=t.config)==null?void 0:N.pivotByColumns)||[],p=m.length,g=((_=e.groupByColumns)==null?void 0:_.length)||1,b=e.columnHeaders.length;function x(E,k,M,T=[]){E.forEach((O,R)=>{var L,F,V;const I=O.level;if(I<p){const $=O.columnKey||`${I}-${T.join("-")}-${O.name}-${R}`,P=O.children?1:p-I,U=`pivot-${$}`,B=l===U;if(M[I].push(c.jsx(ao,{colSpan:O.colspan,rowSpan:P,className:"h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-center text-xs font-medium",children:c.jsxs("div",{className:"group/pivot-header relative flex items-center justify-center",children:[i&&c.jsx("div",{className:X("absolute left-0 overflow-hidden transition-all duration-200",B?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/pivot-header:h-6 group-hover/pivot-header:w-6 group-hover/pivot-header:opacity-100"),children:c.jsx(Vp,{columnName:O.name,groupByFields:e.groupByColumns||[],pivotByFields:((L=t.config)==null?void 0:L.pivotByColumns)||[],currentAggregation:{rowAggregates:(F=t.config)==null?void 0:F.rowAggregates,columnAggregates:(V=t.config)==null?void 0:V.columnAggregates},onAggregationChange:i,onOpenChange:A=>u(A?U:null)})}),c.jsx("span",{className:"whitespace-nowrap",children:O.name})]})},$)),O.children){const A=[...T,O.name];x(O.children,I+1,M,A)}}})}function y(E,k=[]){const M=[];return E.forEach((T,O)=>{var R,I,L,F,V;if(T.columnKey){const $=T.columnKey||`metric-${k.join("-")}-${T.name}-${O}`,P=y4e(T.columnKey),U=v4e(T.columnKey,e.columnSubtotalMeta),B=n.getColumn(T.columnKey),A=f(T.columnKey);M.push(c.jsx(ao,{"data-column-id":T.columnKey,className:X("group/header h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-right text-xs last:border-r-0",U?"bg-muted font-semibold":P?"bg-muted/70 font-medium":""),style:{width:A==null?void 0:A.getSize(),minWidth:A==null?void 0:A.getSize(),maxWidth:A==null?void 0:A.getSize(),position:"relative",transition:"none"},children:B?c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs(oe,{variant:"ghost",className:"h-auto flex-shrink-0 p-0 hover:bg-transparent",onClick:()=>{const Y=B.getIsSorted();s(Y?Y==="asc"?[{id:B.id,desc:!0}]:[]:[{id:B.id,desc:!1}])},"aria-label":`Sort ${((R=e.columnDisplayNames)==null?void 0:R[T.columnKey])||T.name||"Metric"}`,children:[c.jsx(Fo,{className:X("mr-1 h-3 w-3",B.getIsSorted()==="asc"?"hidden group-hover/header:block":"hidden")}),c.jsx(ta,{className:X("mr-1 h-3 w-3",B.getIsSorted()==="desc"?"hidden group-hover/header:block":"hidden")}),c.jsx(ku,{className:X("mr-1 h-3 w-3",B.getIsSorted()?"hidden":"hidden group-hover/header:block")})]}),c.jsx("span",{className:"min-w-0 truncate text-xs font-medium",title:((I=e.columnDisplayNames)==null?void 0:I[T.columnKey])||T.name||"Metric",children:((L=e.columnDisplayNames)==null?void 0:L[T.columnKey])||T.name||"Metric"}),d&&a&&c.jsx(oe,{variant:"ghost",size:"icon",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover/header:opacity-100",onClick:Y=>{Y.stopPropagation(),a(T.columnKey)},children:c.jsx(Ju,{className:"h-3 w-3"})}),A&&c.jsx(Du,{header:A,isResizing:A.column.getIsResizing()})]}):c.jsx("span",{className:"block truncate px-2",title:((F=e.columnDisplayNames)==null?void 0:F[T.columnKey])||T.name||"Metric",children:((V=e.columnDisplayNames)==null?void 0:V[T.columnKey])||T.name||"Metric"})},$))}else if(T.children){const $=[...k,T.name];M.push(...y(T.children,$))}}),M}const v=c.jsxs(fr,{"data-header-type":"pivot-hierarchy","data-header-row-index":"0","data-repeat-header":"true",children:[e.groupByColumns&&e.groupByColumns.length>0?e.groupByColumns.map((E,k)=>{var I,L,F,V,$;const M=(I=n.getHeaderGroups()[0])==null?void 0:I.headers.find(P=>P.column.id===`rowLevel${k}`),T=M==null?void 0:M.getSize(),O=`row-header-${k}`,R=l===O;return c.jsx(ao,{rowSpan:p+2,"data-column-id":`rowLevel${k}`,className:"group/rowheader h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-left align-bottom text-xs font-medium",style:{width:T,minWidth:T,maxWidth:T,position:"relative",transition:"none"},children:c.jsxs("div",{className:"flex h-full min-w-0 items-end justify-between pb-1",children:[c.jsxs("div",{className:"relative flex min-w-0 items-center",children:[i&&c.jsx("div",{className:X("absolute left-0 top-1/2 -translate-y-1/2 overflow-hidden transition-all duration-200",R?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/rowheader:h-6 group-hover/rowheader:w-6 group-hover/rowheader:opacity-100"),children:c.jsx(Vp,{columnName:E.label||E.name,groupByFields:e.groupByColumns||[],pivotByFields:m,currentAggregation:{rowAggregates:(L=t.config)==null?void 0:L.rowAggregates,columnAggregates:(F=t.config)==null?void 0:F.columnAggregates},onAggregationChange:i,onOpenChange:P=>u(P?O:null)})}),c.jsxs(oe,{variant:"ghost",className:X("flex h-auto min-w-0 items-center gap-1 p-0 transition-all duration-200 hover:bg-transparent",i&&(R?"pl-7":"group-hover/rowheader:pl-7")),onClick:P=>{P.stopPropagation(),P.preventDefault(),s(U=>{const B=U.find(A=>A.id===`rowLevel${k}`);return B?B.desc?[]:[{id:`rowLevel${k}`,desc:!0}]:[{id:`rowLevel${k}`,desc:!1}]})},children:[c.jsx("span",{className:"truncate text-xs font-medium",title:E.label||E.name,children:E.label||E.name}),c.jsx(Fo,{className:X("h-3 w-3 flex-shrink-0",((V=r.find(P=>P.id===`rowLevel${k}`))==null?void 0:V.desc)===!1?"hidden group-hover/rowheader:block":"hidden")}),c.jsx(ta,{className:X("h-3 w-3 flex-shrink-0",(($=r.find(P=>P.id===`rowLevel${k}`))==null?void 0:$.desc)===!0?"hidden group-hover/rowheader:block":"hidden")}),c.jsx(ku,{className:X("h-3 w-3 flex-shrink-0",r.find(P=>P.id===`rowLevel${k}`)?"hidden":"hidden group-hover/rowheader:block")})]})]}),M&&c.jsx(Du,{header:M,isResizing:M.column.getIsResizing()})]})},`row-header-corner-${k}`)}):c.jsx(ao,{colSpan:g,rowSpan:p+2,className:"h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-xs",children:""}),c.jsx(ao,{colSpan:b,className:"h-8 whitespace-nowrap border-b bg-muted px-3 py-1 text-xs font-bold",children:c.jsxs("div",{className:"group/pivot-main relative flex items-center",children:[i&&(()=>{var M,T;const E="pivot-main",k=l===E;return c.jsx("div",{className:X("absolute left-0 top-1/2 -translate-y-1/2 overflow-hidden transition-all duration-200",k?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/pivot-main:h-6 group-hover/pivot-main:w-6 group-hover/pivot-main:opacity-100"),children:c.jsx(Vp,{columnName:"Pivot Columns",groupByFields:e.groupByColumns||[],pivotByFields:m,currentAggregation:{rowAggregates:(M=t.config)==null?void 0:M.rowAggregates,columnAggregates:(T=t.config)==null?void 0:T.columnAggregates},onAggregationChange:i,onOpenChange:O=>u(O?E:null)})})})(),c.jsx("div",{className:X("transition-all duration-200",i&&(l==="pivot-main"?"pl-7":"group-hover/pivot-main:pl-7")),children:m.map((E,k)=>c.jsxs("span",{className:"inline-flex items-center",children:[E.label,k<m.length-1&&c.jsx(Go,{className:"mx-1 inline-block h-4 w-4 text-muted-foreground"})]},E.id))})]})},"pivot-hierarchy"),o&&(()=>{var M;const E=(M=n.getHeaderGroups()[0])==null?void 0:M.headers.find(T=>T.column.id==="rowTotal"),k=E==null?void 0:E.getSize();return c.jsx(ao,{"data-column-id":"rowTotal",className:"group/total h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-center text-xs",rowSpan:p+2,style:{width:k,minWidth:k,maxWidth:k,position:"relative",transition:"none"},children:(()=>{const T=n.getColumn("rowTotal");return T?c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs(oe,{variant:"ghost",className:"h-auto flex-shrink-0 p-0 hover:bg-transparent",onClick:()=>{const O=T.getIsSorted();s(O?O==="asc"?[{id:T.id,desc:!0}]:[]:[{id:T.id,desc:!1}])},"aria-label":"Sort Total",children:[c.jsx(Fo,{className:X("mr-1 h-3 w-3",T.getIsSorted()==="asc"?"hidden group-hover/total:block":"hidden")}),c.jsx(ta,{className:X("mr-1 h-3 w-3",T.getIsSorted()==="desc"?"hidden group-hover/total:block":"hidden")}),c.jsx(ku,{className:X("mr-1 h-3 w-3",T.getIsSorted()?"hidden":"hidden group-hover/total:block")})]}),c.jsx("span",{className:"truncate text-xs font-medium",title:"Total",children:"Total"}),E&&c.jsx(Du,{header:E,isResizing:E.column.getIsResizing()})]}):"Total"})()},"pivot-hierarchy-total")})()]},"pivot-hierarchy"),w=[];if(e.columnGroups&&e.columnGroups.length>0){const E=Array.from({length:p},()=>[]);x(e.columnGroups,0,E,[]);for(let k=0;k<p;k++)w.push(c.jsx(fr,{"data-header-type":"pivot-values","data-header-row-index":k+1,"data-repeat-header":"true",children:E[k]},`pivot-row-${k}`))}let C=[];e.columnGroups&&e.columnGroups.length>0?C=y(e.columnGroups,[]):e.columnHeaders.forEach(E=>{var T,O,R,I,L,F;const k=n.getColumn(E),M=(T=n.getHeaderGroups()[0])==null?void 0:T.headers.find(V=>V.column.id===E);C.push(c.jsx(ao,{"data-column-id":E,className:"group/colheader h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-right text-xs last:border-r-0",style:{width:M==null?void 0:M.getSize(),minWidth:M==null?void 0:M.getSize(),maxWidth:M==null?void 0:M.getSize(),position:"relative",transition:"none"},children:k?c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs(oe,{variant:"ghost",className:"h-auto flex-shrink-0 p-0 hover:bg-transparent",onClick:()=>{const V=k.getIsSorted();s(V?V==="asc"?[{id:k.id,desc:!0}]:[]:[{id:k.id,desc:!1}])},"aria-label":`Sort ${((O=e.columnDisplayNames)==null?void 0:O[E])||E}`,children:[c.jsx(Fo,{className:X("mr-1 h-3 w-3",k.getIsSorted()==="asc"?"hidden group-hover/colheader:block":"hidden")}),c.jsx(ta,{className:X("mr-1 h-3 w-3",k.getIsSorted()==="desc"?"hidden group-hover/colheader:block":"hidden")}),c.jsx(ku,{className:X("mr-1 h-3 w-3",k.getIsSorted()?"hidden":"hidden group-hover/colheader:block")})]}),c.jsx("span",{className:"min-w-0 truncate text-xs font-medium",title:((R=e.columnDisplayNames)==null?void 0:R[E])||E,children:((I=e.columnDisplayNames)==null?void 0:I[E])||E}),d&&a&&c.jsx(oe,{variant:"ghost",size:"icon",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover/colheader:opacity-100",onClick:V=>{V.stopPropagation(),a(E)},children:c.jsx(Ju,{className:"h-3 w-3"})}),M&&c.jsx(Du,{header:M,isResizing:M.column.getIsResizing()})]}):c.jsx("span",{className:"block truncate px-2",title:((L=e.columnDisplayNames)==null?void 0:L[E])||E,children:((F=e.columnDisplayNames)==null?void 0:F[E])||E})},E))});const S=c.jsxs(fr,{"data-header-type":"metrics","data-header-row-index":p>0?p+1:0,"data-repeat-header":"true",children:[p===0&&(e.groupByColumns&&e.groupByColumns.length>0?e.groupByColumns.map((E,k)=>{var I,L,F,V;const M=(I=n.getHeaderGroups()[0])==null?void 0:I.headers.find($=>$.column.id===`rowLevel${k}`),T=M==null?void 0:M.getSize(),O=`metric-row-${k}`,R=l===O;return c.jsx(ao,{"data-column-id":`rowLevel${k}`,className:"group/metricrow h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-left text-xs font-medium",style:{width:T,minWidth:T,maxWidth:T,position:"relative",transition:"none"},children:c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs("div",{className:"relative flex min-w-0 items-center",children:[i&&c.jsx("div",{className:X("absolute left-0 top-1/2 -translate-y-1/2 overflow-hidden transition-all duration-200",R?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/metricrow:h-6 group-hover/metricrow:w-6 group-hover/metricrow:opacity-100"),children:c.jsx(Vp,{columnName:E.label||E.name,groupByFields:e.groupByColumns||[],pivotByFields:((L=t.config)==null?void 0:L.pivotByColumns)||[],currentAggregation:{rowAggregates:(F=t.config)==null?void 0:F.rowAggregates,columnAggregates:(V=t.config)==null?void 0:V.columnAggregates},onAggregationChange:i,onOpenChange:$=>u($?O:null)})}),c.jsxs(oe,{variant:"ghost",className:X("flex h-auto min-w-0 items-center gap-1 p-0 transition-all duration-200 hover:bg-transparent",i&&(R?"pl-7":"group-hover/metricrow:pl-7")),onClick:()=>{s($=>{const P=$.find(U=>U.id===`rowLevel${k}`);return P?P.desc===!1?[{id:`rowLevel${k}`,desc:!0}]:[]:[{id:`rowLevel${k}`,desc:!1}]})},children:[c.jsx("span",{className:"truncate text-xs font-medium",title:E.label||E.name,children:E.label||E.name}),(()=>{const $=r.find(P=>P.id===`rowLevel${k}`);return c.jsxs(c.Fragment,{children:[c.jsx(ku,{className:X("h-3 w-3 flex-shrink-0",$?"hidden":"hidden group-hover/metricrow:block")}),c.jsx(ta,{className:X("h-3 w-3 flex-shrink-0",($==null?void 0:$.desc)===!0?"hidden group-hover/metricrow:block":"hidden")}),c.jsx(Fo,{className:X("h-3 w-3 flex-shrink-0",($==null?void 0:$.desc)===!1?"hidden group-hover/metricrow:block":"hidden")})]})})()]})]}),M&&c.jsx(Du,{header:M,isResizing:M.column.getIsResizing()})]})},`row-header-title-${k}`)}):Array.from({length:g}).map((E,k)=>c.jsx(ao,{className:"h-8 whitespace-nowrap border-b border-r bg-muted py-1 text-left text-xs font-medium",children:`Level ${k+1}`},`empty-header-metric-${k}`))),C]},"metric-row");return p>0?[v,...w,S]:[S]},[e,t,n,r,s,o,i,f,l,u,d,a])}}function S4e(e,t,n){var v,w;const r=Q(C=>C.isVisualEditing);Q(C=>C.isDashboardEditing),Q(C=>C.selectedSheetId);const{updateCurrentDashboardCard:s,updateFrame:o}=Gt(),i=Ee(C=>{var S;return(S=C.actions)==null?void 0:S.setCardPreferences}),a=Ee(C=>C.card),l=j.useMemo(()=>{var C,S;return((S=(C=e==null?void 0:e.preferences)==null?void 0:C.tablePrefs)==null?void 0:S.columnSettingsMap)||{}},[(w=(v=e==null?void 0:e.preferences)==null?void 0:v.tablePrefs)==null?void 0:w.columnSettingsMap]),[u,d]=j.useState(!1),[f,h]=j.useState(null),[m,p]=j.useState(Bo()),g=j.useCallback(C=>{h(C);let S=l[C];if(!S){const N=t==null?void 0:t.map(_=>{var E,k;return{[C]:(k=(E=_.cells)==null?void 0:E[C])==null?void 0:k.value}});S=N&&N.length>0?Xg(C,N,n):Bo()}p(S),d(!0)},[l,t,n]),b=j.useCallback(()=>{var C,S;if(f&&m){const N={...l,[f]:m};if(r&&i){const _={...a.preferences,tablePrefs:{...(C=a.preferences)==null?void 0:C.tablePrefs,columnSettingsMap:N}};i(_)}else if(s){const _={...e,preferences:{...e.preferences,tablePrefs:{...(S=e.preferences)==null?void 0:S.tablePrefs,columnSettingsMap:N}}};s(_)}}d(!1)},[f,m,l,r,i,a,s,e]),x=j.useCallback(()=>{f&&p(Bo())},[f]),y=j.useCallback(()=>{var C,S;if(r&&i){const N={...a.preferences,tablePrefs:{...(C=a.preferences)==null?void 0:C.tablePrefs,columnSettingsMap:{}}};i(N)}else if(s){const N={...e,preferences:{...e.preferences,tablePrefs:{...(S=e.preferences)==null?void 0:S.tablePrefs,columnSettingsMap:{}}}};s(N)}d(!1)},[r,i,a,s,e]);return{columnSettings:l,columnSettingsOpen:u,activeColumnId:f,tempColumnSettings:m,isVisualEditing:r,openColumnSettings:g,applyColumnSettings:b,resetColumnSettings:x,resetAllColumnSettings:y,setColumnSettingsOpen:d,setTempColumnSettings:p}}function C4e({table:e,data:t,columns:n,subtotalColumnKeys:r,grandTotalColumnKeys:s,isTablePrintDisplayMode:o=!1,columnSettings:i,shouldVirtualizeRows:a=!1,virtualRows:l,paddingTop:u=0,paddingBottom:d=0,measureElement:f}){var x;const h=e.getRowModel().rows,m=((x=t.groupByColumns)==null?void 0:x.length)||1,g=a&&l&&l.length>0?l:h,b=n.length||1;return h!=null&&h.length?c.jsxs(c.Fragment,{children:[a&&u>0&&c.jsx(fr,{"aria-hidden":!0,className:"pointer-events-none border-none",children:c.jsx(yn,{colSpan:b,style:{height:u,padding:0,border:"none"}})}),g.map((y,v)=>{const w=a?y.index:v,C=a?h[w]:y;if(!C)return null;const S=C.original,N=e.getRowModel().rows,_=w===N.length-1;return c.jsx(fr,{ref:a&&f?E=>f(E):void 0,className:X("h-8 border-b-0",S.isSubtotal&&"border-t border-t-border/50 bg-muted/70 font-medium"),"data-row-type":S.isSubtotal?"subtotal":"data","data-row-index":w,...S.isSubtotal&&{"data-subtotal-level":S.subtotalLevel},children:C.getVisibleCells().map(E=>{var O;const k=E.column.id;if(k.startsWith("rowLevel")){const R=parseInt(k.replace("rowLevel",""));if(S.isSubtotal&&S.subtotalLevel){const L=((O=t.groupByColumns)==null?void 0:O.findIndex(F=>(F.alias||F.name)===S.subtotalLevel))??-1;return R===L?c.jsx(yn,{colSpan:o?1:m-R,className:X("h-8 whitespace-nowrap border-r px-3 py-1 text-xs font-medium",!_&&"border-b"),children:Gs(E.column.columnDef.cell,E.getContext())},E.id):R<L?c.jsx(yn,{className:X("h-8 whitespace-nowrap border-r px-3 py-1 text-xs font-medium",!_&&"border-b"),children:Gs(E.column.columnDef.cell,E.getContext())},E.id):o?c.jsx(yn,{className:X("h-8 whitespace-nowrap border-r px-3 py-1 text-xs",!_&&"border-b")},E.id):null}if(!a&&!o&&w>0)for(let L=w-1;L>=0;L--){const F=N[L].original;if(F.isSubtotal||F.isGrandTotal)break;let V=!0;for(let $=0;$<=R;$++)if(S.fieldValues[$]!==F.fieldValues[$]){V=!1;break}if(V)return null}let I=1;if(!a&&!o)for(let L=w+1;L<N.length;L++){const F=N[L].original;if(F.isSubtotal||F.isGrandTotal)break;let V=!0;for(let $=0;$<=R;$++)if(S.fieldValues[$]!==F.fieldValues[$]){V=!1;break}if(V)I++;else break}return c.jsx(yn,{rowSpan:a?void 0:I,className:X("h-8 whitespace-nowrap border-r px-3 py-1 text-xs",!_&&"border-b"),children:Gs(E.column.columnDef.cell,E.getContext())},E.id)}const M=s.has(k),T=r.has(k);return c.jsx(yn,{"data-column-id":k,className:X("h-8 border-r px-3 py-1 text-xs last:border-r-0",!_&&"border-b",M?"bg-muted/50":T?"bg-muted/30":void 0),style:{width:E.column.getSize(),minWidth:E.column.getSize(),maxWidth:E.column.getSize(),transition:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.isSubtotal&&(i!=null&&i[k])?ob(E.getValue(),i[k]):Gs(E.column.columnDef.cell,E.getContext())},E.id)})},C.id)}),a&&d>0&&c.jsx(fr,{"aria-hidden":!0,className:"pointer-events-none border-none",children:c.jsx(yn,{colSpan:b,style:{height:d,padding:0,border:"none"}})})]}):c.jsx(fr,{className:"h-8",children:c.jsx(yn,{colSpan:n.length,className:"text-center",children:"No results."})})}function Wo({value:e,displayTitle:t=!0,onSave:n,placeholder:r,inputClassName:s,displayClassName:o,isEditable:i=!0,isPending:a=!1}){const[l,u]=j.useState(!1),[d,f]=j.useState(e||""),h=()=>{u(!1),d!==e&&n(d)},m=p=>{p.key==="Enter"?(u(!1),n(d)):p.key==="Escape"&&(u(!1),f(e||""))};return l?c.jsx("div",{className:"flex",children:c.jsx("input",{type:"text",value:d,onChange:p=>f(p.target.value),onBlur:h,onKeyDown:m,onMouseDown:p=>p.stopPropagation(),className:X("w-full border-b border-dashed focus:border-primary focus:outline-none",s),autoFocus:!0})}):c.jsxs("div",{className:X("relative cursor-pointer truncate",o,{"cursor-default":!i,"hover:text-primary":i}),onClick:()=>{!i||a||(u(!0),f(e||""))},title:t?e||r:void 0,children:[c.jsx("div",{className:"flex items-center justify-between gap-2",children:c.jsx("span",{className:X("truncate",{"text-muted-foreground":a}),children:e||c.jsx("span",{className:"text-muted-foreground",children:r})})}),a&&c.jsx("div",{className:"absolute inset-0 animate-pulse rounded bg-gradient-to-r from-transparent via-blue-100/30 to-transparent"})]})}function N4e({grandTotalRows:e,data:t,card:n,table:r,showRowTotals:s,columnSettings:o,onAggregationLabelChange:i}){return e.length===0?null:c.jsx(c.Fragment,{children:e.map((a,l)=>{var u;return c.jsxs(fr,{className:"h-8 font-semibold","data-row-type":"grandtotal","data-grandtotal":"true","data-grandtotal-index":l,children:[c.jsx(yn,{colSpan:((u=t.groupByColumns)==null?void 0:u.length)||1,className:"h-8 whitespace-nowrap border-r px-3 py-1 text-xs font-semibold",children:i?c.jsx(Wo,{value:(()=>{var h,m,p;const d=a.aggregateFunction||"SUM";return((p=(m=(h=n.config)==null?void 0:h.rowAggregates)==null?void 0:m.find(g=>g.function===d&&g.groupLevel==="ALL"))==null?void 0:p.label)||a.fieldValues[0]})(),placeholder:a.fieldValues[0],onSave:d=>{const f=a.aggregateFunction||"SUM";i({type:"row",level:"ALL",function:f,label:d})},displayClassName:"text-right"}):a.fieldValues[0]}),t.columnHeaders.map(d=>{var h,m;const f=(h=r.getHeaderGroups()[0])==null?void 0:h.headers.find(p=>p.column.id===d);return c.jsx(yn,{"data-column-id":d,className:"h-8 border-r px-3 py-1 text-right text-xs last:border-r-0",style:{width:f==null?void 0:f.getSize(),minWidth:f==null?void 0:f.getSize(),maxWidth:f==null?void 0:f.getSize(),transition:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ob((m=a.cells[d])==null?void 0:m.value,o==null?void 0:o[d])},d)}),s&&(()=>{var h;const d=(h=r.getHeaderGroups()[0])==null?void 0:h.headers.find(m=>m.column.id==="rowTotal"),f=d==null?void 0:d.getSize();return c.jsx(yn,{className:"h-8 px-3 py-1 text-right text-xs font-medium","data-column-id":"rowTotal",style:{width:f,minWidth:f,maxWidth:f,transition:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ob(Bq(a,t.columnHeaders))})})()]},a.id)})})}function j4e({groupByColumns:e,numRowLevels:t,onAggregationLabelChange:n,isTablePrintDisplayMode:r=!1}){const s=[];return e&&e.length>0?e.forEach((o,i)=>{s.push({id:`rowLevel${i}`,header:()=>c.jsx("div",{className:"group border border-border px-3 py-1 text-left font-medium text-muted-foreground",children:c.jsx("div",{className:"flex items-center gap-1",children:c.jsx("span",{className:"whitespace-nowrap",children:o.label||o.name})})}),accessorFn:a=>a.fieldValues[i],cell:({row:a,table:l})=>{const u=a.original;if(u.isSubtotal&&u.subtotalLevel){const m=(e==null?void 0:e.findIndex(p=>(p.alias||p.name)===u.subtotalLevel))??-1;if(i===m){const p=u.fieldValues[i];return c.jsx("div",{className:"whitespace-nowrap px-3 py-1 align-top text-xs font-medium",style:{gridColumn:`span ${t-i}`},children:p.includes(" Total")&&n?c.jsx(Wo,{value:p,placeholder:p,onSave:g=>{const b=u.aggregateFunction||"SUM";if(u.subtotalLevel&&e){const x=e.find(y=>(y.alias||y.name)===u.subtotalLevel);x&&n({type:"row",level:x.id,function:b,label:g})}},displayClassName:"text-left"}):p})}else if(i<m)return c.jsx("div",{className:"whitespace-nowrap px-3 py-1 align-top text-xs font-medium",children:u.fieldValues[i]});return r?c.jsx("div",{className:"whitespace-nowrap px-3 py-1 align-top text-xs"}):null}const d=l.getRowModel().rows,f=d.findIndex(m=>m.id===a.id);if(!r&&f>0)for(let m=f-1;m>=0;m--){const p=d[m].original;if(p.isSubtotal||p.isGrandTotal)break;let g=!0;for(let b=0;b<=i;b++)if(u.fieldValues[b]!==p.fieldValues[b]){g=!1;break}if(g)return null}let h=1;if(!r)for(let m=f+1;m<d.length;m++){const p=d[m].original;if(p.isSubtotal||p.isGrandTotal)break;let g=!0;for(let b=0;b<=i;b++)if(u.fieldValues[b]!==p.fieldValues[b]){g=!1;break}if(g)h++;else break}return c.jsx("div",{className:"whitespace-nowrap px-0 py-1 align-top text-xs",style:{gridRow:r?void 0:`span ${h}`},children:u.fieldValues[i]})}})}):s.push({id:"rowHeader",header:()=>c.jsx("div",{className:"px-3 py-1 text-left font-medium",children:"Row"}),accessorFn:o=>o.rowKey,cell:({getValue:o})=>c.jsx("div",{className:"min-w-[150px] max-w-[300px] border-x border-y border-border px-3 py-1",children:String(o())})}),s}function k4e({columnHeaders:e,columnDisplayNames:t,setSorting:n,columnSettings:r,contextTimezone:s,browserTimezone:o}){return e.map(i=>({id:i,accessorFn:a=>{var l;return(l=a.cells[i])==null?void 0:l.value},header:({column:a})=>{const l=(t==null?void 0:t[i])||i;return c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsx(oe,{variant:"ghost",className:"h-auto p-0 hover:bg-transparent",onClick:()=>{const u=a.getIsSorted();n(u?u==="asc"?[{id:a.id,desc:!0}]:[]:[{id:a.id,desc:!1}])},"aria-label":`Sort ${l}`,children:a.getIsSorted()==="asc"?c.jsx(Fo,{className:"mr-1 h-3 w-3"}):a.getIsSorted()==="desc"?c.jsx(ta,{className:"mr-1 h-3 w-3"}):c.jsx(ku,{className:"mr-1 h-3 w-3 opacity-0 group-hover:opacity-100"})}),c.jsx("span",{className:"text-xs font-medium",children:l})]})},cell:({getValue:a})=>{const l=a(),u=r==null?void 0:r[i],d=(u==null?void 0:u.textAlign)||"right",f=d==="left"?"text-left":d==="center"?"text-center":"text-right";return c.jsx("div",{className:`text-xs ${f}`,children:ob(l,u,s,o)})}}))}function E4e({columnHeaders:e,setSorting:t}){return{id:"rowTotal",header:({column:n})=>c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsx(oe,{variant:"ghost",className:"h-auto p-0 hover:bg-transparent",onClick:()=>{const r=n.getIsSorted();t(r?r==="asc"?[{id:n.id,desc:!0}]:[]:[{id:n.id,desc:!1}])},"aria-label":"Sort Total",children:n.getIsSorted()==="asc"?c.jsx(Fo,{className:"mr-1 h-3 w-3"}):n.getIsSorted()==="desc"?c.jsx(ta,{className:"mr-1 h-3 w-3"}):c.jsx(ku,{className:"mr-1 h-3 w-3 opacity-0 group-hover:opacity-100"})}),c.jsx("span",{className:"text-xs font-medium",children:"Total"})]}),cell:({row:n})=>{const r=n.original,s=Bq(r,e);return c.jsx("div",{className:"text-right text-xs font-medium",children:ob(s)})}}}function Nx({data:e,card:t,options:n={},onAggregationChange:r,onAggregationLabelChange:s}){var W,H,G;const o=Q(K=>K.themeStyle),{displayPreferences:i,shouldShowElement:a}=Uc(),l=i.mode==="table-print",u=j.useRef(null),d=n.showRowTotals??!1,{columnSizing:f,onColumnSizingChange:h}=XT({card:t}),{subtotalColumnKeys:m,grandTotalColumnKeys:p}=j.useMemo(()=>rEe(e.columnSubtotalMeta),[e.columnSubtotalMeta]),{tableData:g,grandTotalRows:b}=j.useMemo(()=>OT(e),[e]),{sorting:x,setSorting:y,sortedTableData:v}=x4e(g,e),{columnSettings:w,columnSettingsOpen:C,activeColumnId:S,tempColumnSettings:N,openColumnSettings:_,applyColumnSettings:E,resetColumnSettings:k,resetAllColumnSettings:M,setColumnSettingsOpen:T,setTempColumnSettings:O}=S4e(t,v,e.columnMetadata),R={...n.pagination},I=m4e(R,v.length),L=j.useMemo(()=>{var se;const K=[],te=((se=e.groupByColumns)==null?void 0:se.length)||1,Z=j4e({groupByColumns:e.groupByColumns,numRowLevels:te,onAggregationLabelChange:s,isTablePrintDisplayMode:l});K.push(...Z);const ee=k4e({columnHeaders:e.columnHeaders,columnDisplayNames:e.columnDisplayNames,setSorting:y,columnSettings:w,contextTimezone:void 0,browserTimezone:typeof window<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0});if(K.push(...ee),d){const ce=E4e({columnHeaders:e.columnHeaders,setSorting:y});K.push(ce)}return K},[e,d,s,y,l,w]),F=GT({data:v,columns:L,state:{sorting:x,columnSizing:f,pagination:{pageIndex:I.pageIndex,pageSize:I.pageSize}},onSortingChange:y,onPaginationChange:void 0,getCoreRowModel:qT(),getPaginationRowModel:!I.isServerSidePagination&&!I.isTablePrintDisplayMode?YT():void 0,manualPagination:I.isServerSidePagination||I.isTablePrintDisplayMode,manualSorting:!0,pageCount:I.pageCount,enableColumnResizing:!0,columnResizeMode:"onChange",onColumnSizingChange:h}),V=F.getRowModel().rows,P=!l&&V.length>75,U=QT({count:P?V.length:0,getScrollElement:()=>u.current,estimateSize:()=>32,overscan:10}),B=P?U.getVirtualItems():[],A=P&&B.length>0?B[0].start:0,Y=P&&B.length>0?U.getTotalSize()-B[B.length-1].end:0,{buildColumnHeaderRows:z}=w4e({data:e,card:t,table:F,sorting:x,setSorting:y,showRowTotals:d,onAggregationChange:r,onOpenColumnSettings:_}),q=z();return c.jsxs("div",{className:"flex h-full w-full flex-col gap-4",children:[c.jsxs(Cl,{ref:u,style:{borderRadius:o==null?void 0:o.cardBorderRadius},className:"relative h-full rounded-none border",onMouseDown:K=>K.stopPropagation(),children:[c.jsxs("table",{className:"w-full border-separate border-spacing-0 bg-background text-sm",onMouseDown:K=>K.stopPropagation(),"data-pivot-table":"true","data-row-levels":((W=e.groupByColumns)==null?void 0:W.length)||1,"data-pivot-levels":e.columnGroups&&((G=(H=t.config)==null?void 0:H.pivotByColumns)==null?void 0:G.length)||0,children:[c.jsx(ax,{className:"sticky top-0 z-20 bg-background",children:q}),c.jsx(Yh,{children:c.jsx(C4e,{table:F,data:e,columns:L,subtotalColumnKeys:m,grandTotalColumnKeys:p,isTablePrintDisplayMode:l,columnSettings:w,shouldVirtualizeRows:P,virtualRows:B,paddingTop:A,paddingBottom:Y,measureElement:P?U.measureElement:void 0})}),b.length>0&&c.jsx("tfoot",{className:"sticky bottom-0 z-10 border-t-2 border-t-border bg-muted","data-grandtotal":"true",children:c.jsx(N4e,{grandTotalRows:b,data:e,card:t,table:F,showRowTotals:d,columnSettings:w,onAggregationLabelChange:s})})]}),c.jsx(Zo,{orientation:"horizontal"}),c.jsx(Zo,{orientation:"vertical"})]}),I.showPagination&&c.jsx(KT,{totalColumns:L.length,pageCount:I.pageCount||F.getPageCount(),pageIndex:I.pageIndex,pageSize:I.pageSize,rowCount:I.totalCount,selectedRowCount:0,setPageIndex:I.setPageIndex,setPageSize:I.setPageSize,canPreviousPage:I.canPreviousPage,canNextPage:I.canNextPage,previousPage:I.previousPage,nextPage:I.nextPage,onClearSelection:()=>{}}),S&&c.jsx(ZT,{column:F.getColumn(S)||null,settings:N,onSettingsChange:O,onApply:E,onReset:k,onResetAll:M,open:C,onOpenChange:T,tableType:"pivot"})]})}function _4e({isOpen:e,onClose:t,frame:n,card:r,data:s}){var _;const[o,i]=j.useState(!1),a=Q(E=>E.isDownloadingPdf),{isError:l,isLoading:u,isFetching:d,cfg:f,data:h,handleDatapointClick:m,pagination:p}=ex(r),{customCards:g,placeholders:b}=Ge(),x=zm(r,h),y=j.useMemo(()=>(h==null?void 0:h.records)||[],[h==null?void 0:h.records]),v=()=>{var k,M,T,O,R,I,L;const E=h||s;if(E!=null&&E.records&&E.records.length>0)if((r==null?void 0:r.type)==="aggregateTable"){const F=E.records.find(P=>P.isGrandTotal),V=E.records.filter(P=>!P.isGrandTotal),$=Fq(V,F,E.groupByColumns||[],E.pivotSchema||[],r,(M=(k=r==null?void 0:r.preferences)==null?void 0:k.tablePrefs)==null?void 0:M.columnSettingsMap);sw($,`${(r==null?void 0:r.title)||"export"}.csv`)}else if((r==null?void 0:r.type)==="pivotTable"&&x)Vq(x.data,r,`${(r==null?void 0:r.title)||"export"}.csv`,{includeHeaders:!0,includeSubtotals:!0,includeGrandTotal:!0,showRowTotals:(T=x.options)==null?void 0:T.showRowTotals});else if((r==null?void 0:r.type)==="table"){const F=((R=(O=r==null?void 0:r.preferences)==null?void 0:O.tablePrefs)==null?void 0:R.columnSettingsMap)||{},V=((L=(I=r==null?void 0:r.preferences)==null?void 0:I.tablePrefs)==null?void 0:L.columnVisibility)||{},P=Object.keys(E.records[0]||{}).filter(U=>V[U]!==!1);kEe(E.records,F,P,`${(r==null?void 0:r.title)||"export"}.csv`,void 0,Intl.DateTimeFormat().resolvedOptions().timeZone)}else{const F=[],V=Object.keys(E.records[0]);F.push(V.join(","));for(const P of E.records){const U=V.map(B=>`"${(""+P[B]).replace(/"/g,'""')}"`);F.push(U.join(","))}const $=F.join(`
974
974
  `);sw($,`${(r==null?void 0:r.title)||"export"}.csv`)}},w=()=>{i(!0)},C=(r==null?void 0:r.type)==="table"||(r==null?void 0:r.type)==="aggregateTable",S=((_=r==null?void 0:r.preferences)==null?void 0:_.allowDownload)!==!1,N=()=>{if(!r)return null;if(l)return c.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[c.jsx(cD,{className:"size-8 text-destructive"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Error fetching data. Check your card settings."})]});if(u||d)return c.jsx("div",{className:"flex h-full w-full items-center justify-center",children:c.jsx(Rc,{size:"md",color:"muted","aria-label":"Loading data"})});if(h!=null&&h.records&&(h==null?void 0:h.records.length)===0)return b!=null&&b.NoRecords?c.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:b.NoRecords}):c.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[c.jsx(hD,{className:"size-8 text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(r.type==="table")return c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(lx,{card:r,data:y,paginationMetadata:p,onPaginationChange:()=>{},isLoading:u||d})});if(r.type==="pivotTable"&&x)return c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(Nx,{card:r,data:x.data,options:x.options,onAggregationChange:()=>{},onAggregationLabelChange:()=>{}})});if(r.type==="aggregateTable")return c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(fS,{card:r,data:(h==null?void 0:h.records)||[],groupByColumns:h==null?void 0:h.groupByColumns,pivotSchema:h==null?void 0:h.pivotSchema,paginationMetadata:p,onPaginationChange:()=>{},onAggregationChange:()=>{},isLoading:u||d})});if(r.type==="text")return c.jsx(Xs,{className:"overflow-y-auto break-words pr-2",children:c.jsx(Gh,{isLoading:u||d,card:r,data:(h==null?void 0:h.records)||[]})});if(r.type==="custom")return c.jsx(Da,{FallbackComponent:wS,children:c.jsx(ER,{frame:n,card:r})});if(f)return c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(dx,{cfg:f,onChartClick:()=>{},onDatapointClick:m})});if(g&&g.length>0){const E=g.find(k=>k.cardId===r.id);if(E&&E.content){const k=E.content;return c.jsx(k,{card:r})}}return null};return c.jsxs(c.Fragment,{children:[c.jsx(ls,{open:e,onOpenChange:t,children:c.jsxs(Ur,{className:"flex h-[80vh] w-[80vw] max-w-[80vw] flex-col gap-0 p-0 [&>button]:hidden",children:[c.jsxs(Wr,{className:"shrink-0 border-b px-6 py-4",children:[c.jsx(qr,{className:"text-lg font-semibold",children:(r==null?void 0:r.title)||"Visual"}),c.jsxs(Is,{className:"sr-only",children:["Expanded view of ",(r==null?void 0:r.title)||"visual"," card showing detailed data and export options"]})]}),c.jsxs("div",{className:"flex items-center gap-2 border-b px-6 py-3",children:[S&&c.jsxs(oe,{variant:"ghost",size:"sm",onClick:v,title:"Download CSV",children:[c.jsx(ki,{className:"mr-2 h-4 w-4"}),"CSV"]}),C&&c.jsxs(oe,{variant:"ghost",size:"sm",onClick:w,disabled:a,title:"Download PDF",children:[c.jsx(o1,{className:"mr-2 h-4 w-4"}),"PDF"]}),c.jsx(oe,{variant:"ghost",size:"icon",onClick:t,className:"ml-auto h-8 w-8",children:c.jsx(yt,{className:"h-4 w-4"})})]}),c.jsx("div",{className:"flex flex-1 overflow-hidden p-6",children:N()})]})}),o&&c.jsx(Kq,{isOpen:o,onClose:()=>i(!1),frame:n,card:r,data:h||s})]})}function _R(e){var o;const t=e.activeCardId,n=new Map,r=e.cards.map(i=>{const a=i.id,l=jr();return n.set(a,l),{...i,id:l}});let s=(o=r[0])==null?void 0:o.id;return t&&n.has(t)&&(s=n.get(t)),{...e,id:jr(),cards:r,activeCardId:s}}function D4e({emails:e,onChange:t}){const[n,r]=j.useState(""),[s,o]=j.useState(null),i=d=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d),a=()=>{if(o(null),!n.trim()){o("Please enter at least one email address");return}const d=n.split(/[,;]/).map(m=>m.trim()).filter(m=>m),f=d.filter(m=>!i(m));if(f.length>0){o(`Invalid email${f.length>1?"s":""}: ${f.join(", ")}`);return}const h=d.filter(m=>!e.includes(m));if(h.length===0){o("Email address already added");return}t([...e,...h]),r("")},l=d=>{t(e.filter(f=>f!==d))},u=d=>{d.key==="Enter"&&(d.preventDefault(),a())};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex gap-2",children:[c.jsx(jn,{type:"text",placeholder:"email@company.com, team@company.com",value:n,onChange:d=>{r(d.target.value),o(null)},onKeyPress:u,className:X(s&&"border-destructive")}),c.jsxs(oe,{type:"button",size:"sm",onClick:a,disabled:!n.trim(),children:[c.jsx(kr,{className:"h-4 w-4 mr-1"}),"Add"]})]}),s&&c.jsxs("div",{className:"flex items-center gap-2 text-sm text-destructive",children:[c.jsx(yd,{className:"h-4 w-4"}),s]}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Enter email addresses for external recipients. Separate multiple emails with commas."})]}),e.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"text-sm font-medium",children:["Added Emails (",e.length,")"]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(d=>c.jsxs(Oe,{variant:"secondary",className:"pl-3 pr-1 py-1 flex items-center gap-1",children:[c.jsx("span",{className:"text-xs",children:d}),c.jsx("button",{type:"button",onClick:()=>l(d),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:c.jsx(yt,{className:"h-3 w-3"})})]},d))})]})]})}function M4e({tenantUserIds:e,orgUserIds:t,onChangeTenantUsers:n,onChangeOrgUsers:r}){const[s,o]=j.useState(""),[i,a]=j.useState("");j.useEffect(()=>{const b=setTimeout(()=>{a(s)},300);return()=>clearTimeout(b)},[s]);const{users:l,isLoading:u,error:d}=XM({search:i,limit:50}),f=new Set([...e,...t]),h=l.map(b=>({id:b.id,name:b.name,email:b.email,type:b.type})),m=h.filter(b=>f.has(b.id)),p=b=>{const x=f.has(b.id);b.type==="tenant"?n(x?e.filter(y=>y!==b.id):[...e,b.id]):b.type==="organization"&&r(x?t.filter(y=>y!==b.id):[...t,b.id])},g=(b,x)=>{x==="tenant"?n(e.filter(y=>y!==b)):x==="organization"&&r(t.filter(y=>y!==b))};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"relative",children:[c.jsx(va,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),c.jsx(jn,{type:"text",placeholder:"Search users by name or email...",value:s,onChange:b=>o(b.target.value),className:"pl-9"})]}),f.size>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"text-sm font-medium",children:["Selected Users (",f.size,")"]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:m.map(b=>c.jsxs(Oe,{variant:"secondary",className:"pl-2 pr-1 py-1 flex items-center gap-1",children:[b.type==="organization"?c.jsx(xd,{className:"h-3 w-3"}):c.jsx(Sc,{className:"h-3 w-3"}),c.jsx("span",{className:"text-xs",children:b.name}),c.jsx("button",{type:"button",onClick:()=>g(b.id,b.type),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:c.jsx(yt,{className:"h-3 w-3"})})]},b.id))})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm text-muted-foreground",children:s?"Search Results":"Available Users"}),u?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx(Mn,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):d?c.jsx("div",{className:"text-sm text-destructive py-4 text-center",children:"Failed to load users. Please try again."}):h.length===0?c.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center",children:s?"No users found":"No users available"}):c.jsx(Xs,{className:"h-[300px] rounded-md border p-2",children:c.jsx("div",{className:"space-y-1",children:h.map(b=>{const x=f.has(b.id);return c.jsxs("div",{className:X("flex items-center gap-3 rounded-md p-2 hover:bg-muted/50 cursor-pointer",x&&"bg-primary/10"),onClick:()=>p(b),children:[c.jsx(nn,{checked:x,onCheckedChange:()=>p(b),onClick:y=>y.stopPropagation()}),c.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[b.type==="organization"?c.jsx(xd,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}):c.jsx(Sc,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-sm font-medium truncate",children:b.name}),c.jsx("div",{className:"text-xs text-muted-foreground truncate",children:b.email})]}),c.jsx(Oe,{variant:"outline",className:"text-xs",children:b.type==="organization"?"Org":"Tenant"})]})]},b.id)})})})]})]})}function T4e({groupIds:e,onChange:t}){const[n,r]=j.useState(""),{currentUser:s}=Ts(),{groups:o,isLoading:i,error:a}=QM({search:n,type:"all",limit:50}),l=o.filter(m=>(s==null?void 0:s.type)==="organization"?!0:(s==null?void 0:s.type)==="tenant"?m.type==="TENANT_GROUP"&&m.tenantId===s.tenantId:!1).map(m=>({id:m.id,name:m.name,description:m.description,type:m.type,memberCount:m.memberCount})),u=l.filter(m=>m.name.toLowerCase().includes(n.toLowerCase())||m.description&&m.description.toLowerCase().includes(n.toLowerCase())),d=l.filter(m=>e.includes(m.id)),f=m=>{e.includes(m)?t(e.filter(p=>p!==m)):t([...e,m])},h=m=>{t(e.filter(p=>p!==m))};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"relative",children:[c.jsx(va,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),c.jsx(jn,{type:"text",placeholder:"Search groups by name...",value:n,onChange:m=>r(m.target.value),className:"pl-9"})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",d.length,")"]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:d.map(m=>c.jsxs(Oe,{variant:"secondary",className:"pl-2 pr-1 py-1 flex items-center gap-1",children:[m.type==="ORG_GROUP"?c.jsx(xd,{className:"h-3 w-3"}):c.jsx(is,{className:"h-3 w-3"}),c.jsx("span",{className:"text-xs",children:m.name}),m.memberCount!==void 0&&c.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",m.memberCount,")"]}),c.jsx("button",{type:"button",onClick:()=>h(m.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:c.jsx(yt,{className:"h-3 w-3"})})]},m.id))})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm text-muted-foreground",children:n?"Search Results":"Available Groups"}),i?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx(Mn,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):a?c.jsx("div",{className:"text-sm text-destructive py-4 text-center",children:"Failed to load groups. Please try again."}):u.length===0?c.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center",children:n?"No groups found":"No groups available"}):c.jsx(Xs,{className:"h-[300px] rounded-md border p-2",children:c.jsx("div",{className:"space-y-1",children:u.map(m=>{const p=e.includes(m.id);return c.jsxs("div",{className:X("flex items-center gap-3 rounded-md p-2 hover:bg-muted/50 cursor-pointer",p&&"bg-primary/10"),onClick:()=>f(m.id),children:[c.jsx(nn,{checked:p,onCheckedChange:()=>f(m.id),onClick:g=>g.stopPropagation()}),c.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[m.type==="ORG_GROUP"?c.jsx(xd,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}):c.jsx(is,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-sm font-medium truncate",children:m.name}),m.description&&c.jsx("div",{className:"text-xs text-muted-foreground truncate",children:m.description})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[m.memberCount!==void 0&&c.jsxs(Oe,{variant:"outline",className:"text-xs",children:[m.memberCount," members"]}),c.jsx(Oe,{variant:"outline",className:"text-xs",children:m.type==="ORG_GROUP"?"Org":"Tenant"})]})]})]},m.id)})})})]})]})}const WK=j.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},s)=>c.jsx(Ca,{children:c.jsx(gS,{ref:s,align:t,sideOffset:n,className:X("w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));WK.displayName=gS.displayName;function R4e({value:e,onChange:t,className:n}){const[r,s]=j.useState(!1),[o,i]=j.useState("emails"),a=e.emails.length+e.tenantUserIds.length+e.orgUserIds.length+e.groupIds.length,l=f=>{t({...e,...f})},u=(f,h)=>{switch(h){case"email":l({emails:e.emails.filter(m=>m!==f)});break;case"tenantUser":l({tenantUserIds:e.tenantUserIds.filter(m=>m!==f)});break;case"orgUser":l({orgUserIds:e.orgUserIds.filter(m=>m!==f)});break;case"group":l({groupIds:e.groupIds.filter(m=>m!==f)});break}},d=()=>{const f=[];e.emails.length>0&&f.push(`${e.emails.length} email${e.emails.length!==1?"s":""}`);const h=e.tenantUserIds.length+e.orgUserIds.length;return h>0&&f.push(`${h} user${h!==1?"s":""}`),e.groupIds.length>0&&f.push(`${e.groupIds.length} group${e.groupIds.length!==1?"s":""}`),f.join(", ")};return c.jsxs("div",{className:X("space-y-2",n),children:[a>0&&c.jsx("div",{className:"space-y-2",children:c.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.emails.map(f=>c.jsxs(Oe,{variant:"secondary",className:"gap-1 pr-1",children:[c.jsx(gv,{className:"h-3 w-3"}),c.jsx("span",{className:"max-w-[150px] truncate text-xs",children:f}),c.jsx("button",{onClick:h=>{h.stopPropagation(),u(f,"email")},className:"ml-1 rounded-sm hover:bg-secondary-foreground/20",children:c.jsx(yt,{className:"h-3 w-3"})})]},f)),e.tenantUserIds.length+e.orgUserIds.length>0&&c.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[c.jsx(is,{className:"h-3 w-3"}),e.tenantUserIds.length+e.orgUserIds.length," users"]}),e.groupIds.length>0&&c.jsxs(Oe,{variant:"secondary",className:"gap-1",children:[c.jsx(iP,{className:"h-3 w-3"}),e.groupIds.length," groups"]})]})}),c.jsxs(ks,{open:r,onOpenChange:s,modal:!0,children:[c.jsx(Es,{asChild:!0,children:c.jsxs(oe,{variant:"outline",size:"sm",className:"w-full justify-start",children:[c.jsx(K8,{className:"mr-2 h-4 w-4"}),a>0?c.jsxs("span",{children:["Add more recipients (",d(),")"]}):"Add recipients"]})}),c.jsx(WK,{className:"z-[51] w-[500px] p-0",align:"start",side:"bottom",sideOffset:4,children:c.jsxs("div",{className:"p-4",children:[c.jsxs("div",{className:"mb-4",children:[c.jsx("h4",{className:"text-sm font-medium",children:"Select Recipients"}),c.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Choose who should receive the scheduled reports"})]}),c.jsxs(As,{value:o,onValueChange:f=>i(f),children:[c.jsxs(cs,{className:"grid w-full grid-cols-3",children:[c.jsxs(qt,{value:"emails",className:"flex items-center gap-2 text-xs",children:[c.jsx(gv,{className:"h-3 w-3"}),c.jsx("span",{children:"Emails"}),e.emails.length>0&&c.jsx(Oe,{variant:"secondary",className:"ml-1 h-4 px-1 text-xs",children:e.emails.length})]}),c.jsxs(qt,{value:"users",className:"flex items-center gap-2 text-xs",children:[c.jsx(is,{className:"h-3 w-3"}),c.jsx("span",{children:"Users"}),e.tenantUserIds.length+e.orgUserIds.length>0&&c.jsx(Oe,{variant:"secondary",className:"ml-1 h-4 px-1 text-xs",children:e.tenantUserIds.length+e.orgUserIds.length})]}),c.jsxs(qt,{value:"groups",className:"flex items-center gap-2 text-xs",children:[c.jsx(iP,{className:"h-3 w-3"}),c.jsx("span",{children:"Groups"}),e.groupIds.length>0&&c.jsx(Oe,{variant:"secondary",className:"ml-1 h-4 px-1 text-xs",children:e.groupIds.length})]})]}),c.jsxs("div",{className:"mt-4 max-h-[300px] overflow-y-auto",children:[c.jsx(nr,{value:"emails",className:"mt-0",children:c.jsx(D4e,{emails:e.emails,onChange:f=>l({emails:f})})}),c.jsx(nr,{value:"users",className:"mt-0",children:c.jsx(M4e,{tenantUserIds:e.tenantUserIds,orgUserIds:e.orgUserIds,onChangeTenantUsers:f=>l({tenantUserIds:f}),onChangeOrgUsers:f=>l({orgUserIds:f})})}),c.jsx(nr,{value:"groups",className:"mt-0",children:c.jsx(T4e,{groupIds:e.groupIds,onChange:f=>l({groupIds:f})})})]})]}),c.jsx("div",{className:"mt-4 border-t pt-4",children:c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("p",{className:"text-xs text-muted-foreground",children:a>0?`${a} recipient${a!==1?"s":""} selected`:"No recipients selected"}),c.jsx(oe,{size:"sm",onClick:()=>s(!1),className:"h-7",children:"Done"})]})})]})})]})]})}var qK={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},m3=j.createContext&&j.createContext(qK),I4e=["attr","size","title"];function A4e(e,t){if(e==null)return{};var n=P4e(e,t),r,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(s=0;s<o.length;s++)r=o[s],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function P4e(e,t){if(e==null)return{};var n={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(t.indexOf(r)>=0)continue;n[r]=e[r]}return n}function gw(){return gw=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},gw.apply(this,arguments)}function p3(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function bw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?p3(Object(n),!0).forEach(function(r){O4e(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):p3(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function O4e(e,t,n){return t=F4e(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function F4e(e){var t=$4e(e,"string");return typeof t=="symbol"?t:t+""}function $4e(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function YK(e){return e&&e.map((t,n)=>j.createElement(t.tag,bw({key:n},t.attr),YK(t.child)))}function ru(e){return t=>j.createElement(L4e,gw({attr:bw({},e.attr)},t),YK(e.child))}function L4e(e){var t=n=>{var{attr:r,size:s,title:o}=e,i=A4e(e,I4e),a=s||n.size||"1em",l;return n.className&&(l=n.className),e.className&&(l=(l?l+" ":"")+e.className),j.createElement("svg",gw({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,i,{className:l,style:bw(bw({color:e.color||n.color},n.style),e.style),height:a,width:a,xmlns:"http://www.w3.org/2000/svg"}),o&&j.createElement("title",null,o),e.children)};return m3!==void 0?j.createElement(m3.Consumer,null,n=>t(n)):t(qK)}function GK(e){return ru({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(e)}function z4e(e){return ru({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(e)}function KK(e){return ru({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(e)}function ZK(e){return ru({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(e)}function XK(e){return ru({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4 4m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z"},child:[]},{tag:"path",attr:{d:"M12 4v16"},child:[]},{tag:"path",attr:{d:"M4 15h8"},child:[]},{tag:"path",attr:{d:"M12 12h8"},child:[]},{tag:"path",attr:{d:"M16 12v8"},child:[]},{tag:"path",attr:{d:"M16 16h4"},child:[]}]})(e)}function QK(e){return ru({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(e)}function JK(e){return ru({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(e)}function eZ(e){return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 48 48",...e,children:c.jsxs("g",{stroke:"currentColor",strokeWidth:"3.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none",children:[c.jsx("line",{x1:"12",y1:"6",x2:"12",y2:"42"}),c.jsx("line",{x1:"12",y1:"12",x2:"32",y2:"12"}),c.jsx("line",{x1:"12",y1:"24",x2:"32",y2:"24"}),c.jsx("line",{x1:"12",y1:"36",x2:"32",y2:"36"}),c.jsx("line",{x1:"42",y1:"9",x2:"42",y2:"15"}),c.jsx("line",{x1:"44",y1:"21",x2:"44",y2:"27"}),c.jsx("line",{x1:"42",y1:"33",x2:"42",y2:"39"})]})})}const CS=[{id:"tableBuilder",icon:Yae,label:"Table Builder"},{id:"table",icon:Ty,label:"Table"},{id:"pivotTable",icon:Ty,label:"Pivot Table"},{id:"aggregateTable",icon:Ty,label:"Aggregate Table"},{id:"bar",icon:v8,label:"Bar Chart"},{id:"line",icon:S8,label:"Line Chart"},{id:"area",icon:y8,label:"Area Chart"},{id:"stackedBar",icon:w8,label:"Stacked Bar Chart"},{id:"combo",icon:N8,label:"Combo Chart"},{id:"stackedLine",icon:QK,label:"Stacked Line Chart"},{id:"scatter",icon:E8,label:"Scatter Chart"},{id:"bubble",icon:KK,label:"Bubble Chart"},{id:"pie",icon:k8,label:"Pie Chart"},{id:"doughnut",icon:I8,label:"Doughnut Chart"},{id:"funnel",icon:ZK,label:"Funnel Chart"},{id:"radar",icon:U8,label:"Radar Chart"},{id:"polarArea",icon:GK,label:"Polar Area Chart"},{id:"tornado",icon:G8,label:"Tornado Chart"},{id:"range",icon:j8,label:"Range Chart"},{id:"bullet",icon:eZ,label:"Bullet Chart"},{id:"treemap",icon:XK,label:"Treemap"},{id:"heatmap",icon:P8,label:"Heatmap"},{id:"kpi",icon:JK,label:"KPI"},{id:"text",icon:x8,label:"Text"},{id:"map",icon:V8,label:"Map"}],B4e=e=>{const t=e.toLowerCase();for(const n of CS)if(n.id==="doughnut"){if(t.includes("doughnut")||t.includes("donut")){const r=n.icon;return j.createElement(r,{className:"h-4 w-4"})}}else if(t.includes(n.id.toLowerCase())){const r=n.icon;return j.createElement(r,{className:"h-4 w-4"})}return null},V4e=(e,t="h-4 w-4")=>{const n=CS.find(r=>r.id===e);if(n){const r=n.icon;return j.createElement(r,{className:t})}return j.createElement(N8,{className:t})};function H4e({open:e,onOpenChange:t,dashboardId:n,onSelect:r,existingAttachments:s}){const[o,i]=j.useState(new Map),a=Q(g=>g.dashboard),l=j.useMemo(()=>(a==null?void 0:a.sheets)||[],[a]),u=Q(g=>g.selectedSheetId),d=l.find(g=>g.id===u),f=j.useMemo(()=>{var b;const g=[];if(g.push({id:"dashboard-full",title:`${(a==null?void 0:a.title)||"Dashboard"} (All Sheets)`,type:"dashboard",icon:c.jsx(U2,{className:"h-4 w-4"}),supportedFormats:["pdf"]}),l.length>1&&d&&g.push({id:`dashboard-${d.id}`,title:`${(a==null?void 0:a.title)||"Dashboard"} (${d.title})`,type:"dashboard",icon:c.jsx(ki,{className:"h-4 w-4"}),supportedFormats:["pdf"]}),d){const x=[];(b=d.frames)==null||b.forEach(y=>{var v;(v=y.cards)==null||v.forEach(w=>{if(w.type==="text")return;const C=V4e(w.type),S=AT(w.type);x.push({id:w.id,title:w.title||`${w.type} Chart`,type:"visual",visualId:w.id,cardType:w.type,icon:C,supportedFormats:S})})}),g.push(...x)}return g},[a,l,d]);j.useEffect(()=>{if(!e){i(new Map);return}if(s.length>0&&f.length>0){const g=new Map;s.forEach(b=>{const x=f.find(y=>{var v,w;if(b.type==="visual"&&b.visualId)return y.visualId===b.visualId;if(b.type==="dashboard"){if(((v=b.settings)==null?void 0:v.sheetSelection)==="all")return y.id==="dashboard-full";if((w=b.settings)!=null&&w.currentSheetId)return y.id===`dashboard-${b.settings.currentSheetId}`}return!1});x&&g.set(x.id,{item:x,format:b.format||"pdf"})}),i(g)}},[e,s,f]);const h=g=>{const b=new Map(o);if(b.has(g.id))b.delete(g.id);else{let x="pdf";g.type==="dashboard"?x="pdf":g.cardType?x=PT(g.cardType):x=g.supportedFormats.includes("csv")?"csv":"pdf",b.set(g.id,{item:g,format:x})}i(b)},m=(g,b)=>{const x=o.get(g);if(x){const y=new Map(o);y.set(g,{...x,format:b}),i(y)}},p=()=>{const g=[];o.forEach(({item:b,format:x})=>{const y={type:b.type,visualId:b.visualId,cardType:b.cardType,title:b.title,format:x,supportedFormats:b.supportedFormats,settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0}};b.type==="dashboard"&&(b.id==="dashboard-full"?y.settings.sheetSelection="all":d&&(y.settings.sheetSelection="current",y.settings.currentSheetId=d.id,y.settings.currentSheetName=d.title)),x==="csv"&&(y.settings.delimiter=",",y.settings.includeHeaders=!0,y.settings.useFormattedValues=!0),g.push(y)}),r(g),t(!1)};return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsxs(Ur,{className:"max-w-2xl",children:[c.jsx(Wr,{children:c.jsx(qr,{children:"Select Attachment"})}),c.jsx("div",{className:"space-y-4",children:c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(de,{children:"Select items to attach:"}),o.size>0&&c.jsxs("span",{className:"text-sm text-muted-foreground",children:[o.size," selected"]})]}),c.jsx("div",{className:"max-h-[400px] space-y-2 overflow-y-auto",children:f.map(g=>{var y;const b=o.has(g.id),x=((y=o.get(g.id))==null?void 0:y.format)||"pdf";return c.jsxs("div",{className:X("flex items-center gap-3 rounded-lg border p-3 transition-colors",b?"border-primary bg-primary/5":"border-border hover:bg-muted/50"),children:[c.jsx(nn,{checked:b,onCheckedChange:()=>h(g)}),c.jsx("div",{className:"flex-shrink-0",children:g.icon}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:g.title}),c.jsx("div",{className:"text-xs text-muted-foreground",children:g.type==="dashboard"?"Dashboard":"Visual"})]}),b&&c.jsxs(rt,{value:x,onValueChange:v=>m(g.id,v),children:[c.jsx(tt,{className:"h-7 w-20 text-xs",children:c.jsx(at,{})}),c.jsxs(nt,{children:[g.supportedFormats.includes("pdf")&&c.jsx(ge,{value:"pdf",children:"PDF"}),g.supportedFormats.includes("csv")&&c.jsx(ge,{value:"csv",children:"CSV"})]})]})]},g.id)})})]})}),c.jsxs(Rs,{children:[c.jsx(oe,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),c.jsxs(oe,{onClick:p,disabled:o.size===0,children:[c.jsx($r,{className:"mr-2 h-4 w-4"}),"Add"," ",o.size>1?`${o.size} Attachments`:"Attachment"]})]})]})})}function U4e({open:e,onOpenChange:t,attachment:n,onSave:r}){const[s,o]=j.useState(n.settings);j.useEffect(()=>{o(n.settings)},[n]);const i=()=>{r({...n,settings:s}),t(!1)};return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsxs(Ur,{className:"max-w-md",children:[c.jsx(Wr,{children:c.jsx(qr,{children:"Export Settings"})}),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsx(de,{className:"text-sm font-medium",children:n.title}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[n.type==="dashboard"?"Dashboard":"Visual"," • ",n.format.toUpperCase()]})]}),c.jsx(Ss,{}),n.format==="pdf"&&c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{htmlFor:"page-size",children:"Page Size"}),c.jsxs(rt,{value:s.pageSize||"letter",onValueChange:a=>o({...s,pageSize:a}),children:[c.jsx(tt,{id:"page-size",children:c.jsx(at,{})}),c.jsxs(nt,{children:[c.jsx(ge,{value:"letter",children:'Letter (8.5" × 11")'}),c.jsx(ge,{value:"a4",children:"A4 (210mm × 297mm)"}),c.jsx(ge,{value:"legal",children:'Legal (8.5" × 14")'}),c.jsx(ge,{value:"a3",children:"A3 (297mm × 420mm)"}),c.jsx(ge,{value:"tabloid",children:'Tabloid (11" × 17")'})]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{htmlFor:"orientation",children:"Orientation"}),c.jsxs(rt,{value:s.orientation||"portrait",onValueChange:a=>o({...s,orientation:a}),children:[c.jsx(tt,{id:"orientation",children:c.jsx(at,{})}),c.jsxs(nt,{children:[c.jsx(ge,{value:"portrait",children:"Portrait"}),c.jsx(ge,{value:"landscape",children:"Landscape"})]})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(nn,{id:"include-filters",checked:s.includeFilters!==!1,onCheckedChange:a=>o({...s,includeFilters:a})}),c.jsx(de,{htmlFor:"include-filters",className:"text-sm font-normal cursor-pointer",children:"Include applied filters"})]}),c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(nn,{id:"include-timestamp",checked:s.includeTimestamp!==!1,onCheckedChange:a=>o({...s,includeTimestamp:a})}),c.jsx(de,{htmlFor:"include-timestamp",className:"text-sm font-normal cursor-pointer",children:"Include timestamp"})]})]})]}),n.format==="csv"&&c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{htmlFor:"delimiter",children:"Delimiter"}),c.jsxs(rt,{value:s.delimiter||",",onValueChange:a=>o({...s,delimiter:a}),children:[c.jsx(tt,{id:"delimiter",children:c.jsx(at,{})}),c.jsxs(nt,{children:[c.jsx(ge,{value:",",children:"Comma (,)"}),c.jsx(ge,{value:";",children:"Semicolon (;)"}),c.jsx(ge,{value:"\\t",children:"Tab"})]})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(nn,{id:"include-headers",checked:s.includeHeaders!==!1,onCheckedChange:a=>o({...s,includeHeaders:a})}),c.jsx(de,{htmlFor:"include-headers",className:"text-sm font-normal cursor-pointer",children:"Include column headers"})]}),c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(nn,{id:"use-formatted",checked:s.useFormattedValues!==!1,onCheckedChange:a=>o({...s,useFormattedValues:a})}),c.jsx(de,{htmlFor:"use-formatted",className:"text-sm font-normal cursor-pointer",children:"Use formatted values"})]})]}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Formatted values preserve number formatting, dates, and currency symbols. Raw values export the underlying data."})]})]}),c.jsxs(Rs,{children:[c.jsx(oe,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),c.jsx(oe,{onClick:i,children:"Save Settings"})]})]})})}function W4e({attachments:e,onRemove:t,onUpdate:n}){const[r,s]=j.useState({open:!1,index:null}),o=(d,f)=>{const h=e[d],m={...h,format:f,settings:{...h.settings,...f==="csv"?{delimiter:",",includeHeaders:!0,useFormattedValues:!0}:{}}};n(d,m)},i=d=>d==="csv"?c.jsx(A8,{className:"h-4 w-4"}):c.jsx(ki,{className:"h-4 w-4"}),a=d=>d==="csv"?"text-green-600":"text-red-600",l=d=>{s({open:!0,index:d})},u=d=>{r.index!==null&&n(r.index,d),s({open:!1,index:null})};return c.jsxs("div",{className:"space-y-2",children:[e.map((d,f)=>{var h,m,p;return c.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg bg-muted/30",children:[c.jsx("div",{className:X("flex-shrink-0",a(d.format)),children:i(d.format)}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"font-medium text-sm truncate",children:d.title}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:[d.type==="dashboard"?"Dashboard":"Visual",((h=d.settings)==null?void 0:h.sheetSelection)==="all"&&" • All sheets",((m=d.settings)==null?void 0:m.sheetSelection)==="current"&&((p=d.settings)==null?void 0:p.currentSheetName)&&` • ${d.settings.currentSheetName}`]})]}),d.supportedFormats&&d.supportedFormats.length>1?c.jsxs(rt,{value:d.format,onValueChange:g=>o(f,g),children:[c.jsx(tt,{className:"w-24 h-8",children:c.jsx(at,{})}),c.jsxs(nt,{children:[d.supportedFormats.includes("pdf")&&c.jsx(ge,{value:"pdf",children:"PDF"}),d.supportedFormats.includes("csv")&&c.jsx(ge,{value:"csv",children:"CSV"})]})]}):c.jsx(Oe,{variant:"secondary",className:"uppercase",children:d.format}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>l(f),children:c.jsx(im,{className:"h-4 w-4"})}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive",onClick:()=>t(f),children:c.jsx(yt,{className:"h-4 w-4"})})]},f)}),r.open&&r.index!==null&&c.jsx(U4e,{open:r.open,onOpenChange:d=>s({...r,open:d}),attachment:e[r.index],onSave:u})]})}const DR=[{value:0,label:"Sun",shortLabel:"S"},{value:1,label:"Mon",shortLabel:"M"},{value:2,label:"Tue",shortLabel:"T"},{value:3,label:"Wed",shortLabel:"W"},{value:4,label:"Thu",shortLabel:"T"},{value:5,label:"Fri",shortLabel:"F"},{value:6,label:"Sat",shortLabel:"S"}],AE=[{value:"America/New_York",label:"Eastern Time (ET)",offset:"UTC-5"},{value:"America/Chicago",label:"Central Time (CT)",offset:"UTC-6"},{value:"America/Denver",label:"Mountain Time (MT)",offset:"UTC-7"},{value:"America/Los_Angeles",label:"Pacific Time (PT)",offset:"UTC-8"},{value:"Europe/London",label:"London (GMT)",offset:"UTC+0"},{value:"Europe/Paris",label:"Paris (CET)",offset:"UTC+1"},{value:"Asia/Tokyo",label:"Tokyo (JST)",offset:"UTC+9"},{value:"Asia/Shanghai",label:"Shanghai (CST)",offset:"UTC+8"},{value:"Australia/Sydney",label:"Sydney (AEDT)",offset:"UTC+11"},{value:"UTC",label:"UTC",offset:"UTC+0"}],ly=[...AE,{value:"America/Phoenix",label:"Phoenix (MST)",offset:"UTC-7"},{value:"America/Toronto",label:"Toronto (ET)",offset:"UTC-5"},{value:"America/Vancouver",label:"Vancouver (PT)",offset:"UTC-8"},{value:"America/Mexico_City",label:"Mexico City (CST)",offset:"UTC-6"},{value:"America/Sao_Paulo",label:"São Paulo (BRT)",offset:"UTC-3"},{value:"Europe/Berlin",label:"Berlin (CET)",offset:"UTC+1"},{value:"Europe/Moscow",label:"Moscow (MSK)",offset:"UTC+3"},{value:"Asia/Dubai",label:"Dubai (GST)",offset:"UTC+4"},{value:"Asia/Mumbai",label:"Mumbai (IST)",offset:"UTC+5:30"},{value:"Asia/Singapore",label:"Singapore (SGT)",offset:"UTC+8"},{value:"Asia/Hong_Kong",label:"Hong Kong (HKT)",offset:"UTC+8"},{value:"Australia/Melbourne",label:"Melbourne (AEDT)",offset:"UTC+11"},{value:"Pacific/Auckland",label:"Auckland (NZDT)",offset:"UTC+13"}];function q4e({value:e,onChange:t,className:n}){var i;const r=j.useMemo(()=>Intl.DateTimeFormat().resolvedOptions().timeZone,[]),s=j.useMemo(()=>{var l;const a=ly.find(u=>u.value===e);return a?a.label:e===r?`${(l=e.split("/").pop())==null?void 0:l.replace(/_/g," ")}`:e},[e,r]),o=j.useMemo(()=>{var l;const a=ly.find(u=>u.value===e);return a?`${a.label} (${a.offset})`:e===r?`${(l=e.split("/").pop())==null?void 0:l.replace(/_/g," ")} (Browser)`:e},[e,r]);return c.jsx("div",{className:X("relative",n),children:c.jsxs(rt,{value:e||r,onValueChange:t,children:[c.jsx(tt,{className:"w-full",title:o,children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(i1,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"truncate",children:s})]})}),c.jsxs(nt,{className:"w-full max-h-[300px]",children:[r&&!ly.find(a=>a.value===r)&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"px-2 py-1.5 text-xs font-medium text-muted-foreground",children:"Your timezone"}),c.jsx(ge,{value:r,children:c.jsxs("div",{className:"flex items-center justify-between w-full",children:[c.jsx("span",{children:(i=r.split("/").pop())==null?void 0:i.replace(/_/g," ")}),c.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:"(Browser)"})]})}),c.jsx("div",{className:"my-1 h-px bg-border"})]}),c.jsx("div",{className:"px-2 py-1.5 text-xs font-medium text-muted-foreground",children:"Common timezones"}),AE.map(a=>c.jsx(ge,{value:a.value,children:c.jsxs("div",{className:"flex items-center justify-between w-full",children:[c.jsx("span",{children:a.label}),c.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:a.offset})]})},a.value)),c.jsx("div",{className:"my-1 h-px bg-border"}),c.jsx("div",{className:"px-2 py-1.5 text-xs font-medium text-muted-foreground",children:"Other timezones"}),ly.filter(a=>!AE.find(l=>l.value===a.value)).map(a=>c.jsx(ge,{value:a.value,children:c.jsxs("div",{className:"flex items-center justify-between w-full",children:[c.jsx("span",{children:a.label}),c.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:a.offset})]})},a.value))]})]})})}function Y4e({value:e,onChange:t,className:n}){const r=j.useMemo(()=>{const o=[];for(let i=0;i<24;i++)for(let a=0;a<60;a+=30){const l=`${i.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`;let u;i===0?u=12:i>12?u=i-12:u=i;const d=i<12?"AM":"PM",f=`${u}:${a.toString().padStart(2,"0")} ${d}`;o.push({value:l,label:f})}return o},[]),s=j.useMemo(()=>{const o=r.find(i=>i.value===e);return(o==null?void 0:o.label)||e},[e,r]);return c.jsxs(rt,{value:e,onValueChange:t,children:[c.jsx(tt,{className:X("w-full",n),children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(ml,{className:"h-4 w-4 text-muted-foreground"}),c.jsx(at,{placeholder:"Select time",children:s})]})}),c.jsx(nt,{className:"max-h-[300px]",children:r.map(o=>c.jsx(ge,{className:"hover:bg-muted",value:o.value,children:o.label},o.value))})]})}function G4e({value:e=[],onChange:t,disabled:n=!1,className:r}){const s=h=>{if(n)return;const m=e.includes(h)?e.filter(p=>p!==h):[...e,h];t(m.sort())},o=()=>{n||t([1,2,3,4,5])},i=()=>{n||t([0,6])},a=()=>{n||t([0,1,2,3,4,5,6])},l=()=>{n||t([])},u=[1,2,3,4,5].every(h=>e.includes(h))&&e.length===5,d=e.includes(0)&&e.includes(6)&&e.length===2,f=e.length===7;return c.jsxs("div",{className:X("space-y-3",r),children:[c.jsxs("div",{className:"flex flex-wrap gap-2",children:[c.jsx(oe,{type:"button",variant:u?"default":"outline",size:"sm",onClick:o,disabled:n,className:"h-7 text-xs",children:"Weekdays"}),c.jsx(oe,{type:"button",variant:d?"default":"outline",size:"sm",onClick:i,disabled:n,className:"h-7 text-xs",children:"Weekends"}),c.jsx(oe,{type:"button",variant:f?"default":"outline",size:"sm",onClick:a,disabled:n,className:"h-7 text-xs",children:"Every day"}),e.length>0&&c.jsx(oe,{type:"button",variant:"ghost",size:"sm",onClick:l,disabled:n,className:"h-7 text-xs",children:"Clear"})]}),c.jsx("div",{className:"grid grid-cols-7 gap-2",children:DR.map(h=>c.jsxs("div",{className:X("flex flex-col items-center space-y-2",n&&"opacity-50"),children:[c.jsx(de,{htmlFor:`weekday-${h.value}`,className:X("text-xs font-medium cursor-pointer select-none",n&&"cursor-not-allowed"),children:h.shortLabel}),c.jsx(nn,{id:`weekday-${h.value}`,checked:e.includes(h.value),onCheckedChange:()=>s(h.value),disabled:n,className:"h-5 w-5"}),c.jsx("span",{className:"text-[10px] text-muted-foreground",children:h.label.slice(0,3)})]},h.value))}),e.length>0&&c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Selected: ",K4e(e)]})]})}function K4e(e){if(e.length===0)return"None";if(e.length===7)return"Every day";const t=new Set(e),n=[1,2,3,4,5].every(a=>t.has(a))&&e.length===5,r=t.has(0)&&t.has(6)&&e.length===2;if(n)return"Monday through Friday";if(r)return"Saturday and Sunday";const o=[...e].sort().map(a=>DR[a].label);if(o.length===1)return o[0];if(o.length===2)return`${o[0]} and ${o[1]}`;const i=o.pop();return`${o.join(", ")}, and ${i}`}function Z4e(e,t,n){const[r,s]=e.split(":").map(Number);switch(t){case"daily":return`${s} ${r} * * *`;case"weekly":if(n&&n.length>0){const o=n.sort().join(",");return`${s} ${r} * * ${o}`}return`${s} ${r} * * 0`;case"biweekly":return`${s} ${r} 1,15 * *`;case"monthly":return`${s} ${r} 1 * *`;default:return`${s} ${r} * * *`}}function X4e(e){if(!e)return"";if(e.includes("AM")||e.includes("PM"))return e;const t=e.split(":");if(t.length!==2)return e;const n=parseInt(t[0],10),r=parseInt(t[1],10);if(isNaN(n)||isNaN(r))return console.warn("Invalid time format:",e),e;if(n<0||n>23||r<0||r>59)return console.warn("Time out of range:",e),e;const s=n>=12?"PM":"AM";return`${n%12||12}:${r.toString().padStart(2,"0")} ${s}`}function Q4e(e){if(!e||e.length===0)return"No days selected";const t=new Set(e),n=[1,2,3,4,5].every(a=>t.has(a))&&t.size===5,r=t.has(0)&&t.has(6)&&t.size===2;if(t.size===7)return"Every day";if(n)return"Weekdays";if(r)return"Weekends";const i=[...e].sort().map(a=>DR[a].label);return i.length===1?i[0]:i.length===2?`${i[0]} and ${i[1]}`:i.join(", ")}function J4e(e){if(!e||e.length===0)return"No dates excluded";const t=e.map(n=>new Date(n).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}));return t.length===1?t[0]:t.length===2?`${t[0]} and ${t[1]}`:t.length>5?`${t.slice(0,3).join(", ")} and ${t.length-3} more`:t.join(", ")}function e3e(e,t){if(!e&&!t)return"Ongoing";const n=r=>new Date(r).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return e&&!t?`Starting ${n(e)}`:!e&&t?`Until ${n(t)}`:`${n(e)} - ${n(t)}`}function t3e(e){if(typeof e=="string"){const r=e.split(/[,;]/).filter(s=>s.trim());return`${r.length} recipient${r.length!==1?"s":""}`}const t=[];e.emails.length>0&&t.push(`${e.emails.length} email${e.emails.length!==1?"s":""}`);const n=e.tenantUserIds.length+e.orgUserIds.length;return n>0&&t.push(`${n} user${n!==1?"s":""}`),e.groupIds.length>0&&t.push(`${e.groupIds.length} group${e.groupIds.length!==1?"s":""}`),t.join(", ")||"No recipients"}function n3e({schedules:e,onDelete:t,isDeleting:n,isLoading:r=!1,onRefresh:s}){const[o,i]=j.useState(null),a=u=>{i(u)},l=()=>{o&&(t(o),i(null))};return r?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx(Mn,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.length===0?c.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[c.jsx(os,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),c.jsx("p",{className:"text-sm",children:"No active schedules"}),c.jsx("p",{className:"mt-1 text-xs",children:"Create a schedule to start receiving reports"})]}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx("h4",{className:"text-sm font-medium",children:"Active Schedules"}),c.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[e.length," active schedule",e.length!==1?"s":""]})]}),s&&c.jsx(oe,{variant:"ghost",size:"sm",onClick:s,className:"h-8",children:c.jsx(W8,{className:"h-3 w-3"})})]}),c.jsx(Ss,{}),c.jsx("div",{className:"space-y-3",children:e.map(u=>c.jsx(r3e,{schedule:u,onDelete:()=>a(u.id),isDeleting:n===u.id},u.id))})]}),c.jsx(Gb,{open:!!o,onOpenChange:()=>i(null),children:c.jsxs(bm,{children:[c.jsxs(xm,{children:[c.jsx(vm,{children:"Delete Schedule?"}),c.jsx(wm,{children:"This will permanently delete this schedule. You will no longer receive these reports."})]}),c.jsxs(ym,{children:[c.jsx(Cm,{children:"Cancel"}),c.jsx(Sm,{className:"bg-destructive/90 hover:bg-destructive",onClick:l,children:"Delete Schedule"})]})]})})]})}function r3e({schedule:e,onDelete:t,isDeleting:n}){var l,u,d,f,h,m;const s=(()=>{if(typeof e.recipients=="string"){const p=e.recipients?e.recipients.split(/[,;]/).filter(Boolean):[];return{summary:`${p.length} recipient${p.length!==1?"s":""}`,details:p.length===1?p[0]:null}}else if(e.recipients)return{summary:t3e(e.recipients),details:null};return{summary:"No recipients",details:null}})(),o=e.endDate&&new Date(e.endDate)<new Date,i=new Date(e.nextRun),a=i<new Date&&!o;return c.jsx("div",{className:X("rounded-lg border bg-card p-4 transition-colors",o&&"opacity-60"),children:c.jsxs("div",{className:"flex items-start justify-between gap-3",children:[c.jsxs("div",{className:"flex-1 space-y-3",children:[c.jsx("div",{className:"flex-1",children:c.jsx("p",{className:"text-sm font-medium",children:e.subject||"Untitled"})}),typeof e.recipients=="object"&&"emails"in e.recipients?c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[c.jsx(gv,{className:"h-3 w-3"}),c.jsx("span",{className:"text-xs font-medium",children:"Recipients:"})]}),c.jsx(On,{children:c.jsxs("div",{className:"ml-4 flex flex-wrap gap-1",children:[e.recipients.emails.map(p=>c.jsx(Oe,{variant:"outline",className:"h-5 py-0 text-xs",children:p},p)),e.recipients.tenantUserIds.length+e.recipients.orgUserIds.length>0&&c.jsxs(un,{delayDuration:300,children:[c.jsx(dn,{asChild:!0,children:c.jsxs(Oe,{variant:"outline",className:"h-5 cursor-help py-0 text-xs",children:[e.recipients.tenantUserIds.length+e.recipients.orgUserIds.length," ","users"]})}),c.jsx(pn,{className:"max-w-xs p-2",side:"top",align:"start",children:c.jsxs("div",{className:"space-y-2 text-xs",children:[((l=e.recipientDetails)==null?void 0:l.tenantUsers)&&e.recipientDetails.tenantUsers.length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"mb-1 font-medium",children:"Tenant Users:"}),c.jsx("div",{className:"ml-2 space-y-0.5",children:e.recipientDetails.tenantUsers.map(p=>c.jsxs("div",{className:"text-muted-foreground",children:[p.name," (",p.email,")"]},p.id))})]}),((u=e.recipientDetails)==null?void 0:u.orgUsers)&&e.recipientDetails.orgUsers.length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"mb-1 font-medium",children:"Organization Users:"}),c.jsx("div",{className:"ml-2 space-y-0.5",children:e.recipientDetails.orgUsers.map(p=>c.jsxs("div",{className:"text-muted-foreground",children:[p.name," (",p.email,")"]},p.id))})]}),!e.recipientDetails&&c.jsx("div",{className:"italic text-muted-foreground",children:"User details not available"})]})})]}),e.recipients.groupIds.length>0&&c.jsxs(un,{delayDuration:300,children:[c.jsx(dn,{asChild:!0,children:c.jsxs(Oe,{variant:"outline",className:"h-5 cursor-help py-0 text-xs",children:[e.recipients.groupIds.length," group",e.recipients.groupIds.length!==1?"s":""]})}),c.jsx(pn,{className:"max-w-xs p-2",side:"top",align:"start",children:c.jsxs("div",{className:"space-y-1 text-xs",children:[c.jsx("div",{className:"mb-1 font-medium",children:"Groups:"}),(d=e.recipientDetails)!=null&&d.groups&&e.recipientDetails.groups.length>0?c.jsx("div",{className:"ml-2 space-y-1",children:e.recipientDetails.groups.map(p=>c.jsxs("div",{className:"space-y-0.5",children:[c.jsx("div",{className:"font-medium",children:p.name}),c.jsxs("div",{className:"text-[10px] text-muted-foreground",children:[p.type==="TENANT_GROUP"?"Tenant":"Organization"," ","Group",p.memberCount&&` • ${p.memberCount} members`]})]},p.id))}):c.jsx("div",{className:"ml-2 italic text-muted-foreground",children:"Group details not available"})]})})]})]})})]}):c.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[c.jsx(gv,{className:"h-3 w-3"}),c.jsx("span",{children:s.details||s.summary})]}),c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[c.jsx(aD,{className:"h-3 w-3"}),c.jsx("span",{children:"Attachments:"})]}),c.jsx("div",{className:"flex flex-wrap items-start gap-2",children:(f=e.reportParams)!=null&&f.attachments&&e.reportParams.attachments.length>0?e.reportParams.attachments.map((p,g)=>{var y,v;const b=(y=p.title)==null?void 0:y.includes("(All Sheets)"),x=((v=p.settings)==null?void 0:v.sheetSelection)==="all"&&!b;return c.jsxs(Oe,{variant:"outline",className:"text-xs",children:[p.type==="dashboard"?c.jsx(oP,{className:"mr-1 h-3 w-3"}):p.type==="visual"?c.jsx(ki,{className:"mr-1 h-3 w-3"}):c.jsx(U2,{className:"mr-1 h-3 w-3"}),p.title,x&&" (All Sheets)"]},g)}):c.jsxs(c.Fragment,{children:[(e.dashboardName||e.reportName)&&c.jsxs(Oe,{variant:"outline",className:"text-xs",children:[e.reportType==="VISUAL"?c.jsx(ki,{className:"mr-1 h-3 w-3"}):c.jsx(oP,{className:"mr-1 h-3 w-3"}),e.dashboardName||e.reportName]}),((h=e.reportParams)==null?void 0:h.sheetSelection)==="all"&&c.jsxs(Oe,{variant:"outline",className:"text-xs",children:[c.jsx(U2,{className:"mr-1 h-3 w-3"}),"All Sheets"]})]})})]}),c.jsxs("div",{className:"grid gap-2 text-xs",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[c.jsx(ml,{className:"h-3 w-3"}),c.jsxs("span",{children:[Mg(e.frequency),e.frequency==="weekly"&&e.weekdays&&c.jsxs(c.Fragment,{children:[" on ",Q4e(e.weekdays)]})," at ",X4e(e.time)||e.time||"Time not set",e.timezone&&e.timezone!=="UTC"&&c.jsxs(c.Fragment,{children:[" ","(",(m=e.timezone.split("/").pop())==null?void 0:m.replace(/_/g," "),")"]})]})]}),(e.startDate||e.endDate)&&c.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[c.jsx(os,{className:"h-3 w-3"}),c.jsx("span",{children:e3e(e.startDate?String(e.startDate):void 0,e.endDate?String(e.endDate):void 0)})]}),e.skipDates&&e.skipDates.length>0&&c.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[c.jsx(yd,{className:"h-3 w-3"}),c.jsxs("span",{children:["Skipping: ",J4e(e.skipDates)]})]}),c.jsxs("div",{className:X("flex items-center gap-1.5 font-medium",o?"text-muted-foreground line-through":a?"text-orange-500":"text-foreground"),children:[c.jsx(ml,{className:"h-3 w-3"}),c.jsx("span",{children:o?"Schedule expired":c.jsxs(c.Fragment,{children:["Next: ",Ka(i,"MMM d, yyyy")," at"," ",Ka(i,"h:mm a"),a&&" (processing)"]})})]})]})]}),c.jsx("div",{className:"flex items-center",children:n?c.jsx(Mn,{className:"h-4 w-4 animate-spin text-muted-foreground"}):c.jsx(oe,{variant:"ghost",size:"sm",onClick:t,className:"h-8 w-8 p-0 hover:bg-destructive/10 hover:text-destructive",children:c.jsx(Wd,{className:"h-4 w-4"})})})]})})}function s3e(e={}){const{reportType:t,dashboardId:n,visualId:r,pageSettings:s,enabled:o=!0}=e,[i,a]=j.useState(!1),[l,u]=j.useState(null),[d,f]=j.useState(null),{authToken:h,tokenProps:m}=Ge(),p=Q(T=>{var O;return(O=T.dashboard)==null?void 0:O.id}),g=Q(T=>{var O;return(O=T.dashboard)==null?void 0:O.title});Q(T=>T.theme);const b=Q(T=>T.dashboard.filters),x=Q(T=>T.filterValues),y=Q(T=>T.selectedSheetId),v=Jc(b,y),w=x==null?void 0:x.filter(T=>(v==null?void 0:v.some(O=>O.id===T.filterId))||T.filterId.endsWith(y)),C=n||p;Ts();const{data:S=[],isLoading:N,isError:_,refetch:E}=cn({queryKey:["schedules","with-details"],queryFn:async()=>{const T=`${m.apiServiceUrl}/v1/schedules`;return await Hn(T,(h==null?void 0:h.accessToken)||"",{includeRecipientDetails:"true"})},enabled:!!(h!=null&&h.accessToken)&&!!(m!=null&&m.apiServiceUrl)&&o,staleTime:5*60*1e3,gcTime:10*60*1e3}),k=j.useCallback(async T=>{var O;a(!0),u(null);try{const R=Z4e(T.time,T.frequency,T.weekdays),{authToken:I,...L}=t==="DASHBOARD"?TT(h):{},F=Oq(w||[]),V={recipients:T.recipients,recipientsString:void 0,subject:T.subject||g||"Scheduled Report",message:T.message,frequency:T.frequency,time:T.time,timezone:T.timezone,dashboardId:C,weekdays:T.weekdays,skipDates:T.skipDates,startDate:T.startDate,endDate:T.endDate,reportParams:(O=T.reportParams)!=null&&O.attachments?{...T.reportParams,attachments:T.reportParams.attachments.map(U=>({...U,settings:{...U.settings,sheetFilterValues:w||[]}}))}:T.reportParams||{}};t&&(t==="DASHBOARD"?(V.reportParams||(V.reportParams={}),V.dashboardParams={...L,filterLine:F}):t==="VISUAL"&&r&&(V.reportParams={attachments:[{type:"visual",visualId:r,title:T.subject||"Visual Report",format:"pdf",settings:{...s,filterLine:F}}]}));const $=`${m.apiServiceUrl}/v1/schedules`,P=await yl($,(h==null?void 0:h.accessToken)||"",V);return Fe.success("Schedule created successfully!",{description:`Reports will be sent ${T.frequency} at ${T.time}`}),await E(),a(!1),P}catch(R){console.error("Failed to create schedule:",R);const I=R instanceof Error?R.message:"Failed to create schedule";throw u(I),a(!1),Fe.error("Failed to create schedule",{description:I}),R}},[t,C,r,s,h,m.apiServiceUrl,g,w,E]),M=j.useCallback(async T=>{f(T);try{const O=`${m.apiServiceUrl}/v1/schedules`;if(!(await fetch(`${O}/${T}`,{method:"DELETE",headers:{Authorization:`Bearer ${(h==null?void 0:h.accessToken)||""}`,"Content-Type":"application/json"}})).ok)throw new Error("Failed to delete schedule");Fe.success("Schedule deleted successfully"),await E(),f(null)}catch(O){throw console.error("Failed to delete schedule:",O),f(null),Fe.error("Failed to delete schedule",{description:O instanceof Error?O.message:"Please try again"}),O}},[h,E,m.apiServiceUrl]);return{schedules:S,isLoading:N,isError:_,createSchedule:k,deleteSchedule:M,refetch:E,isSubmitting:i,submitError:l,deletingId:d}}const g3=`Hello,
975
975
 
976
976
  Your scheduled email is ready. The attachments you requested are included for your review.`;function tZ({open:e,onOpenChange:t,dashboardId:n,dashboardName:r="Dashboard",preSelectedVisual:s}){const[o,i]=j.useState("create"),[a,l]=j.useState({emails:[],tenantUserIds:[],orgUserIds:[],groupIds:[]}),[u,d]=j.useState(`${r} Report`),[f,h]=j.useState(g3),[m,p]=j.useState(s?[s]:[]),[g,b]=j.useState(!1),[x,y]=j.useState(!1),{currentUser:v}=Ts(),w=Q(re=>re.dashboard),C=j.useMemo(()=>(w==null?void 0:w.sheets)||[],[w==null?void 0:w.sheets]),S=Q(re=>re.selectedSheetId),N=C.find(re=>re.id===S),[_,E]=j.useState("daily"),[k,M]=j.useState("09:00"),[T,O]=j.useState(Intl.DateTimeFormat().resolvedOptions().timeZone),[R,I]=j.useState([1,2,3,4,5]),[L,F]=j.useState(new Date),[V,$]=j.useState(),{schedules:P,isLoading:U,createSchedule:B,deleteSchedule:A,isSubmitting:Y,deletingId:z,refetch:q}=s3e({enabled:e});j.useEffect(()=>{if(e&&!x){if(v){const re={emails:[],tenantUserIds:[],orgUserIds:[],groupIds:[]};v.type==="tenant"&&v.id?re.tenantUserIds=[v.id]:v.type==="organization"&&v.id&&(re.orgUserIds=[v.id]),l(re)}if(s)p([s]);else if(w&&N){const re={type:"dashboard",title:C.length>1?`${w.title} (${N.title})`:`${w.title} (All Sheets)`,format:"pdf",settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0,sheetSelection:C.length>1?"current":"all",currentSheetId:C.length>1?N.id:void 0,currentSheetName:C.length>1?N.title:void 0}};p([re])}else if(w){const re={type:"dashboard",title:`${w.title} (All Sheets)`,format:"pdf",settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0,sheetSelection:"all"}};p([re])}y(!0)}},[e,v,w,N,C,x,s]),j.useEffect(()=>{e||y(!1)},[e]);const W=re=>{p(re),b(!1)},H=re=>{p(m.filter((fe,Ce)=>Ce!==re))},G=(re,fe)=>{const Ce=[...m];Ce[re]=fe,p(Ce)},K=()=>{l({emails:[],tenantUserIds:[],orgUserIds:[],groupIds:[]}),d(`${r} Report`),h(g3),p([]),E("daily"),M("09:00"),O(Intl.DateTimeFormat().resolvedOptions().timeZone),I([1,2,3,4,5]),F(new Date),$(void 0)},te=async()=>{try{await B({recipients:a,subject:u,message:f,frequency:_,time:k,timezone:T,weekdays:_==="weekly"?R:void 0,startDate:Ka(L,"yyyy-MM-dd"),endDate:V?Ka(V,"yyyy-MM-dd"):void 0,reportParams:{attachments:m.map(re=>({type:re.type,visualId:re.visualId,cardType:re.cardType,title:re.title,format:re.format,settings:re.settings}))}}),K(),i("active"),q()}catch(re){console.error("Failed to create schedule:",re)}},Z=async re=>{try{await A(re)}catch(fe){console.error("Failed to delete schedule:",fe)}},se=(a.emails.length>0||a.tenantUserIds.length>0||a.orgUserIds.length>0||a.groupIds.length>0)&&u&&m.length>0,ce=re=>{re||y(!1),t(re)};return c.jsxs(c.Fragment,{children:[c.jsx(ls,{open:e,onOpenChange:ce,children:c.jsxs(Ur,{className:"max-h-[90vh] max-w-2xl",children:[c.jsxs(Wr,{children:[c.jsx(qr,{children:"Schedule Export"}),c.jsx(Is,{className:"sr-only",children:"Create and manage scheduled exports for your dashboard"})]}),c.jsxs(As,{value:o,onValueChange:re=>i(re),className:"w-full",children:[c.jsxs(cs,{className:"grid w-full grid-cols-2",children:[c.jsxs(qt,{value:"create",className:"flex items-center gap-2",children:[c.jsx(kr,{className:"h-4 w-4"}),"Create Schedule"]}),c.jsxs(qt,{value:"active",className:"flex items-center gap-2",children:[c.jsx(z8,{className:"h-4 w-4"}),"Active Schedules",P&&P.length>0&&c.jsx(Oe,{variant:"secondary",className:"ml-1 h-5 px-1",children:P.length})]})]}),c.jsxs(nr,{value:"create",className:"mt-4 max-h-[calc(80vh-200px)] space-y-4 overflow-y-auto",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{children:"Recipients"}),c.jsx(R4e,{value:a,onChange:l})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{htmlFor:"subject",children:"Subject"}),c.jsx(jn,{id:"subject",value:u,onChange:re=>d(re.target.value),placeholder:"Enter email subject"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{htmlFor:"message",children:"Message"}),c.jsx(Qd,{className:"ring-inset focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",id:"message",value:f,onChange:re=>h(re.target.value),placeholder:"Enter email message",rows:4})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(de,{children:"Attachments"}),c.jsxs(oe,{variant:"secondary",size:"sm",onClick:()=>b(!0),children:[c.jsx(aD,{className:"mr-2 h-4 w-4"}),"Select attachments"]})]}),m.length>0?c.jsx(W4e,{attachments:m,onRemove:H,onUpdate:G}):c.jsx("div",{className:"rounded-lg border-2 border-dashed p-4 text-center text-sm text-muted-foreground",children:"No attachments selected"})]}),c.jsx(Ss,{}),c.jsx("div",{className:"space-y-4",children:c.jsxs("div",{className:"space-y-4",children:[c.jsx(de,{className:"text-base font-medium",children:"Schedule Settings"}),c.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{htmlFor:"date",className:"text-xs text-muted-foreground",children:"First occurrence"}),c.jsxs(ks,{modal:!0,children:[c.jsx(Es,{asChild:!0,children:c.jsxs(oe,{variant:"outline",className:X("w-full justify-start text-left font-normal",!L&&"text-muted-foreground"),children:[c.jsx(os,{className:"mr-2 h-4 w-4 shrink-0"}),L?Ka(L,"PPP"):"Pick a date"]})}),c.jsx(_s,{className:"z-[51] w-auto p-0",align:"start",children:c.jsx(hw,{mode:"single",selected:L,onSelect:re=>re&&F(re),disabled:re=>re<new Date(new Date().setHours(0,0,0,0)),initialFocus:!0})})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{htmlFor:"time",className:"text-xs text-muted-foreground",children:"Time"}),c.jsx(Y4e,{value:k,onChange:M})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{htmlFor:"timezone",className:"text-xs text-muted-foreground",children:"Timezone"}),c.jsx(q4e,{value:T,onChange:O})]})]})]})}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{htmlFor:"frequency",children:"Repeats:"}),c.jsxs(rt,{value:_,onValueChange:re=>E(re),children:[c.jsx(tt,{children:c.jsx(at,{})}),c.jsxs(nt,{children:[c.jsx(ge,{className:"hover:bg-muted",value:"daily",children:"Daily"}),c.jsx(ge,{className:"hover:bg-muted",value:"weekly",children:"Weekly"}),c.jsx(ge,{className:"hover:bg-muted",value:"biweekly",children:"Biweekly"}),c.jsx(ge,{className:"hover:bg-muted",value:"monthly",children:"Monthly"})]})]})]}),_==="weekly"&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{children:"On days:"}),c.jsx(G4e,{value:R,onChange:I})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(_ae,{className:"h-4 w-4 text-muted-foreground"}),c.jsx(de,{className:"text-xs text-muted-foreground",htmlFor:"end-date",children:"End date (optional):"})]}),c.jsxs(ks,{modal:!0,children:[c.jsx(Es,{asChild:!0,children:c.jsxs(oe,{variant:"outline",className:X("w-full justify-start text-left font-normal",!V&&"text-muted-foreground"),children:[c.jsx(os,{className:"mr-2 h-4 w-4"}),V?Ka(V,"PPP"):"No end date"]})}),c.jsx(_s,{className:"z-[51] w-auto p-0",align:"start",children:c.jsx(hw,{mode:"single",selected:V,onSelect:$,disabled:re=>re<=L,initialFocus:!0})})]})]})]}),c.jsx(nr,{value:"active",className:"mt-4 max-h-[calc(80vh-200px)] overflow-y-auto",children:P&&P.length>0?c.jsx(n3e,{schedules:P,onDelete:Z,isDeleting:z,isLoading:U,onRefresh:q}):c.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[c.jsx(ml,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),c.jsx("p",{className:"text-sm font-medium",children:"No active schedules"}),c.jsx("p",{className:"mt-1 text-xs",children:'Switch to the "Create Schedule" tab to add your first schedule'})]})})]}),o==="create"&&c.jsxs(Rs,{children:[c.jsx(oe,{variant:"outline",onClick:()=>ce(!1),disabled:Y,children:"Cancel"}),c.jsx(oe,{onClick:te,disabled:!se||Y,children:Y?c.jsx(c.Fragment,{children:"Scheduling..."}):c.jsxs(c.Fragment,{children:[c.jsx(q8,{className:"mr-2 h-4 w-4"}),"Schedule"]})})]})]})}),g&&c.jsx(H4e,{open:g,onOpenChange:b,dashboardId:n,onSelect:W,existingAttachments:m})]})}function nZ({frame:e,isHovered:t,isExpandedViewOpen:n=!1,onExpandClick:r}){const{authToken:s,tokenProps:o}=Ge(),[i,a]=j.useState(!1),{openPopover:l}=DT(),[u,d]=j.useState(!1),[f,h]=j.useState(!1),[m,p]=j.useState(!1),[g,b]=j.useState(""),[x,y]=j.useState(!1),[v,w]=j.useState(!1),C=r?n:v,S=r||(()=>w(!0)),N=j.useRef(null),_=j.useRef(null),E=Q(re=>re.isDashboardEditing),k=Q(re=>re.isDownloadingPdf),M=Q(re=>re.selectedSheetId),T=Q(re=>{var fe;return(fe=re.dashboard)==null?void 0:fe.id}),O=Q(re=>{var fe;return(fe=re.dashboard)==null?void 0:fe.title}),{removeFrame:R,addFrame:I,setSelectedFrameId:L}=Q(re=>re.actions),F=e.cards.find(re=>re.id===e.activeCardId),{handleEditVisual:V,card:$,data:P}=Ake(e),{cardFilterValues:U}=D1(($==null?void 0:$.id)||""),{permissions:B}=Mq(),A=Q(re=>re.inlineFilterValuesMap[($==null?void 0:$.id)||""]),Y=[...U||[],...A||[]];j.useEffect(()=>()=>{_.current&&clearTimeout(_.current)},[]);const z=()=>{_.current&&clearTimeout(_.current),a(!0)},q=()=>{_.current=setTimeout(()=>{a(!1)},300)},W=()=>{a(!1),_.current&&clearTimeout(_.current)},H=async()=>{if(!g)return;d(!1),b(""),y(!1);const re=Fe.loading("Generating protected PDF report... may take up to 60 seconds");try{await Aq(o.apiServiceUrl,s,e.activeCardId||"",e.id,($==null?void 0:$.title)||"visual",$==null?void 0:$.type,g,void 0,void 0,void 0,Y),Fe.dismiss(re),Fe.success("Protected visual PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(fe){Fe.dismiss(re),Fe.error("Failed to download protected visual PDF. Please try again."),console.error("Protected visual PDF download error:",fe)}},G=()=>{if(M)try{const re=JSON.parse(JSON.stringify(e)),fe=_R(re),Ce=fe.cards.findIndex(ie=>ie.id===fe.activeCardId);Ce!==-1&&(fe.cards[Ce].title=`${fe.cards[Ce].title} (Copy)`),I(M,fe),L(fe.id),Fe.success("Card duplicated successfully")}catch(re){console.error("Failed to duplicate frame:",re),Fe.error("Failed to duplicate card")}},K=()=>{const{theme:re,dashboardTitle:fe,selectedSheetId:Ce,dashboardId:ie}=TT(s),pe=new URLSearchParams;pe.set("token",(s==null?void 0:s.accessToken)||""),pe.set("theme",re||"light"),pe.set("filterValues",JSON.stringify(Y||[])),pe.set("dashboardTitle",fe||""),pe.set("selectedSheetId",Ce||""),pe.set("dashboardId",ie||"");const ue=e.activeCardId,ve=`https://semaphor.cloud/view/dashboard/${ie}/visual/${ue}?${pe.toString()}`;window.open(ve,"_blank")},te=($==null?void 0:$.type)==="kpi",Z=($==null?void 0:$.type)==="text",ee={editVisual:{visible:E&&B.canEdit},duplicateFrame:{visible:E&&B.canEdit},expand:{visible:!te&&!Z},export:{visible:!te&&!Z},deleteCard:{visible:E&&B.canEdit},moreOptions:{visible:!te&&!Z,submenu:{interactions:{visible:E&&B.canEdit&&!!(F!=null&&F.config)&&!te&&!Z},schedule:{visible:!te&&!Z&&!E}}}},se=ee.editVisual.visible||ee.duplicateFrame.visible||ee.expand.visible||ee.export.visible||ee.deleteCard.visible||ee.moreOptions.visible,ce=t&&!C&&se;return c.jsxs(c.Fragment,{children:[ce&&c.jsx("div",{ref:N,className:"absolute right-2 top-2 z-50 duration-200 animate-in fade-in-0 zoom-in-95",onMouseLeave:W,children:c.jsx(vo,{className:"min-w-[32px] border-border bg-popover p-0.5 shadow-lg",children:c.jsxs("div",{className:"flex flex-row gap-0.5",children:[ee.moreOptions.visible&&c.jsxs("div",{className:"relative",children:[c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-accent hover:text-accent-foreground",onMouseEnter:z,onMouseLeave:q,onClick:re=>re.stopPropagation(),title:"More Options",children:c.jsx(om,{className:"h-3.5 w-3.5"})}),i&&c.jsx("div",{className:"z-60 absolute right-full top-0 mr-0.5 duration-150 animate-in fade-in-0 zoom-in-95",onMouseEnter:z,onMouseLeave:q,children:c.jsx(vo,{className:"min-w-[140px] border-border bg-popover p-0.5 shadow-lg",children:c.jsxs("div",{className:"flex flex-col gap-0.5",children:[ee.moreOptions.submenu.interactions.visible&&c.jsxs(oe,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:re=>{re.stopPropagation(),L(e.id);const fe=e.activeCardId;fe&&l(e.id,fe,re.currentTarget),a(!1)},children:[c.jsx(im,{className:"mr-1.5 h-3.5 w-3.5"}),c.jsx("span",{className:"text-xs",children:"Interactions"})]}),ee.export.visible&&c.jsxs(oe,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:re=>{re.stopPropagation(),h(!0),a(!1)},children:[c.jsx(o1,{className:"mr-1.5 h-3.5 w-3.5"}),c.jsx("span",{className:"text-xs",children:"Download"})]}),c.jsxs(oe,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:re=>{re.stopPropagation(),K()},children:[c.jsx(pv,{className:"mr-1.5 h-3.5 w-3.5"}),c.jsx("span",{className:"text-xs",children:"Open in New Window"})]}),ee.moreOptions.submenu.schedule.visible&&c.jsxs(oe,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:re=>{re.stopPropagation(),p(!0),a(!1)},children:[c.jsx(ml,{className:"mr-1.5 h-3.5 w-3.5"}),c.jsx("span",{className:"text-xs",children:"Schedule Export"})]})]})})})]}),ee.deleteCard.visible&&c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-destructive hover:text-destructive-foreground",onClick:re=>{re.stopPropagation(),R(M,e.id)},disabled:!1,title:"Delete Card",children:c.jsx(Wd,{className:"h-3.5 w-3.5"})}),ee.duplicateFrame.visible&&c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:re=>{re.stopPropagation(),G()},disabled:!1,title:"Duplicate Card",children:c.jsx(R8,{className:"h-3.5 w-3.5"})}),ee.expand.visible&&c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:re=>{re.stopPropagation(),S(),a(!1)},disabled:!1,title:"Expand View",children:c.jsx(l1,{className:"h-3.5 w-3.5"})}),ee.editVisual.visible&&c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-primary hover:text-primary-foreground",onClick:re=>{re.stopPropagation(),V()},disabled:!1,title:"Edit Visual",children:c.jsx(lD,{className:"h-3.5 w-3.5"})})]})})}),c.jsx(ls,{open:u,onOpenChange:d,children:c.jsxs(Ur,{className:"sm:max-w-[425px]",children:[c.jsxs(Wr,{children:[c.jsx(qr,{children:"Download Protected Visual PDF"}),c.jsx(Is,{children:"Enter a password to protect your visual PDF. The PDF will be encrypted and require this password to open."})]}),c.jsx("div",{className:"grid gap-4 py-4",children:c.jsxs("div",{className:"grid gap-2",children:[c.jsx(de,{htmlFor:"password",children:"Password"}),c.jsxs("div",{className:"relative",children:[c.jsx(jn,{id:"password",type:x?"text":"password",value:g,onChange:re=>b(re.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:re=>{re.key==="Enter"&&g&&H()}}),c.jsx(oe,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>y(!x),children:x?c.jsx(rD,{className:"h-4 w-4 text-muted-foreground"}):c.jsx(vd,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),c.jsxs(Rs,{children:[c.jsx(oe,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),c.jsx(oe,{onClick:H,disabled:!g||k,children:"Download"})]})]})}),!r&&v&&c.jsx(_4e,{isOpen:v,onClose:()=>w(!1),frame:e,card:$,data:P}),c.jsx(Kq,{isOpen:f,onClose:()=>h(!1),frame:e,card:$,data:P}),c.jsx(tZ,{open:m,onOpenChange:p,dashboardId:T||"",dashboardName:O,preSelectedVisual:$?{visualId:$.id,cardType:$.type,title:$.title||"Visual",type:"visual",format:PT($.type),supportedFormats:AT($.type),settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0,inlineFilterValues:A}}:void 0})]})}function ib({children:e,containerClassName:t,className:n,text:r,onSave:s,type:o="input",placeholder:i,enabled:a}){const[l,u]=j.useState(!1),[d,f]=j.useState(r),h=Q(x=>x.isDashboardEditing);j.useEffect(()=>{f(x=>x!==r?r:x)},[r]);const m=x=>{x.stopPropagation(),h&&u(!0)};function p(x){if(x.stopPropagation(),x.key==="Escape"){u(!1);return}x.key==="Enter"&&x.shiftKey||(x.key==="Enter"||x.key==="Tab")&&(u(!1),s(d))}function g(){return o==="textarea"?c.jsx("textarea",{className:X("resize rounded-sm bg-background px-2 py-1 text-sm outline-[0.5px] outline-muted",n),onChange:x=>f(x.target.value),value:d,autoFocus:!0,placeholder:i,onBlur:()=>u(!1),onKeyDown:p}):c.jsx("input",{onMouseDown:x=>x.stopPropagation(),type:"text",className:X("rounded-sm bg-background outline-none",n),onChange:x=>f(x.target.value),value:d,autoFocus:!0,placeholder:i,onBlur:()=>u(!1),onKeyDown:p})}function b(){return a?c.jsxs("div",{className:"flex grow items-center gap-2",children:[c.jsx("div",{children:l?g():e}),!l&&c.jsx(lD,{onClick:()=>u(!0),className:"hidden size-3 cursor-pointer text-muted-foreground group-hover/editable:block"})]}):e}return c.jsx("div",{className:X("flex",t),role:"editable",onDoubleClick:m,onMouseDown:x=>x.stopPropagation(),children:c.jsx("div",{className:"group/editable flex grow items-center gap-2",children:b()})})}function NS(e){const{authToken:t}=Ge(),n=zie(t==null?void 0:t.accessToken);function r(){var o,i,a,l,u,d;if((i=(o=e.preferences)==null?void 0:o.formatNumber)!=null&&i.currency&&((l=(a=e.preferences)==null?void 0:a.formatNumber)==null?void 0:l.currency)!=="none")return n!=null&&n.currency?n==null?void 0:n.currency:(d=(u=e.preferences)==null?void 0:u.formatNumber)==null?void 0:d.currency}function s(){var o,i,a,l,u,d;return(i=(o=e.preferences)==null?void 0:o.formatNumber)!=null&&i.locale&&((l=(a=e.preferences)==null?void 0:a.formatNumber)==null?void 0:l.locale)!=="none"?n!=null&&n.locale?n==null?void 0:n.locale:(d=(u=e.preferences)==null?void 0:u.formatNumber)==null?void 0:d.locale:navigator.language||"en-US"}return{getCurrency:r,getLocale:s}}var o3e="Toggle",rZ=D.forwardRef((e,t)=>{const{pressed:n,defaultPressed:r=!1,onPressedChange:s,...o}=e,[i=!1,a]=zr({prop:n,onChange:s,defaultProp:r});return c.jsx(Ue.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...o,ref:t,onClick:De(e.onClick,()=>{e.disabled||a(!i)})})});rZ.displayName=o3e;var sZ=rZ;const i3e=Lb("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),jx=D.forwardRef(({className:e,variant:t,size:n,...r},s)=>c.jsx(sZ,{ref:s,className:X(i3e({variant:t,size:n,className:e})),...r}));jx.displayName=sZ.displayName;function MR({children:e,className:t,...n}){return c.jsx(q9,{children:c.jsx(Ca,{children:c.jsx(pn,{...n,className:t,children:e})})})}const a3e={"currentPeriod.start":{icon:c.jsx(B2,{className:"h-3 w-3 text-blue-500"}),label:"Current Start"},"currentPeriod.end":{icon:c.jsx(B2,{className:"h-3 w-3 text-blue-500"}),label:"Current End"},"comparisonPeriod.start":{icon:c.jsx(os,{className:"h-3 w-3 text-gray-500"}),label:"Previous Start"},"comparisonPeriod.end":{icon:c.jsx(os,{className:"h-3 w-3 text-gray-500"}),label:"Previous End"},trendlineGranularity:{icon:c.jsx(C8,{className:"h-3 w-3 text-green-500"}),label:"Data Period"},trendlineWindow:{icon:c.jsx(ml,{className:"h-3 w-3 text-purple-500"}),label:"Time Range"}},l3e=(e,t,n)=>e>t?c.jsx(Fo,{className:`h-3 w-3 ${n?"text-green-500":"text-red-500"}`}):e<t?c.jsx(ta,{className:`h-3 w-3 ${n?"text-green-500":"text-red-500"}`}):c.jsx(Fo,{className:"h-3 w-3 text-gray-500"}),c3e=(e,t)=>e>t?c.jsx(ta,{className:"h-3 w-3 text-gray-500"}):e<t?c.jsx(Fo,{className:"h-3 w-3 text-gray-500"}):c.jsx(Fo,{className:"h-3 w-3 text-gray-500"}),u3e=(e,t,n)=>e>t?c.jsx(_h,{className:`h-3 w-3 ${n?"text-green-500":"text-red-500"}`}):e<t?c.jsx(mD,{className:`h-3 w-3 ${n?"text-green-500":"text-red-500"}`}):c.jsx(_h,{className:"h-3 w-3 text-gray-500"}),d3e=(e,t)=>e.filter(n=>n.segment==="meta"||n.Segment==="meta").filter(n=>{const r=n.key??n.Key;return!(!t&&(r==="trendlineGranularity"||r==="trendlineWindow"))});function jj({label:e,value:t,icon:n,formatCurrency:r}){return c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[n,c.jsxs("span",{children:[e,":"]})]}),c.jsx("span",{className:"font-mono",children:r(t)})]})}function f3e({metaKey:e,value:t}){const n=a3e[e];return n?c.jsxs("div",{className:"flex items-center justify-between gap-4",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[n.icon,c.jsxs("span",{children:[n.label,":"]})]}),c.jsx("span",{className:"font-mono",children:t})]}):c.jsxs("div",{className:"flex items-center justify-between gap-4",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(tr,{className:"h-3 w-3"}),c.jsxs("span",{children:[e,":"]})]}),c.jsx("span",{className:"font-mono",children:t})]})}function h3e({currentValue:e,comparisonValue:t,isPositive:n,formatCurrency:r}){return c.jsxs("div",{className:"space-y-1",children:[c.jsx(jj,{label:"Current",value:e,icon:l3e(e,t,n),formatCurrency:r}),c.jsx(jj,{label:"Previous",value:t,icon:c3e(e,t),formatCurrency:r}),c.jsx(jj,{label:"Change",value:e-t,icon:u3e(e,t,n),formatCurrency:r})]})}function m3e({data:e,showTrendline:t}){const n=d3e(e,t);return n.length===0?null:c.jsxs("div",{className:"border-t pt-2",children:[c.jsxs("div",{className:"mb-2 flex items-center gap-1 font-semibold",children:[c.jsx(os,{className:"h-3 w-3"}),"Period Details"]}),c.jsx("div",{className:"space-y-1",children:n.map((r,s)=>c.jsx(f3e,{metaKey:r.key??r.Key,value:r.value??r.Value},s))})]})}function p3e({currentValue:e,comparisonValue:t,isPositive:n,data:r,formatCurrency:s,showTrendline:o=!1,conditionalLabel:i}){return c.jsx(MR,{side:"right",className:"max-w-fit",children:c.jsxs("div",{className:"space-y-2 text-xs",children:[c.jsxs("div",{className:"flex items-center gap-1 font-semibold",children:[c.jsx(C8,{className:"h-3 w-3"}),"Key Metrics"]}),i&&c.jsx("div",{className:`flex items-center gap-1 text-sm font-medium ${n?"text-green-600 dark:text-green-400":"text-red-600 dark:text-red-400"}`,children:i}),c.jsx(h3e,{currentValue:e,comparisonValue:t,isPositive:n,formatCurrency:s}),c.jsx(m3e,{data:r,showTrendline:o})]})})}const g3e=[{id:"us",name:"United States",flag:"🇺🇸",code:"US",region:"North America"},{id:"ca",name:"Canada",flag:"🇨🇦",code:"CA",region:"North America"},{id:"mx",name:"Mexico",flag:"🇲🇽",code:"MX",region:"North America"},{id:"gb",name:"United Kingdom",flag:"🇬🇧",code:"GB",region:"Europe"},{id:"de",name:"Germany",flag:"🇩🇪",code:"DE",region:"Europe"},{id:"fr",name:"France",flag:"🇫🇷",code:"FR",region:"Europe"},{id:"it",name:"Italy",flag:"🇮🇹",code:"IT",region:"Europe"},{id:"es",name:"Spain",flag:"🇪🇸",code:"ES",region:"Europe"},{id:"nl",name:"Netherlands",flag:"🇳🇱",code:"NL",region:"Europe"},{id:"be",name:"Belgium",flag:"🇧🇪",code:"BE",region:"Europe"},{id:"ch",name:"Switzerland",flag:"🇨🇭",code:"CH",region:"Europe"},{id:"at",name:"Austria",flag:"🇦🇹",code:"AT",region:"Europe"},{id:"se",name:"Sweden",flag:"🇸🇪",code:"SE",region:"Europe"},{id:"no",name:"Norway",flag:"🇳🇴",code:"NO",region:"Europe"},{id:"dk",name:"Denmark",flag:"🇩🇰",code:"DK",region:"Europe"},{id:"fi",name:"Finland",flag:"🇫🇮",code:"FI",region:"Europe"},{id:"pl",name:"Poland",flag:"🇵🇱",code:"PL",region:"Europe"},{id:"cz",name:"Czech Republic",flag:"🇨🇿",code:"CZ",region:"Europe"},{id:"hu",name:"Hungary",flag:"🇭🇺",code:"HU",region:"Europe"},{id:"pt",name:"Portugal",flag:"🇵🇹",code:"PT",region:"Europe"},{id:"ie",name:"Ireland",flag:"🇮🇪",code:"IE",region:"Europe"},{id:"gr",name:"Greece",flag:"🇬🇷",code:"GR",region:"Europe"},{id:"jp",name:"Japan",flag:"🇯🇵",code:"JP",region:"Asia"},{id:"cn",name:"China",flag:"🇨🇳",code:"CN",region:"Asia"},{id:"in",name:"India",flag:"🇮🇳",code:"IN",region:"Asia"},{id:"kr",name:"South Korea",flag:"🇰🇷",code:"KR",region:"Asia"},{id:"sg",name:"Singapore",flag:"🇸🇬",code:"SG",region:"Asia"},{id:"hk",name:"Hong Kong",flag:"🇭🇰",code:"HK",region:"Asia"},{id:"tw",name:"Taiwan",flag:"🇹🇼",code:"TW",region:"Asia"},{id:"th",name:"Thailand",flag:"🇹🇭",code:"TH",region:"Asia"},{id:"my",name:"Malaysia",flag:"🇲🇾",code:"MY",region:"Asia"},{id:"id",name:"Indonesia",flag:"🇮🇩",code:"ID",region:"Asia"},{id:"ph",name:"Philippines",flag:"🇵🇭",code:"PH",region:"Asia"},{id:"vn",name:"Vietnam",flag:"🇻🇳",code:"VN",region:"Asia"},{id:"ae",name:"United Arab Emirates",flag:"🇦🇪",code:"AE",region:"Asia"},{id:"sa",name:"Saudi Arabia",flag:"🇸🇦",code:"SA",region:"Asia"},{id:"il",name:"Israel",flag:"🇮🇱",code:"IL",region:"Asia"},{id:"tr",name:"Turkey",flag:"🇹🇷",code:"TR",region:"Asia"},{id:"au",name:"Australia",flag:"🇦🇺",code:"AU",region:"Oceania"},{id:"nz",name:"New Zealand",flag:"🇳🇿",code:"NZ",region:"Oceania"},{id:"br",name:"Brazil",flag:"🇧🇷",code:"BR",region:"South America"},{id:"ar",name:"Argentina",flag:"🇦🇷",code:"AR",region:"South America"},{id:"cl",name:"Chile",flag:"🇨🇱",code:"CL",region:"South America"},{id:"co",name:"Colombia",flag:"🇨🇴",code:"CO",region:"South America"},{id:"pe",name:"Peru",flag:"🇵🇪",code:"PE",region:"South America"},{id:"uy",name:"Uruguay",flag:"🇺🇾",code:"UY",region:"South America"},{id:"ec",name:"Ecuador",flag:"🇪🇨",code:"EC",region:"South America"},{id:"ve",name:"Venezuela",flag:"🇻🇪",code:"VE",region:"South America"},{id:"za",name:"South Africa",flag:"🇿🇦",code:"ZA",region:"Africa"},{id:"ng",name:"Nigeria",flag:"🇳🇬",code:"NG",region:"Africa"},{id:"eg",name:"Egypt",flag:"🇪🇬",code:"EG",region:"Africa"},{id:"ma",name:"Morocco",flag:"🇲🇦",code:"MA",region:"Africa"},{id:"ke",name:"Kenya",flag:"🇰🇪",code:"KE",region:"Africa"},{id:"gh",name:"Ghana",flag:"🇬🇭",code:"GH",region:"Africa"},{id:"et",name:"Ethiopia",flag:"🇪🇹",code:"ET",region:"Africa"},{id:"tz",name:"Tanzania",flag:"🇹🇿",code:"TZ",region:"Africa"},{id:"ru",name:"Russia",flag:"🇷🇺",code:"RU",region:"Europe/Asia"},{id:"ua",name:"Ukraine",flag:"🇺🇦",code:"UA",region:"Europe"},{id:"by",name:"Belarus",flag:"🇧🇾",code:"BY",region:"Europe"},{id:"lt",name:"Lithuania",flag:"🇱🇹",code:"LT",region:"Europe"},{id:"lv",name:"Latvia",flag:"🇱🇻",code:"LV",region:"Europe"},{id:"ee",name:"Estonia",flag:"🇪🇪",code:"EE",region:"Europe"},{id:"ro",name:"Romania",flag:"🇷🇴",code:"RO",region:"Europe"},{id:"bg",name:"Bulgaria",flag:"🇧🇬",code:"BG",region:"Europe"},{id:"hr",name:"Croatia",flag:"🇭🇷",code:"HR",region:"Europe"},{id:"si",name:"Slovenia",flag:"🇸🇮",code:"SI",region:"Europe"},{id:"sk",name:"Slovakia",flag:"🇸🇰",code:"SK",region:"Europe"},{id:"rs",name:"Serbia",flag:"🇷🇸",code:"RS",region:"Europe"},{id:"ba",name:"Bosnia and Herzegovina",flag:"🇧🇦",code:"BA",region:"Europe"},{id:"me",name:"Montenegro",flag:"🇲🇪",code:"ME",region:"Europe"},{id:"mk",name:"North Macedonia",flag:"🇲🇰",code:"MK",region:"Europe"},{id:"al",name:"Albania",flag:"🇦🇱",code:"AL",region:"Europe"},{id:"xk",name:"Kosovo",flag:"🇽🇰",code:"XK",region:"Europe"},{id:"md",name:"Moldova",flag:"🇲🇩",code:"MD",region:"Europe"},{id:"is",name:"Iceland",flag:"🇮🇸",code:"IS",region:"Europe"},{id:"lu",name:"Luxembourg",flag:"🇱🇺",code:"LU",region:"Europe"},{id:"mt",name:"Malta",flag:"🇲🇹",code:"MT",region:"Europe"},{id:"cy",name:"Cyprus",flag:"🇨🇾",code:"CY",region:"Europe"},{id:"mc",name:"Monaco",flag:"🇲🇨",code:"MC",region:"Europe"},{id:"ad",name:"Andorra",flag:"🇦🇩",code:"AD",region:"Europe"},{id:"sm",name:"San Marino",flag:"🇸🇲",code:"SM",region:"Europe"},{id:"va",name:"Vatican City",flag:"🇻🇦",code:"VA",region:"Europe"},{id:"li",name:"Liechtenstein",flag:"🇱🇮",code:"LI",region:"Europe"},{id:"pk",name:"Pakistan",flag:"🇵🇰",code:"PK",region:"Asia"},{id:"bd",name:"Bangladesh",flag:"🇧🇩",code:"BD",region:"Asia"},{id:"lk",name:"Sri Lanka",flag:"🇱🇰",code:"LK",region:"Asia"},{id:"np",name:"Nepal",flag:"🇳🇵",code:"NP",region:"Asia"},{id:"bt",name:"Bhutan",flag:"🇧🇹",code:"BT",region:"Asia"},{id:"mv",name:"Maldives",flag:"🇲🇻",code:"MV",region:"Asia"},{id:"af",name:"Afghanistan",flag:"🇦🇫",code:"AF",region:"Asia"},{id:"ir",name:"Iran",flag:"🇮🇷",code:"IR",region:"Asia"},{id:"iq",name:"Iraq",flag:"🇮🇶",code:"IQ",region:"Asia"},{id:"sy",name:"Syria",flag:"🇸🇾",code:"SY",region:"Asia"},{id:"lb",name:"Lebanon",flag:"🇱🇧",code:"LB",region:"Asia"},{id:"jo",name:"Jordan",flag:"🇯🇴",code:"JO",region:"Asia"},{id:"kw",name:"Kuwait",flag:"🇰🇼",code:"KW",region:"Asia"},{id:"qa",name:"Qatar",flag:"🇶🇦",code:"QA",region:"Asia"},{id:"bh",name:"Bahrain",flag:"🇧🇭",code:"BH",region:"Asia"},{id:"om",name:"Oman",flag:"🇴🇲",code:"OM",region:"Asia"},{id:"ye",name:"Yemen",flag:"🇾🇪",code:"YE",region:"Asia"},{id:"ge",name:"Georgia",flag:"🇬🇪",code:"GE",region:"Asia"},{id:"am",name:"Armenia",flag:"🇦🇲",code:"AM",region:"Asia"},{id:"az",name:"Azerbaijan",flag:"🇦🇿",code:"AZ",region:"Asia"},{id:"kz",name:"Kazakhstan",flag:"🇰🇿",code:"KZ",region:"Asia"},{id:"kg",name:"Kyrgyzstan",flag:"🇰🇬",code:"KG",region:"Asia"},{id:"tj",name:"Tajikistan",flag:"🇹🇯",code:"TJ",region:"Asia"},{id:"tm",name:"Turkmenistan",flag:"🇹🇲",code:"TM",region:"Asia"},{id:"uz",name:"Uzbekistan",flag:"🇺🇿",code:"UZ",region:"Asia"},{id:"mn",name:"Mongolia",flag:"🇲🇳",code:"MN",region:"Asia"},{id:"kp",name:"North Korea",flag:"🇰🇵",code:"KP",region:"Asia"},{id:"mm",name:"Myanmar",flag:"🇲🇲",code:"MM",region:"Asia"},{id:"la",name:"Laos",flag:"🇱🇦",code:"LA",region:"Asia"},{id:"kh",name:"Cambodia",flag:"🇰🇭",code:"KH",region:"Asia"},{id:"bn",name:"Brunei",flag:"🇧🇳",code:"BN",region:"Asia"},{id:"tl",name:"East Timor",flag:"🇹🇱",code:"TL",region:"Asia"},{id:"dz",name:"Algeria",flag:"🇩🇿",code:"DZ",region:"Africa"},{id:"tn",name:"Tunisia",flag:"🇹🇳",code:"TN",region:"Africa"},{id:"ly",name:"Libya",flag:"🇱🇾",code:"LY",region:"Africa"},{id:"sd",name:"Sudan",flag:"🇸🇩",code:"SD",region:"Africa"},{id:"ss",name:"South Sudan",flag:"🇸🇸",code:"SS",region:"Africa"},{id:"td",name:"Chad",flag:"🇹🇩",code:"TD",region:"Africa"},{id:"ne",name:"Niger",flag:"🇳🇪",code:"NE",region:"Africa"},{id:"ml",name:"Mali",flag:"🇲🇱",code:"ML",region:"Africa"},{id:"bf",name:"Burkina Faso",flag:"🇧🇫",code:"BF",region:"Africa"},{id:"sn",name:"Senegal",flag:"🇸🇳",code:"SN",region:"Africa"},{id:"gm",name:"Gambia",flag:"🇬🇲",code:"GM",region:"Africa"},{id:"gw",name:"Guinea-Bissau",flag:"🇬🇼",code:"GW",region:"Africa"},{id:"gn",name:"Guinea",flag:"🇬🇳",code:"GN",region:"Africa"},{id:"sl",name:"Sierra Leone",flag:"🇸🇱",code:"SL",region:"Africa"},{id:"lr",name:"Liberia",flag:"🇱🇷",code:"LR",region:"Africa"},{id:"ci",name:"Ivory Coast",flag:"🇨🇮",code:"CI",region:"Africa"},{id:"tg",name:"Togo",flag:"🇹🇬",code:"TG",region:"Africa"},{id:"bj",name:"Benin",flag:"🇧🇯",code:"BJ",region:"Africa"},{id:"zw",name:"Zimbabwe",flag:"🇿🇼",code:"ZW",region:"Africa"},{id:"zm",name:"Zambia",flag:"🇿🇲",code:"ZM",region:"Africa"}];function Fd(){return Fd=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Fd.apply(null,arguments)}function b3e(e,t=[]){let n=[];function r(o,i){const a=j.createContext(i),l=n.length;n=[...n,i];function u(f){const{scope:h,children:m,...p}=f,g=(h==null?void 0:h[e][l])||a,b=j.useMemo(()=>p,Object.values(p));return j.createElement(g.Provider,{value:b},m)}function d(f,h){const m=(h==null?void 0:h[e][l])||a,p=j.useContext(m);if(p)return p;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${o}\``)}return u.displayName=o+"Provider",[u,d]}const s=()=>{const o=n.map(i=>j.createContext(i));return function(a){const l=(a==null?void 0:a[e])||o;return j.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return s.scopeName=e,[r,x3e(s,...t)]}function x3e(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(o){const i=r.reduce((a,{useScope:l,scopeName:u})=>{const f=l(o)[`__scope${u}`];return{...a,...f}},{});return j.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function y3e(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function v3e(...e){return t=>e.forEach(n=>y3e(n,t))}const oZ=j.forwardRef((e,t)=>{const{children:n,...r}=e,s=j.Children.toArray(n),o=s.find(S3e);if(o){const i=o.props.children,a=s.map(l=>l===o?j.Children.count(i)>1?j.Children.only(null):j.isValidElement(i)?i.props.children:null:l);return j.createElement(PE,Fd({},r,{ref:t}),j.isValidElement(i)?j.cloneElement(i,void 0,a):null)}return j.createElement(PE,Fd({},r,{ref:t}),n)});oZ.displayName="Slot";const PE=j.forwardRef((e,t)=>{const{children:n,...r}=e;return j.isValidElement(n)?j.cloneElement(n,{...C3e(r,n.props),ref:t?v3e(t,n.ref):n.ref}):j.Children.count(n)>1?j.Children.only(null):null});PE.displayName="SlotClone";const w3e=({children:e})=>j.createElement(j.Fragment,null,e);function S3e(e){return j.isValidElement(e)&&e.type===w3e}function C3e(e,t){const n={...t};for(const r in t){const s=e[r],o=t[r];/^on[A-Z]/.test(r)?s&&o?n[r]=(...a)=>{o(...a),s(...a)}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}const N3e=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],iZ=N3e.reduce((e,t)=>{const n=j.forwardRef((r,s)=>{const{asChild:o,...i}=r,a=o?oZ:t;return j.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),j.createElement(a,Fd({},i,{ref:s}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{}),aZ="Progress",jS=100,[j3e]=b3e(aZ),[k3e,E3e]=j3e(aZ),lZ=j.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:s,getValueLabel:o=M3e,...i}=e,a=OE(s)?s:jS,l=uZ(r,a)?r:null,u=xw(l)?o(l,a):void 0;return j.createElement(k3e,{scope:n,value:l,max:a},j.createElement(iZ.div,Fd({"aria-valuemax":a,"aria-valuemin":0,"aria-valuenow":xw(l)?l:void 0,"aria-valuetext":u,role:"progressbar","data-state":cZ(l,a),"data-value":l??void 0,"data-max":a},i,{ref:t})))});lZ.propTypes={max(e,t,n){const r=e[t],s=String(r);return r&&!OE(r)?new Error(T3e(s,n)):null},value(e,t,n){const r=e[t],s=String(r),o=OE(e.max)?e.max:jS;return r!=null&&!uZ(r,o)?new Error(R3e(s,n)):null}};const _3e="ProgressIndicator",D3e=j.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...s}=e,o=E3e(_3e,r);return j.createElement(iZ.div,Fd({"data-state":cZ(o.value,o.max),"data-value":(n=o.value)!==null&&n!==void 0?n:void 0,"data-max":o.max},s,{ref:t}))});function M3e(e,t){return`${Math.round(e/t*100)}%`}function cZ(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function xw(e){return typeof e=="number"}function OE(e){return xw(e)&&!isNaN(e)&&e>0}function uZ(e,t){return xw(e)&&!isNaN(e)&&e<=t&&e>=0}function T3e(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${jS}\`.`}function R3e(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be:
@@ -1068,7 +1068,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1068
1068
 
1069
1069
  `)},flush(e){e.enqueue(`data: [DONE]
1070
1070
 
1071
- `)}})}});var YXe=zZe(()=>aee(Ar([qn({type:mt("text-start"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("text-delta"),id:ze(),delta:ze(),providerMetadata:ur.optional()}),qn({type:mt("text-end"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("error"),errorText:ze()}),qn({type:mt("tool-input-start"),toolCallId:ze(),toolName:ze(),providerExecuted:Cr().optional(),dynamic:Cr().optional()}),qn({type:mt("tool-input-delta"),toolCallId:ze(),inputTextDelta:ze()}),qn({type:mt("tool-input-available"),toolCallId:ze(),toolName:ze(),input:fo(),providerExecuted:Cr().optional(),providerMetadata:ur.optional(),dynamic:Cr().optional()}),qn({type:mt("tool-input-error"),toolCallId:ze(),toolName:ze(),input:fo(),providerExecuted:Cr().optional(),providerMetadata:ur.optional(),dynamic:Cr().optional(),errorText:ze()}),qn({type:mt("tool-output-available"),toolCallId:ze(),output:fo(),providerExecuted:Cr().optional(),dynamic:Cr().optional(),preliminary:Cr().optional()}),qn({type:mt("tool-output-error"),toolCallId:ze(),errorText:ze(),providerExecuted:Cr().optional(),dynamic:Cr().optional()}),qn({type:mt("reasoning-start"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("reasoning-delta"),id:ze(),delta:ze(),providerMetadata:ur.optional()}),qn({type:mt("reasoning-end"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("source-url"),sourceId:ze(),url:ze(),title:ze().optional(),providerMetadata:ur.optional()}),qn({type:mt("source-document"),sourceId:ze(),mediaType:ze(),title:ze(),filename:ze().optional(),providerMetadata:ur.optional()}),qn({type:mt("file"),url:ze(),mediaType:ze(),providerMetadata:ur.optional()}),qn({type:nee(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:ze().optional(),data:fo(),transient:Cr().optional()}),qn({type:mt("start-step")}),qn({type:mt("finish-step")}),qn({type:mt("start"),messageId:ze().optional(),messageMetadata:fo().optional()}),qn({type:mt("finish"),messageMetadata:fo().optional()}),qn({type:mt("abort")}),qn({type:mt("message-metadata"),messageMetadata:fo()})])));function GXe(e){return e.type.startsWith("data-")}function pee(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=pee(o,s):n[r]=s}return n}function KXe(e){const t=["ROOT"];let n=-1,r=null;function s(l,u,d){switch(l){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":s(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function gee(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Bw({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Bw({text:KXe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Ky(e){return e.type.startsWith("tool-")}function ZXe(e){return e.type==="dynamic-tool"}function f_(e){return Ky(e)||ZXe(e)}function _L(e){return e.type.split("-").slice(1).join("-")}function XXe({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function QXe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,m,p;function g(w){const S=u.message.parts.filter(Ky).find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function b(w){const S=u.message.parts.filter(N=>N.type==="dynamic-tool").find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function x(w){var C;const S=u.message.parts.find(E=>Ky(E)&&E.toolCallId===w.toolCallId),N=w,_=S;S!=null?(S.state=w.state,_.input=N.input,_.output=N.output,_.errorText=N.errorText,_.rawInput=N.rawInput,_.preliminary=N.preliminary,_.providerExecuted=(C=N.providerExecuted)!=null?C:S.providerExecuted,N.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=N.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:N.input,output:N.output,rawInput:N.rawInput,errorText:N.errorText,providerExecuted:N.providerExecuted,preliminary:N.preliminary,...N.providerMetadata!=null?{callProviderMetadata:N.providerMetadata}:{}})}function y(w){var C;const S=u.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===w.toolCallId),N=w,_=S;S!=null?(S.state=w.state,_.toolName=w.toolName,_.input=N.input,_.output=N.output,_.errorText=N.errorText,_.rawInput=(C=N.rawInput)!=null?C:_.rawInput,_.preliminary=N.preliminary,N.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=N.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:N.input,output:N.output,errorText:N.errorText,preliminary:N.preliminary,...N.providerMetadata!=null?{callProviderMetadata:N.providerMetadata}:{}})}async function v(w){if(w!=null){const C=u.message.metadata!=null?pee(u.message.metadata,w):w;t!=null&&await CL({value:C,schema:t}),u.message.metadata=C}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,w.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const w=u.message.parts.filter(Ky);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:C}=await gee(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:C}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:C}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:_L(w),state:"output-available",input:w.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:_L(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:a.errorText})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(GXe(a)){(n==null?void 0:n[a.type])!=null&&await CL({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const C=w.id!=null?u.message.parts.find(S=>w.type===S.type&&w.id===S.id):void 0;C!=null?C.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function JXe({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}Bx({prefix:"aitxt",size:24});Bx({prefix:"aiobj",size:24});var eQe=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(r){n(r)}}),this.processQueue()})}};Bx({prefix:"aiobj",size:24});var tQe={};FXe(tQe,{object:()=>rQe,text:()=>nQe});var nQe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),rQe=({schema:e})=>{const t=PXe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await gee(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await Bw({text:n});if(!s.success)throw new kL({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await AI({value:s.value,schema:t});if(!o.success)throw new kL({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}},sQe=Yf({name:ze(),version:ze()}),OI=Yf({_meta:xr(Wt({}).loose())}),Cb=OI,oQe=Wt({method:ze(),params:xr(OI)}),iQe=Yf({experimental:xr(Wt({}).loose()),logging:xr(Wt({}).loose()),prompts:xr(Yf({listChanged:xr(Cr())})),resources:xr(Yf({subscribe:xr(Cr()),listChanged:xr(Cr())})),tools:xr(Yf({listChanged:xr(Cr())}))});Cb.extend({protocolVersion:ze(),capabilities:iQe,serverInfo:sQe,instructions:xr(ze())});var aQe=Cb.extend({nextCursor:xr(ze())}),lQe=Wt({name:ze(),description:xr(ze()),inputSchema:Wt({type:mt("object"),properties:xr(Wt({}).loose())}).loose()}).loose();aQe.extend({tools:ou(lQe)});var cQe=Wt({type:mt("text"),text:ze()}).loose(),uQe=Wt({type:mt("image"),data:ZJ(),mimeType:ze()}).loose(),bee=Wt({uri:ze(),mimeType:xr(ze())}).loose(),dQe=bee.extend({text:ze()}),fQe=bee.extend({blob:ZJ()}),hQe=Wt({type:mt("resource"),resource:Ar([dQe,fQe])}).loose();Cb.extend({content:ou(Ar([cQe,uQe,hQe])),isError:Cr().default(!1).optional()}).or(Cb.extend({toolResult:fo()}));var sC="2.0",mQe=Wt({jsonrpc:mt(sC),id:Ar([ze(),wb().int()])}).merge(oQe).strict(),pQe=Wt({jsonrpc:mt(sC),id:Ar([ze(),wb().int()]),result:Cb}).strict(),gQe=Wt({jsonrpc:mt(sC),id:Ar([ze(),wb().int()]),error:Wt({code:wb().int(),message:ze(),data:xr(fo())})}).strict(),bQe=Wt({jsonrpc:mt(sC)}).merge(Wt({method:ze(),params:xr(OI)})).strict();Ar([mQe,bQe,pQe,gQe]);async function xQe(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var yQe=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await Mf(this.body),l=await Mf(this.headers),u=await Mf(this.credentials),d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...l,...t.headers},credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(r=d==null?void 0:d.api)!=null?r:this.api,h=(d==null?void 0:d.headers)!==void 0?d.headers:{...l,...t.headers},m=(d==null?void 0:d.body)!==void 0?d.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},p=(s=d==null?void 0:d.credentials)!=null?s:u,b=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:SL({"Content-Type":"application/json",...h},`ai-sdk/${EL}`,wL()),body:JSON.stringify(m),credentials:p,signal:e});if(!b.ok)throw new Error((i=await b.text())!=null?i:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await Mf(this.body),a=await Mf(this.headers),l=await Mf(this.credentials),u=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:{...a,...e.headers},credentials:l,requestMetadata:e.metadata})),d=(n=u==null?void 0:u.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=(u==null?void 0:u.headers)!==void 0?u.headers:{...a,...e.headers},h=(r=u==null?void 0:u.credentials)!=null?r:l,p=await((s=this.fetch)!=null?s:globalThis.fetch)(d,{method:"GET",headers:SL(f,`ai-sdk/${EL}`,wL()),credentials:h});if(p.status===204)return null;if(!p.ok)throw new Error((o=await p.text())!=null?o:"Failed to fetch the chat response.");if(!p.body)throw new Error("The response body is empty.");return this.processResponseStream(p.body)}},FI=class extends yQe{constructor(e={}){super(e)}processResponseStream(e){return HZe({stream:e,schema:YXe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},vQe=class{constructor({generateId:e=TZe,id:t=e(),transport:n=new FI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new eQe,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await xQe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(p=>p.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>f_(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>f_(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=l,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let u=!1,d=!1,f=!1;try{const h={state:XXe({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};h.abortController.signal.addEventListener("abort",()=>{u=!0}),this.activeResponse=h;let m;if(e==="resume-stream"){const g=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(g==null){this.setStatus({status:"ready"});return}m=g}else m=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:h.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const p=g=>this.jobExecutor.run(()=>g({state:h.state,write:()=>{var b;this.setStatus({status:"streaming"}),h.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,h.state.message):this.state.pushMessage(h.state.message)}}));await JXe({stream:QXe({stream:m,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:p,onError:g=>{throw g}}),onError:g=>{throw g}}),this.setStatus({status:"ready"})}catch(h){if(u||h.name==="AbortError")return u=!0,this.setStatus({status:"ready"}),null;f=!0,h instanceof TypeError&&(h.message.toLowerCase().includes("fetch")||h.message.toLowerCase().includes("network"))&&(d=!0),this.onError&&h instanceof Error&&this.onError(h),this.setStatus({status:"error",error:h})}finally{try{(o=this.onFinish)==null||o.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:u,isDisconnect:d,isError:f})}catch(h){console.error(h)}this.activeResponse=void 0}(i=this.sendAutomaticallyWhen)!=null&&i.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(a=this.lastMessage)==null?void 0:a.id,metadata:t,headers:n,body:r})}};function wQe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(f_);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function SQe(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},l)}}var CQe=SQe;const NQe=Vc(CQe);var xee=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},In=(e,t,n)=>(xee(e,t,"read from private field"),n?n.call(e):t.get(e)),Vi=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Ll=(e,t,n,r)=>(xee(e,t,"write to private field"),t.set(e,n),n);function jQe(e,t){return t!=null?NQe(e,t):e}var ko,Zy,Xy,Yp,Gp,Kp,Of,h_,m_,kQe=class{constructor(e=[]){Vi(this,ko,void 0),Vi(this,Zy,"ready"),Vi(this,Xy,void 0),Vi(this,Yp,new Set),Vi(this,Gp,new Set),Vi(this,Kp,new Set),this.pushMessage=t=>{Ll(this,ko,In(this,ko).concat(t)),In(this,Of).call(this)},this.popMessage=()=>{Ll(this,ko,In(this,ko).slice(0,-1)),In(this,Of).call(this)},this.replaceMessage=(t,n)=>{Ll(this,ko,[...In(this,ko).slice(0,t),this.snapshot(n),...In(this,ko).slice(t+1)]),In(this,Of).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?jQe(t,n):t;return In(this,Yp).add(r),()=>{In(this,Yp).delete(r)}},this["~registerStatusCallback"]=t=>(In(this,Gp).add(t),()=>{In(this,Gp).delete(t)}),this["~registerErrorCallback"]=t=>(In(this,Kp).add(t),()=>{In(this,Kp).delete(t)}),Vi(this,Of,()=>{In(this,Yp).forEach(t=>t())}),Vi(this,h_,()=>{In(this,Gp).forEach(t=>t())}),Vi(this,m_,()=>{In(this,Kp).forEach(t=>t())}),Ll(this,ko,e)}get status(){return In(this,Zy)}set status(e){Ll(this,Zy,e),In(this,h_).call(this)}get error(){return In(this,Xy)}set error(e){Ll(this,Xy,e),In(this,m_).call(this)}get messages(){return In(this,ko)}set messages(e){Ll(this,ko,[...e]),In(this,Of).call(this)}};ko=new WeakMap;Zy=new WeakMap;Xy=new WeakMap;Yp=new WeakMap;Gp=new WeakMap;Kp=new WeakMap;Of=new WeakMap;h_=new WeakMap;m_=new WeakMap;var Ff,DL=class extends vQe{constructor({messages:e,...t}){const n=new kQe(e);super({...t,state:n}),Vi(this,Ff,void 0),this["~registerMessagesCallback"]=(r,s)=>In(this,Ff)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>In(this,Ff)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>In(this,Ff)["~registerErrorCallback"](r),Ll(this,Ff,n)}};Ff=new WeakMap;function yee({experimental_throttle:e,resume:t=!1,...n}={}){const r=j.useRef("chat"in n?n.chat:new DL(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new DL(n));const o="id"in n?n.id:null,i=j.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=j.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=j.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=j.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=j.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return j.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolResult}}function EQe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function _Qe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function DQe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function MQe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function vee(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:MQe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function wee(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function TQe(){var b;const{authToken:e,tokenProps:t}=Ge(),n=Q(x=>x.dashboard.aiScopeTables),r=(b=s1().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=yee({transport:new FI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Oi.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:x.currentAIContext,reasoningEffort:x.reasoningEffort,showReasoning:x.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:x,body:y})=>({body:{...y,messages:$W(x)}})}),onToolCall:m,sendAutomaticallyWhen:wQe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function m({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:vee(n||[])}}),x.toolName==="getDashboardContext"){const y=Q.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const p=!["ready","error"].includes(l),g=wee(d);return{sendMessage:s,regenerate:a,isLoading:p,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function See(){var u;const{authToken:e,tokenProps:t}=Ge(),n=(u=s1().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=cn({queryKey:["assistant-profile",n],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function Cee({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:c.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[c.jsxs("div",{className:"mb-3 flex items-center",children:[c.jsx(M8,{className:"mr-2 h-4 w-4 text-muted-foreground"}),c.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function Vw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(fD,{className:r});case"view":return c.jsx(vd,{className:r});case"materialized view":return c.jsx(Iae,{className:r});case"model":return c.jsx(a1,{className:r});case"file":return c.jsx(ki,{className:r});case"dataset":return c.jsx(al,{className:r});case"upload":return c.jsx(pD,{className:r});case"url":return c.jsx(L8,{className:r});default:return c.jsx(i1,{className:r})}}const Nee=D.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(va,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(ds.Input,{ref:n,className:X("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));Nee.displayName=ds.Input.displayName;const vy=e=>e.label||(e==null?void 0:e.name),ML=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function RQe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=Ge(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=j.useState(""),[p,g]=j.useState(""),b=s.filter(S=>{if(!h)return!0;const N=vy(S).toLowerCase(),_=ML(S).toLowerCase(),E=h.toLowerCase();return N.includes(E)||_.includes(E)});j.useEffect(()=>{e||(m(""),g(""))},[e]),j.useEffect(()=>{b.length>0&&!p&&g(vy(b[0]))},[b,p]);const x=()=>{if(!p)return;const S=b.find(N=>vy(N)===p);S&&(o.some(_=>"id"in S&&"id"in _?S.id===_.id:S.name===_.name&&S.connectionId===_.connectionId)||t(S),i(S),r())},y=S=>{(S.key==="Tab"||S.key==="Enter")&&(S.preventDefault(),x())};if(!e)return null;const v=S=>o.some(N=>"id"in S&&"id"in N?S.id===N.id:S.name===N.name&&S.connectionId===N.connectionId),w=o.length===s.length,C=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(FS,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(Nee,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(kr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),a==null||a()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),C&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),l==null||l()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(yt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs($S,{className:"min-h-60",children:[c.jsx(LS,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(kr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(zS,{children:b.map((S,N)=>{const _=v(S),E="id"in S?S.id:`${S.connectionId}-${S.name}`,k=vy(S);return c.jsxs(BS,{value:k,onSelect:()=>{_?n==null||n(S):t(S)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:X("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:Vw(S.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:k}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:ML(S)})]}),_&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx($r,{className:"h-3 w-3 text-background"})})]},E)})})]})]})})}const p_=e=>e.name||e.name,IQe=e=>{const t=p_(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"font-medium",children:t}),n&&c.jsx("div",{className:"text-sm text-muted-foreground",children:n}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function AQe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=j.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(On,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(un,{children:[c.jsx(dn,{asChild:!0,children:c.jsxs(Oe,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[Vw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:p_(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(yt,{className:"h-3 w-3"})})]})}),c.jsx(pn,{side:"top",className:"max-w-xs",children:IQe(d)})]},h)}),u&&c.jsxs(un,{open:s,onOpenChange:o,children:[c.jsx(dn,{asChild:!0,children:c.jsxs(Oe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(Aae,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(yt,{className:"h-3 w-3"})})]})}),c.jsx(pn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:Vw(d.type,{size:"h-3 w-3"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:p_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(yt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function jee(e){return e.type==="dataset"&&e.label||e.name}function PQe(e){const t=[];return t.push({label:"Type",value:e.type}),t.push({label:"Name",value:e.name}),e.connectionType&&t.push({label:"Connection",value:e.connectionType}),e.database&&t.push({label:"Database",value:e.database}),e.schema&&t.push({label:"Schema",value:e.schema}),e.type==="dataset"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="dataset"&&e.description&&t.push({label:"Description",value:e.description}),e.type==="model"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="model"&&e.description&&t.push({label:"Description",value:e.description}),t}function OQe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(de,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(Oe,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),jee(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(yt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function FQe(e){const{tokenProps:t}=Ge(),n=Q(l=>l.authToken)||e;Ee(l=>l.selectedConnectionId),Ee(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=cn({queryKey:["semantic-domains"],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function $Qe(e,t){const{tokenProps:n}=Ge(),r=Q(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=cn({queryKey:["datasets",e],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function LQe(e){var g,b;const{tokenProps:t}=Ge(),n=Q(x=>x.authToken)||e,{connections:r}=Pi(e),s=Ee(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:m}=cn({queryKey:["databases",s],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:l}}function zQe(e){var g;const{tokenProps:t}=Ge(),n=Q(b=>b.authToken)||e,{connections:r}=Pi(e),s=Ee(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Ee(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:m}=cn({queryKey:["schemas",s,o],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:l}}function kee(e){const{tokenProps:t}=Ge(),n=Q(h=>h.authToken)||e,{connections:r}=Pi(e),s=Ee(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=cn({queryKey:["dataModels",s],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function BQe(){var C,S,N;const e=Ee(_=>_.card.dataSource);Ee(_=>_.actions.updateDirectSource);const t=Ee(_=>_.actions.updateDataSource),[n,r]=j.useState(""),{selectedConnection:s,error:o}=Pi(),{databases:i,isPending:a,error:l,label:u}=LQe(),{schemas:d,isPending:f,error:h,label:m}=zQe(),{error:p}=kee(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=_=>{e&&t({...e,dbSelection:{database:_,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=_=>{var k;if(!((k=e==null?void 0:e.dbSelection)!=null&&k.database))return;const E=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...E,schema:_},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||p)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[m,": ",h.message]}),p&&c.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),c.jsx(oe,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:u}),c.jsxs(rt,{value:((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)||"",onValueChange:v,disabled:a,children:[c.jsx(tt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(Mn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(nt,{children:i.map(_=>c.jsx(ge,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]}),((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:m}),c.jsxs(rt,{value:((N=e==null?void 0:e.dbSelection)==null?void 0:N.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(tt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(Mn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(nt,{children:d.map(_=>c.jsx(ge,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]})]})]})}function VQe(){const e=Ee(l=>l.card.dataSource),t=Ee(l=>l.actions.updateDataSource),[n,r]=j.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(pD,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(de,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(ki,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(yt,{className:"h-3 w-3"})})]},l.id))})]})]})}function HQe(){const e=Ee(f=>f.card.dataSource),t=Ee(f=>f.actions.updateDataSource),[n,r]=j.useState(""),[s,o]=j.useState(""),[i,a]=j.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(m=>m.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(jn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(jn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[c.jsx("option",{value:"api",children:"API Endpoint"}),c.jsx("option",{value:"csv",children:"CSV File"}),c.jsx("option",{value:"json",children:"JSON File"})]})]}),c.jsxs(oe,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(kr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(de,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(i1,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(yt,{className:"h-3 w-3"})})]},f.id))})]})]})}function UQe(e,t){var y,v;const{tokenProps:n}=Ge(),r=Q(w=>w.authToken)||t,{connections:s}=Pi(t),o=Ee(w=>{var C,S;return(S=(C=w==null?void 0:w.card)==null?void 0:C.dataSource)==null?void 0:S.connectionId}),i=Ee(w=>{var C,S,N;return(N=(S=(C=w==null?void 0:w.card)==null?void 0:C.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.database}),a=Ee(w=>{var C,S,N;return(N=(S=(C=w==null?void 0:w.card)==null?void 0:C.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:m,isLoading:p,error:g,refetch:b}=cn({queryKey:[e,o,i,a],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(w=>{var C;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(C=w==null?void 0:w.table_type)==null?void 0:C.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function Hw({title:e,message:t}){return c.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:c.jsxs("div",{className:"flex items-start gap-4",children:[c.jsx(yd,{className:"h-6 w-6 flex-shrink-0"}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h4",{className:"text-base font-semibold",children:e}),t&&c.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function WQe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Pi(),[i,a]=j.useState(""),[l,u]=j.useState(""),[d,f]=j.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=lr(),{entities:p,isLoading:g,error:b}=UQe("table"),{dataModels:x,isPending:y,error:v}=kee(),w=k=>{const M=s.find(O=>O.id===k);if(!M)return;const T=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:k,connectionType:M.type,mode:T,dbSelection:{database:"",schema:"",entityType:"table"}}),m(k)},C=k=>{var R,I;const M=n||[],T=M.some(L=>L.name===k.name&&L.type===k.type);let O;if(T)O=M.filter(L=>!(L.name===k.name&&L.type===k.type));else{const L={connectionId:e.connectionId,connectionType:e.connectionType,type:k.type,dbObjectType:k.dbObjectType,database:((R=e.dbSelection)==null?void 0:R.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:k.name,dialect:k.dialect};O=[...M,L]}t==null||t(O)},S=k=>{const M=n||[],T=M.some(R=>R.type==="model"&&R.name===k.name);let O;T?O=M.filter(R=>!(R.type==="model"&&R.name===k.name)):O=[...M,k],t==null||t(O)},N=p.filter(k=>k.name.toLowerCase().includes(i.toLowerCase())),_=x.filter(k=>k.name.toLowerCase().includes(l.toLowerCase())),E=j.useCallback(()=>{if(!t)return;const k=n||[];let M=[...k];if(d==="tables"){const O=N.filter(R=>!k.some(I=>I.name===R.name&&I.type==="table")).map(R=>{var I,L;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:R.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((L=e.dbSelection)==null?void 0:L.schema)||"",name:R.name,dialect:R.dialect}});M=[...k,...O]}else if(d==="datamodels"){const T=_.filter(O=>!k.some(R=>R.name===O.name&&R.type==="model"));M=[...k,...T]}t(M)},[d,N,_,n,e,t]);return j.useEffect(()=>{r&&r(E)},[r,E]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(rt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(tt,{className:"w-full",children:c.jsx(at,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(nt,{children:s.map(k=>c.jsx(ge,{className:"hover:bg-muted",value:k.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(al,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:k.name}),c.jsx(Oe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:k.type})]})},k.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(VQe,{}),e.connectionType==="url"&&c.jsx(HQe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(BQe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(As,{defaultValue:"tables",value:d,onValueChange:k=>f(k),className:"w-full",children:[c.jsxs(cs,{className:"grid w-full grid-cols-2",children:[c.jsxs(qt,{value:"tables",children:["Tables & Views (",N.length,")"]}),c.jsxs(qt,{value:"datamodels",children:["Data Models (",_.length,")"]})]}),c.jsxs(nr,{value:"tables",className:"space-y-2",children:[c.jsx(Nn,{placeholder:"Search tables and views...",value:i,onChange:k=>a(k.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(Hw,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):N.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):N.map(k=>{const M=n.some(T=>T.name===k.name&&T.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(k),children:[c.jsx(nn,{id:`table-${k.name}`,checked:M,onCheckedChange:()=>C(k),onClick:T=>T.stopPropagation(),disabled:g}),c.jsxs(de,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[k.name,k.dbObjectType==="view"&&c.jsx(Oe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),k.dbObjectType==="materialized view"&&c.jsx(Oe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},k.name)})})]}),c.jsxs(nr,{value:"datamodels",className:"space-y-2",children:[c.jsx(Nn,{placeholder:"Search data models...",value:l,onChange:k=>u(k.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(Hw,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):_.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):_.map(k=>{const M=n.some(T=>T.name===k.name&&T.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(k),children:[c.jsx(nn,{id:`dataModel-${k.name}`,checked:M,onCheckedChange:()=>S(k),onClick:T=>T.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(de,{className:"cursor-pointer",children:k.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:k.description})]})]},k.name)})})]})]})})})]})]})]})}function qQe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var C;const[l,u]=j.useState(""),d=j.useCallback(S=>{const N={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...N})},[e,t]);j.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:m}=FQe(),p=o?f.filter(S=>s.includes(S.id)):f,{datasets:g,isPending:b,error:x}=$Qe(e==null?void 0:e.semanticDomainId),y=S=>{const N=r||[],_=N.some(k=>k.id===S.id&&k.type==="dataset");let E;if(_)E=N.filter(k=>!(k.id===S.id&&k.type==="dataset"));else{const k={id:S.id,datasetType:S.type,name:S.name||S.table,label:S.label,domainId:S.domainId,description:S.description,database:S.database,schema:S.schema,type:"dataset",connectionId:S.connectionId,connectionType:S.connectionType,dialect:S.dialect,datamodelId:S.datamodelId,sql:S.sql};E=[...N,k]}n==null||n(E)},v=g.filter(S=>S.name.toLowerCase().includes(l.toLowerCase())),w=j.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const S=r||[],_=v.filter(k=>!S.some(M=>M.id===k.id&&M.type==="dataset")).map(k=>({id:k.id,datasetType:k.type,name:k.name||k.table,label:k.label,domainId:k.domainId,description:k.description,database:k.database,schema:k.schema,type:"dataset",connectionId:k.connectionId,connectionType:k.connectionType,dialect:k.dialect,datamodelId:k.datamodelId,sql:k.sql})),E=[...S,..._];n(E)},[v,r,e==null?void 0:e.semanticDomainId,n]);return j.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(rt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(tt,{className:"w-full",children:c.jsx(at,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((C=p.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:C.label)||"Select semantic domain"})}),c.jsx(nt,{children:p.map(S=>c.jsx(ge,{className:"hover:bg-muted",value:S.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:S.label}),c.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),m&&c.jsx(Hw,{title:"Error loading semantic models",message:m.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Nn,{placeholder:"Search datasets...",value:l,onChange:S=>u(S.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(Hw,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(S=>{const N=r.some(_=>_.id===S.id&&_.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(S),children:[c.jsx(nn,{id:`dataset-${S.id}`,checked:N,onCheckedChange:()=>y(S),onClick:_=>_.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(de,{className:"cursor-pointer font-medium",children:S.label||S.name}),c.jsx("span",{className:"text-xs text-gray-500",children:S.description})]})]},S.label||S.name)})})]})]})]})}function $I({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Ge(),{allowedSemanticDomains:i}=o,[a,l]=j.useState([]),{updateDataSource:u}=lr(),d=Q(M=>M.isVisualEditing),f=Q(M=>M.dashboard.aiContext),{setAiContext:h}=Gt(),m=j.useRef(null),[p,g]=j.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=j.useCallback(M=>{const T=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:T,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...T!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=j.useCallback(M=>{u({...n,...M})},[n,u]);j.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),j.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),j.useEffect(()=>{e?l(s||[]):(m.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const C=M=>{const T=a.filter(O=>!(O.name===M.name&&O.type===M.type));l(T)},S=()=>{l([])},N=j.useCallback(M=>{l(M)},[]),_=j.useCallback(()=>{m.current&&m.current()},[]),E=j.useCallback(M=>{m.current=M,g(!0)},[]);function k(){var M,T;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const O=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,R=(T=a==null?void 0:a[0])==null?void 0:T.connectionType;u({...n,connectionId:O,connectionType:R,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsx(Ur,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Wr,{className:"flex-shrink-0",children:[c.jsx(qr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(Is,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(As,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(cs,{className:"grid w-full grid-cols-2",children:[c.jsx(qt,{value:"database",children:"Direct Source"}),c.jsx(qt,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(qQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:E}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(WQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,onRegisterSelectAll:E})]})}),c.jsx(OQe,{selectedEntities:a,onDeselectEntity:C}),c.jsx(Rs,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(oe,{variant:"outline",onClick:_,disabled:!p,children:"Select All"}),c.jsx(oe,{variant:"outline",onClick:S,disabled:a.length===0,children:"Clear All"}),c.jsxs(oe,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(yt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(oe,{onClick:k,children:[c.jsx($r,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function YQe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=j.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=Ba-n;if(l.length>u){Fe.error(`You can only attach ${Ba} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=lJ(l);if(f.forEach(({file:h,error:m})=>{Fe.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>jI(m)));e(h)}catch(h){console.error("Failed to process files:",h),Fe.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=Ba}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Ba,title:n>=Ba?`Maximum ${Ba} files allowed`:"Attach files",children:c.jsx(aD,{className:"h-4 w-4 text-muted-foreground"})})]})}function GQe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=j.useState(!1),a=j.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=j.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=j.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=j.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const m=Ba-r;if(h.length>m){Fe.error(`You can only attach ${Ba} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=lJ(h);if(g.forEach(({file:b,error:x})=>{Fe.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>jI(x)));t(b),Fe.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),Fe.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:X("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(pD,{className:"h-8 w-8 text-primary"}),c.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ba-r," slot(s) available"]})]})})]})}const LI=j.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=j.useState(!1),[h,m]=j.useState(!1),[p,g]=j.useState(!1),b=j.useRef(null),x=$m();YNe(),qNe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:C}=G1(),{queueMessage:S}=Lm(),{addFileAttachment:N,removeFileAttachment:_,clearFileAttachments:E,getFileAttachments:k}=rT(),M=nT(l),T=Ee(H=>H.card.dataSource),O=Q(H=>H.dashboard.aiContext),R=Q(H=>{var G;return(G=H.dashboard.aiContext)==null?void 0:G.selectedEntities});j.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=j.useCallback(()=>{const H=b.current;if(H){if(!e||e.length===0){H.style.height="10px";return}H.style.height="auto";const G=Math.min(Math.max(H.scrollHeight,10),200);H.style.height=`${G}px`}},[e]);j.useEffect(()=>{I()},[I]),j.useEffect(()=>{const H=setTimeout(()=>{I()},0);return()=>clearTimeout(H)},[I]);const L=()=>{const H=e.trim();!H&&M.length===0||(a!=="ready"?(S(l,H,M),t(""),E(l)):r({preventDefault:()=>{}}))},F=H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),L()),H.key==="@"&&(W(),f(!0))},V=j.useCallback(H=>{const G=lqe(H.nativeEvent);G.length>0&&(H.preventDefault(),G.forEach(async K=>{const te=await jI(K);N(l,te)}))},[N,l]),$=j.useCallback(H=>{H.forEach(G=>{N(l,G)})},[N,l]),P=j.useCallback(H=>{H.forEach(G=>{N(l,G)})},[N,l]),U=j.useCallback(H=>{_(l,H)},[_,l]),B=H=>{if(x.selectedEntities.some(K=>K.id&&K.id===H.id||K.name===H.name)){const K=x.selectedEntities.filter(te=>!(te.id&&te.id===H.id||te.name===H.name));y({selectedEntities:K})}else{const K=[...x.selectedEntities,H];y({selectedEntities:K})}},A=H=>{B(H)},Y=H=>{var te;if(!x.selectedEntities.some(Z=>Z.id&&Z.id===H.id||Z.name===H.name)){const Z=[...x.selectedEntities,H];y({selectedEntities:Z})}const K="label"in H?H.label:H.name;t(e+`@${K} `),f(!1),(te=b.current)==null||te.focus()},z=H=>{const G=x.selectedEntities.filter(Z=>!(Z.id&&Z.id===H.id||Z.name===H.name));y({selectedEntities:G});const te=`@${"label"in H?H.label:H.name}`;e.includes(te)&&t(e.replace(te,"").trim())},q=H=>{const G=new Set(H.map(Z=>Z.id||Z.name)),K=x.selectedEntities.filter(Z=>!G.has(Z.id||Z.name));y({selectedEntities:K});let te=e;H.forEach(Z=>{const se=`@${"label"in Z?Z.label:Z.name}`;te=te.replace(se,"").trim()}),t(te)},W=j.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})},[x.selectedEntities.length,O==null?void 0:O.selectedEntities,y]);return c.jsxs(GQe,{onFilesDropped:$,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(AQe,{entities:x.selectedEntities,availableEntities:R||[],onRemoveEntity:z,onRemoveEntities:q}),M.length>0&&c.jsx(cqe,{files:M,onRemove:U,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:F,onPaste:V,onFocus:()=>{I(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(ks,{open:d,onOpenChange:H=>{H&&W(),f(H)},children:[c.jsx(Es,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Eae,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(_s,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:H=>H.preventDefault(),children:c.jsx(RQe,{isOpen:!0,onSelect:B,onDeselect:A,onClose:()=>{var H;f(!1),(H=b.current)==null||H.focus()},availableEntities:R||[],selectedEntities:x.selectedEntities,onTabComplete:Y,onSelectAll:()=>{R&&y({selectedEntities:R})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),m(!0)}})})]}),c.jsx(YQe,{onFilesSelected:P,disabled:s,currentFileCount:M.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(oe,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(Wae,{className:"size-3.5 bg-background"})}),!s&&c.jsx(oe,{disabled:!e.trim()&&M.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:L,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(q8,{className:"size-4"})})]})]})]}),c.jsx($I,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:m,dataSource:T||tC,dialogMode:"aiContext"})]})});LI.displayName="ChatInputWithContext";function Eee({assistantType:e,className:t}){const n=LW(e),{removeFromQueue:r}=Lm();return n.length===0?null:c.jsxs("div",{className:X("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(ml,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>c.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(yt,{className:"h-3 w-3"})})]})},s.id))})]})}function _ee({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=LW(e),{dequeueMessage:o}=Lm();j.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function Dee(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=j.useRef(null),[a,l]=j.useState(!0),[u,d]=j.useState(!0),[f,h]=j.useState(!1),[m,p]=j.useState(0),g=j.useRef(0),b=j.useRef(!1),x=j.useRef(0),y=j.useRef(a),v=j.useRef(),w=j.useRef({key:null,count:0,length:0}),C=j.useCallback(()=>{const E=i.current;return E?E.scrollHeight-E.scrollTop-E.clientHeight:0},[]),S=j.useCallback((E={})=>{if(!i.current)return;const{force:M=!1,instant:T=!1}=E;if(!M&&!y.current||!a&&!M)return;const O=T||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!M&&!y.current){b.current=!1,v.current=void 0;return}const R=i.current;if(!R){b.current=!1,v.current=void 0;return}const I=R.scrollHeight;O==="smooth"&&"scrollTo"in R?R.scrollTo({top:I,behavior:O}):R.scrollTop=I,g.current=R.scrollTop,d(!0),l(!0),y.current=!0,h(!1),p(0),b.current=!1,v.current=void 0})},[r,a]),N=j.useCallback(()=>{const E=i.current;if(!E)return;const k=g.current,M=E.scrollTop,T=M-k;if(g.current=M,T<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const O=C()<=n;d(O),l(O),y.current=O,O&&(h(!1),p(0))},[C,n]),_=j.useCallback(()=>{p(0),h(!1)},[]);return j.useEffect(()=>{y.current=a},[a]),j.useEffect(()=>{const E=i.current;if(!E||!e||e.length===0){h(!1),p(0),w.current={key:null,count:0,length:0},g.current=E?E.scrollTop:0,x.current=E?E.scrollHeight:0;return}g.current=E.scrollTop,x.current=E.scrollHeight;const k=w.current,M=e[e.length-1],T=(M==null?void 0:M.id)??(M==null?void 0:M.messageId)??(M==null?void 0:M.createdAt)??(M==null?void 0:M.timestamp)??e.length,O=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce(($,P)=>P?typeof P=="string"?$+P.length:typeof P.text=="string"?$+P.text.length:typeof P.content=="string"?$+P.content.length:typeof P.value=="string"?$+P.value.length:$:$,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,R=e.length>k.count,I=T!==k.key,L=O>k.length,F=s&&(M==null?void 0:M.role)==="assistant"&&!R&&(I||L),V=o||F;if(w.current={key:T,count:e.length,length:O},a&&(R||I||L||V)){S({force:!1,instant:V});return}if(!a&&R){const $=e.length-k.count;$>0&&(h(!0),p(P=>P+$))}else!a&&L&&(h(!0),p($=>$>0?$:1))},[e,S,a,s,o]),j.useEffect(()=>{S({instant:!0})},[S]),j.useEffect(()=>{if(typeof ResizeObserver>"u")return;const E=i.current;if(!E)return;x.current=E.scrollHeight;const k=new ResizeObserver(()=>{const M=i.current;if(!M)return;const T=x.current,O=M.scrollHeight;x.current=O,!b.current&&y.current&&O>T&&S({force:!1,instant:!0})});return k.observe(E),()=>{k.disconnect()}},[S]),j.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:m,scrollToBottom:S,handleScroll:N,resetNewMessageCount:_}}function Mee(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=j.useState(r),a=j.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=j.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=j.useCallback(()=>{i(r)},[r]);return j.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function Tee(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:r.text||"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:cJ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const KQe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function ZQe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=j.useState(!1),[a,l]=j.useState(T_),[u,d]=j.useState(!1),[f,h]=j.useState(!1),[m,p]=j.useState(!1),g=n??m,{isLocalDev:b,isConsoleMode:x}=gm(),y=j.useRef(null);Q(Be=>Be.dashboard.aiScopeTables),Q(Be=>Be.isDashboardEditing);const v=Q(Be=>Be.selectedSheetId),{setDataSource:w}=lr(),{addFrame:C,setSelectedFrameId:S,setIsDashboardEditing:N}=Gt(),_=$m(),{setCurrentAIContext:E,updateSelectedEntities:k,setReasoningEffort:M,setShowReasoning:T}=G1(),{clearQueue:O}=Lm(),{clearFileAttachments:R,getFileAttachments:I}=rT(),L=nT("dashboard"),F=Q(Be=>Be.dashboard.aiContext),V=Ee(Be=>Be.card.dataSource),{assistantProfile:$}=See(),P=Q(Be=>Be.handleOpenAssistantProfile),{sendMessage:U,isLoading:B,messages:A,setMessages:Y,status:z,stop:q,errorMessage:W,clearError:H}=TQe(),G=j.useCallback(Be=>{r==null||r(Be),n===void 0&&p(Be)},[n,r]),K=j.useCallback(()=>{G(!g)},[g,G]);j.useEffect(()=>{if(!g)return;function Be(We){We.key==="Escape"&&G(!1)}return window.addEventListener("keydown",Be),()=>{window.removeEventListener("keydown",Be)}},[g,G]);const[te,Z]=j.useState(""),ee=Be=>{Z(Be.target.value)};function se({sql:Be,data:We,cardTitle:ht,connectionId:qe,cardType:Je,python:Ne,cardConfig:_e,dataSource:Re}){if(console.log("handleAddNewFrame",{sql:Be,data:We,cardTitle:ht,connectionId:qe,cardType:Je,python:Ne,cardConfig:_e,dataSource:Re}),!v)return;const Ve={id:jr(),title:ht||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Je==="horizontalBar"?"y":"x"}},type:Je,sql:Be,python:Ne,dataSource:Re,config:_e,connectionId:qe},it={id:jr(),cards:[Ve],activeCardId:Ve.id};N(!0),C(v,it,"end"),S(it.id)}const ce=Be=>{Be.preventDefault();const We=te.trim();if(!We&&L.length===0)return;const ht=[];We&&ht.push({type:"text",text:We}),L.forEach(qe=>{qe.data&&ht.push({type:"file",mediaType:qe.type,filename:qe.name,url:`data:${qe.type};base64,${qe.data}`})}),U({role:"user",parts:ht}),Z(""),R("dashboard"),le({force:!0})};j.useEffect(()=>{var Be;e&&((Be=y.current)==null||Be.focus())},[e]),_ee({assistantType:"dashboard",status:z,isLoading:B,sendMessage:U});const{hasActiveTools:re}=Tee(A),{visibleMessages:fe,hasMoreMessages:Ce,totalMessageCount:ie,loadMoreMessages:pe,resetMessageWindow:ue}=Mee(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ve,isAtBottom:Se,hasNewMessages:Qe,newMessageCount:Ke,scrollToBottom:le,handleScroll:xe,resetNewMessageCount:Le}=Dee(fe,{threshold:50,behavior:"smooth",isStreaming:B});function me(Be){Ie();const We={role:"user",parts:[{type:"text",text:Be.title+" "+Be.subtitle}]};U(We)}function ke(Be){Ie(),U({role:"user",parts:[{type:"text",text:Be}]})}function $e(Be){Ie(),U({role:"user",parts:[{type:"text",text:Be}]}),le({force:!0})}const He=j.useCallback(async()=>{const Be=JSON.stringify(A??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Be),Fe.success("Conversation copied")}catch(We){console.error("Failed to copy conversation",We),Fe.error("Unable to copy conversation")}},[A]);function Ie(){_.selectedEntities.length===0&&E({selectedEntities:(F==null?void 0:F.selectedEntities)||[]})}const st=(te==null?void 0:te.length)===0&&(A==null?void 0:A.filter(Be=>Be.role==="user").length)===0;function je(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function pt(){return c.jsxs(mm,{children:[c.jsx(pm,{asChild:!0,children:c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(om,{className:"size-3.5"})})}),c.jsxs(Zd,{align:"end",children:[c.jsx(eh,{children:"Options"}),c.jsx(Cd,{}),c.jsx(Qp,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Qp,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Qp,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const It=c.jsxs("div",{"data-role":"dashboard-assistant",className:X("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[je(),P&&c.jsx(oe,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:P,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&pt(),a&&c.jsx(oe,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:He,children:"Copy Conversation"}),c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:K,children:g?c.jsx(iD,{className:"size-4"}):c.jsx(l1,{className:"size-4"})}),c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{Y([]),O("dashboard"),H(),ue()},children:c.jsx(c1,{className:"size-4"})}),c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(yt,{className:"size-4"})})]})]}),c.jsxs(Cl,{"data-role":"dashboard-assistant-scroll-area",ref:ve,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:xe,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[Ce&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:pe,className:"text-xs",children:["Load ",Math.min(5,ie-fe.length)," ","more messages (",ie-fe.length," ","hidden)"]})}),c.jsx(dJ,{showTools:a,showSystemMessage:u,messages:fe,onAddToDashboard:se,onQuickReply:$e,disableQuickReplies:B}),!re&&c.jsx(uJ,{status:z,errorMessage:W})]}),c.jsx(Zo,{orientation:"horizontal"})]}),e&&!Se&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{le({force:!0}),Le()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(Ks,{className:"h-4 w-4"}),Qe&&Ke>0&&c.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:Ke>9?"9+":Ke})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&st&&c.jsx(fJ,{onClick:me,placeholders:KQe}),c.jsx("div",{children:st&&$&&c.jsx(Cee,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:ke})}),c.jsx(Eee,{assistantType:"dashboard",className:"mb-3"}),c.jsx(LI,{ref:y,setInput:Z,stop:q,input:te,handleInputChange:ee,handleSubmit:Be=>{Ie(),ce(Be),le({force:!0})},isLoading:B,status:z,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx($I,{incomingSelectedEntities:(F==null?void 0:F.selectedEntities)||[],open:f,onOpenChange:h,dataSource:V||tC,dialogMode:"aiContext"})]});return g&&s?Pn.createPortal(c.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:c.jsx("div",{className:"flex h-full w-full",children:It})}),s):It}function XQe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Gt(),o=Q(d=>d.dashboard.sheets),a=Q(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=Q(d=>d.isDashboardEditing),u=Q(d=>d.isVisualEditing);j.useEffect(()=>{if(!l||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),Fe.success("Card copied to clipboard"),m.preventDefault()):p&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=_R(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),Fe.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function QQe(e,t){switch(e.interactionMode){case"drillToDetail":JQe(e,t);break;case"drillThrough":eJe(e,t);break;case"drillToURL":tJe(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 JQe(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 eJe(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 tJe(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 nJe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsxs(Ur,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Wr,{children:[c.jsx(qr,{children:i||"Insight Detail"}),c.jsx(Is,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(xZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(wZ,{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 rJe(){const e=Pt(w=>w.interactionStates),t=Pt(w=>w.setInteractionState),n=Pt(w=>w.clearLastInteractionEvent),r=Pt(w=>w.replaceCardWithInsight),s=Pt(w=>w.setPendingDrillThrough),o=Pt(w=>w.pendingDrillThrough),i=Pt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Gt(),{selectDashboard:u}=$b(),d=Q(w=>w.dashboard),f=Q(w=>w.filterValues),{data:h,isLoading:m}=ahe((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=j.useState({open:!1,insightId:""}),b=SZ(p.insightId,{enabled:p.open&&!!p.insightId}),x=j.useRef(new Set),y=j.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:C,contextMode:S})=>{g({open:!0,insightId:w,filters:C,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:S})},replaceCardContent:({cardId:w,insightId:C,filters:S,contextMode:N})=>{r(w,C,S,N)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:C,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:_})=>{const k={sourceCardId:oa,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...Po(),appliedClickFilters:[k],contextMode:C,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:_};t(oa,M)}}),[a,r,f,l,d,s,t]);j.useEffect(()=>{Object.entries(e).forEach(([w,C])=>{if(C!=null&&C.lastInteractionEvent){const S=C.lastInteractionEvent,N=`${w}-${S.interactionMode}-${S.sourceCardId}-${Date.now()}`;if(x.current.has(N))return;x.current.add(N);try{QQe(S,y)}catch(_){console.error("Error executing interaction event:",_)}finally{n(w),setTimeout(()=>{x.current.delete(N)},5e3)}}})},[e,n,y]),j.useEffect(()=>{if(!(!o||!h||m))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,m,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(nJe,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&m&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(Mn,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function sJe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=oJe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function oJe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function iJe(e){return e?`Back to ${e}`:"Back"}function aJe(){var x,y,v,w,C;const e=Pt(S=>S.interactionStates[oa]),t=Q(S=>S.actions.goBackFromDrill),n=Q(S=>S.actions.clearDrillContext),{selectDashboard:r}=$b(),[s,o]=j.useState({x:16,y:16}),[i,a]=j.useState(!1),l=j.useRef({x:0,y:0});j.useEffect(()=>{if(!i)return;const S=_=>{o({x:_.clientX-l.current.x,y:_.clientY-l.current.y})},N=()=>{a(!1)};return document.addEventListener("mousemove",S),document.addEventListener("mouseup",N),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",N)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:w.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((C=e.appliedClickFilters)!=null&&C.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(S){console.error("[DrillBack] Error during back navigation:",S)}},p=()=>{n()},g=S=>{S.target.closest("button")||(a(!0),l.current={x:S.clientX-s.x,y:S.clientY-s.y})};sJe(f);const b=iJe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((S,N)=>{const _=S.field.label||S.field.name,E=String(S.value);return c.jsxs(Oe,{variant:"secondary",className:"pointer-events-none text-xs",children:[_," = ",E]},N)})})]}),c.jsx(oe,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(yt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(oe,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(g8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function Ree(){var Z;const{showAssistant:e,tokenProps:t}=Ge(),{preferences:n,isConsoleMode:r}=gm(),s=((Z=n==null?void 0:n.cardDisplay)==null?void 0:Z.mode)==="print",o=j.useRef(null),i=j.useRef(null),[a,l]=j.useState(!1),u=id(ee=>ee.setFullscreen),d=id(ee=>ee.setPanelOpen),f=id(ee=>ee.setContainer),h=PW("dashboard"),m=OW(),p=FW("dashboard"),g=h.isOpen,b=m==="dashboard",x=Q(ee=>ee.isVisualEditing),y=Q(ee=>ee.themeStyle),v=Q(ee=>{var se;return(se=ee.dashboard)==null?void 0:se.sheets}),w=Q(ee=>ee.isDashboardEditing),C=Q(ee=>ee.selectedSheetId),S=Q(ee=>{var se;return(se=ee.dashboard)==null?void 0:se.id}),N=Q(ee=>ee.isDashboardPanelOpen),_=Q(ee=>ee.actions.setIsDashboardPanelOpen),{getDefaultSheetId:E,setDefaultSheetId:k,clearDefaultSheetId:M}=d8(S),[T,O]=j.useState(null);j1(Ft.DASHBOARD);const{setSelectedSheetId:R,setSheetTitle:I,addSheet:L,setSheets:F}=Gt();XQe(i);const{setActiveAssistantType:V}=G1();j.useEffect(()=>{if(S){const ee=E();O(ee)}},[S,E]),j.useEffect(()=>{g?V("dashboard"):m==="dashboard"&&u(null)},[g,V,m,u]);function $(ee){var se,ce;ee?((se=o.current)==null||se.resize(40),d("dashboard",!0),V("dashboard")):(d("dashboard",!1),u(null),(ce=o.current)==null||ce.resize(0),V(null))}function P(){const ee={id:jr(),title:"New Sheet"};L(ee),R(ee.id)}function U(ee,se){if(!S)return;T===ee?(M(),O(null),Fe.success("Default sheet cleared")):(k(ee),O(ee),Fe.success(`"${se}" set as default sheet`))}function B(ee){ee<1?(d("dashboard",!1),u(null),V(null)):(g||d("dashboard",!0),V("dashboard"))}function A(){return(y==null?void 0:y.canvasTheme)==="muted"||!(y!=null&&y.canvasTheme)?"hsl(var(--semaphor-muted))":(y==null?void 0:y.canvasTheme)==="clear"?"":y==null?void 0:y.canvasTheme}const Y=(ee,se)=>{ee.dataTransfer.setData("tabIndex",se.toString())},z=ee=>{ee.preventDefault()},q=(ee,se)=>{const ce=ee.dataTransfer.getData("tabIndex");if(ce===se.toString())return;const re=Array.from(v||[]),[fe]=re.splice(parseInt(ce),1);re.splice(se,0,fe),F(re)},W=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail;function H(){var ee,se;if(v&&v.length>1||w)return c.jsxs(cs,{role:"tab-list",className:"flex h-11 items-center justify-start gap-2 rounded-none border-b border-b-muted bg-transparent px-2.5 py-3",children:[r&&W&&c.jsx(oe,{variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{_(!N)},className:"h-8 p-2",children:N?c.jsx(_8,{className:"h-4 w-4"}):c.jsx(D8,{className:"h-4 w-4"})}),v==null?void 0:v.map((ce,re)=>{const fe=C===ce.id,Ce=T===ce.id;return c.jsxs(qt,{draggable:!0,onDragStart:ie=>Y(ie,re),onDragOver:z,onDrop:ie=>q(ie,re),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>R(ce.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:ce.id,children:[c.jsx(ib,{enabled:w&&fe,text:ce.title,onSave:ie=>I(ce.id,ie),children:ce.title},ce.id),!w&&fe&&c.jsx("div",{title:Ce?"Clear default sheet":"Set as default sheet",children:c.jsx(dD,{className:X("ml-1 size-3 cursor-pointer transition-all",Ce?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:ie=>{ie.stopPropagation(),U(ce.id,ce.title||"Sheet")}})}),w&&fe&&v.length>1&&c.jsx(yt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},ce.id)}),w&&c.jsx("div",{style:{borderRadius:(se=(ee=y==null?void 0:y.chart)==null?void 0:ee.options)==null?void 0:se.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:P,children:c.jsx(kr,{className:"size-3"})})]})}function G(){return c.jsx("div",{ref:i,style:{},className:"grow",children:v==null?void 0:v.map(ee=>c.jsx(nr,{style:{backgroundColor:A()},className:X("mt-0",{}),value:ee.id,children:c.jsx(C8e,{sheet:ee})},ee.id))})}function K(){var ee;return c.jsxs(As,{"data-role":"dashboard-tabs-container",className:X("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:se=>{R(se)},value:C||((ee=v==null?void 0:v[0])==null?void 0:ee.id),children:[H(),c.jsx(Cl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:G()}),c.jsx(nze,{open:a,setOpen:l})]})}const te=j.useCallback(ee=>{f("dashboard",ee)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(rJe,{}),c.jsx(aJe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(YX,{className:X("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(qE,{children:K()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(tze,{open:g,onTabClick:$,withHandle:!0}),c.jsx(qE,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:B,defaultSize:g?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(ZQe,{open:g,setOpen:$,isFullscreen:b,onFullscreenChange:ee=>u(ee?"dashboard":null),fullscreenContainer:p})})})]})]}),c.jsx("div",{ref:te,className:X("absolute inset-0",!b&&"pointer-events-none")}),e===!0&&!s&&!g&&!x&&c.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:c.jsx(oe,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>$(!0),title:"Open Assistant",children:c.jsx(uD,{className:"h-5 w-5"})})})]})]}):null}function zI({children:e}){return c.jsx(Ca,{style:{height:"100%",width:"100%"},children:c.jsx(qie,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(On,{delayDuration:0,children:e})})})}function Iee({children:e,preferences:t}){const{currentUser:n}=Ts(),r=j.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($9.Provider,{value:r,children:c.jsx(RR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function Aee(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(Da,{FallbackComponent:SS,children:c.jsx(J_,{dashboardProps:e,children:c.jsx(zI,{children:c.jsx(Iee,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(sT,{...e,type:"dashboard",children:c.jsx(Ree,{})})})})})})})}function BI(e){const{tokenProps:t,authToken:n}=Ge(),r=t==null?void 0:t.apiServiceUrl;return cn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return Hn(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 Pee(e,t,n){if(t==="source")return{isValid:!0};const r=Ir(e.dataType);if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function Oee(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=(t==null?void 0:t.comparisonType)==="none";!o&&i||n(r,{groupByColumns:[],comparisonType:"none"})}const Fee=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=BI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=lr(),h=Ee(R=>R.card.type),m=e==null?void 0:e.id,p=j.useCallback(R=>{if(!(e!=null&&e.config))return[];switch(R){case"groupBy":return(e.config.groupByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,dateFormat:I.dateFormat,customFormat:I.customFormat,granularity:I.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,direction:I.direction}));case"source":return[];default:return[]}},[e]),g=j.useCallback((R,I)=>{if(m)switch(R){case"groupBy":{r(m,{groupByColumns:I});break}case"metrics":{r(m,{metricColumns:I});break}case"pivotBy":{r(m,{pivotByColumns:I});break}case"sortBy":{r(m,{sortByColumns:I});break}}},[m,r]),b=j.useCallback((R,I,L)=>{if(!m)return;const V=p(R)[I];if(V)switch(R){case"groupBy":s(m,V.id,{label:L});break;case"metrics":o(m,V.id,{label:L});break;case"pivotBy":i(m,V.id,{label:L});break;case"sortBy":a(m,V.id,{label:L});break}},[m,p,s,o,i,a]),x=j.useCallback((R,I)=>{if(!m)return;const F=p("metrics")[R];F&&o(m,F.id,{aggregate:I,label:hU(F.name,I)})},[m,p,o]),y=j.useCallback((R,I,L)=>{if(!m)return;const V=p("groupBy")[R];if(!V)return;const $={dateFormat:I};I==="custom"&&L?$.customFormat=L:$.customFormat=void 0,s(m,V.id,$)},[m,p,s]),v=j.useCallback((R,I)=>{if(!m)return;const F=p("groupBy")[R];F&&s(m,F.id,{granularity:I})},[m,p,s]),w=j.useCallback((R,I)=>{if(!m)return;const F=p("metrics")[R];F&&o(m,F.id,{aliasTemplate:I})},[m,p,o]),C=j.useCallback((R,I)=>{if(console.log("handleValueAliasesChange",R,I),!m)return;console.log("handleValueAliasesChange",R,I);const F=p("metrics")[R];F&&(console.log("handleValueAliasesChange",I),o(m,F.id,{valueAliases:I}))},[m,p,o]),S=j.useCallback(R=>{if(!m)return;if(p("metrics").length===0){Fe.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(m,{comparisonType:R})},[m,r,p]),N=j.useCallback(R=>{m&&r(m,{showTrendline:R})},[m,r]),_=j.useCallback(R=>{m&&r(m,{trendlineWindow:R})},[m,r]),E=j.useCallback(R=>{m&&r(m,{trendlineGranularity:R})},[m,r]),k=j.useCallback(R=>{m&&r(m,{targetValue:R})},[m,r]),M=j.useCallback(R=>{var U;if(!m)return;const I=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],L=bCe(R,I,{joinPlan:(U=e==null?void 0:e.config)==null?void 0:U.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!L.isValid){L.showError&&uU();return}const F=vCe(R,I,h);if(!F){Fe.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const V=Pee(R,F,h);if(!V.isValid){Fe.error("Invalid Field Type",{description:V.reason,position:"top-center",duration:3e3});return}const $=p(F);if(dU(R,$))return;const P=mU(R,F,$);if(P){const B=[...$,P];g(F,B),F==="metrics"&&Oee(h,e==null?void 0:e.config,r,m,B)}},[m,e==null?void 0:e.config,p,g,t,n,h,r]),T=j.useCallback((R,I)=>{if(!m)return;const F=p(R)[I];if(F){if(R!=="sortBy"){const V=p("sortBy"),$=V.filter(P=>!(P.name===F.name&&P.qualifiedEntityName===F.qualifiedEntityName));$.length!==V.length&&r(m,{sortByColumns:$})}switch(R){case"groupBy":l(m,F.id);break;case"metrics":u(m,F.id);break;case"pivotBy":d(m,F.id);break;case"sortBy":f(m,F.id);break}}},[m,p,l,u,d,f,r]);return{getFieldsForContainer:p,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:C,removeField:T,handleFieldClick:M,handleKpiComparisonTypeChange:S,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:_,handleKpiTrendlineGranularityChange:E,handleKpiTargetValueChange:k,cardType:h}};function Vx(e,t){var ke,$e,He,Ie,st;const{tokenProps:n}=Ge(),r=Qs(),s=Ge().authToken||e,o=Ee(je=>je.selectedConnectionId),i=Ee(je=>je.card),{queryKey:a}=upe(i),l=Ee(je=>je.selectedDatamodelId),u=Ee(je=>je.isDevMode),d=Ee(je=>je.selectedDatabaseName),f=Ee(je=>je.selectedSchemaName),h=Ee(je=>je.selectedTableName),m=Ee(je=>je.actions.setSelectedConnectionId),p=Ee(je=>je.actions.setSelectedDatamodelId),g=Ee(je=>je.actions.setSelectedDatabaseName),b=Ee(je=>je.actions.setSelectedSchemaName),x=Ee(je=>je.actions.setSelectedTableName);Ee(je=>je.actions.setCardSql);const{setQueryConfig:y}=lr();function v(je){var It;return o&&je==="API"?!1:o&&je==="S3"?!0:!(!o||!d||d==="NA"||((It=E==null?void 0:E.capabilities)==null?void 0:It.path.includes("schema"))&&!f)}function w(je){return o&&je?!(je==="API"||je==="S3"):!1}const{refetchConnections:C,connectionsData:S,isConnectionsLoading:N,isConnectionsError:_,selectedConnection:E}=Pi(e),{refetch:k,data:M,isLoading:T,isError:O}=cn({queryKey:["models",o],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),R=E==null?void 0:E.type,I=(E==null?void 0:E.type)==="API"||(E==null?void 0:E.type)==="S3",{data:L,isLoading:F,isFetching:V,isError:$,refetch:P}=cn({queryKey:["databases",o],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(R)}),{data:U,isLoading:B,isFetching:A,isError:Y,refetch:z}=cn({queryKey:["schemas",o,d],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!I&&d!=="NA"}),{data:q,isLoading:W,isFetching:H,isError:G,refetch:K}=cn({queryKey:["tables",o,d,f],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(R)}),{columns:te,isColumnsLoading:Z,isColumnsFetching:ee,isColumnsError:se,refetchColumns:ce}=pU(e);j.useEffect(()=>{(R==="S3"||R==="API")&&(g(""),b(""),p(""),R==="API"&&x("api"))},[R,x,g,b,p]);const re=(E==null?void 0:E.type)==="API"?(ke=E==null?void 0:E.type)==null?void 0:ke.toLowerCase():h||"",fe=I?"":f||"";function Ce(je){x(je),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function ie(je){b(je),x("")}function pe(je){g(je==="none"?"":je),b(""),x(""),je!=="none"&&je!==""&&p("")}function ue(je){m(je)}function ve(je){p(je==="none"?"":je),je!=="none"&&je!==""&&g("")}L&&(($e=L==null?void 0:L.databases)==null?void 0:$e.length)>0,U&&((He=U==null?void 0:U.schemas)==null?void 0:He.length)>0;const Se=S==null?void 0:S.connections.map(je=>({id:je.id,name:je.name,type:je.type})),Qe=(Ie=M==null?void 0:M.datamodels)==null?void 0:Ie.map(je=>({id:je.id,name:je.name})),Ke=L==null?void 0:L.databases.map(je=>({id:je.database_name,name:je.database_name})),le=U==null?void 0:U.schemas.map(je=>({id:je.schema_name,name:je.schema_name})),xe=q==null?void 0:q.tables.map(je=>({id:je.table_name,name:je.table_name})),Le=(st=M==null?void 0:M.datamodels.find(je=>je.id===l))==null?void 0:st.name,me=nv({schemaName:fe,tableName:re,modelName:Le,connectionType:R,databaseName:d||""});return{connectionItems:Se,selectedConnectionId:o,selectedConnection:E,isConnectionsLoading:N,isConnectionsError:_,modelItems:Qe,selectedDatamodelId:l,selectedDatamodelName:Le,isModelsLoading:T,isModelsError:O,selectedDatabaseName:d,databaseItems:Ke,isDatabasesLoadingOrFetching:F||V,isDatabaseError:$,schemaItems:le,selectedSchemaName:f,isSchemaLoadingOrFetching:B||A,isSchemaError:Y,tableItems:xe,selectedTableName:h,isTableLoadingOrFetching:W||H,isTableError:G,columns:te,isColumnsLoadingOrFetching:Z||ee,isColumnsError:se,isNonDbConnection:I,connectionType:R,tableName:re,formattedTableName:me,schemaName:fe,refetchConnections:C,refetchModels:k,refetchDatabases:P,refetchSchemas:z,refetchTables:K,refetchColumns:ce,handleConnectionChange:ue,handleDatamodelChange:ve,handleDatabaseChange:pe,handleSchemaChange:ie,handleTableChange:Ce}}function wy(e){return`${e}-${jr()}`}function TL(e,t){const n=Yo(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function lJe(e,t){const n=Yo(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function VI(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 $ee(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Lee(){const e=Ee(S=>S.sqlGen),t=Ee(S=>S.isDevMode),n=Ee(S=>S.card.dataSource),r=Ee(S=>{var N,_;return(_=(N=S.card)==null?void 0:N.queryConfig)==null?void 0:_.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=VI(n),a=$ee(n),l=Ee(S=>S.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=lr(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Vx(),y=S=>({column_name:S.name,data_type:S.dataType,label:S.label,description:S.description});return{handleDevModeFieldClick:S=>{var _;if(!t)return;const N=y(S);if(t&&a&&s){const E=O_(N,e);m(E);const k=(_=b==null?void 0:b.find(T=>T.id===l))==null?void 0:_.name,M=P_(E,fi(o||""),fi(s),k||"",g,i||"");M&&(f(M),h(!0))}else if(!t){if(Ab(N.data_type))if(r&&r.length>0){const E={...N,role:"groupby",id:wy(N.column_name),name:N.column_name,type:N.data_type};d(E)}else{const E={...N,role:"metric",id:wy(N.column_name),name:N.column_name,label:TL(N.column_name,"COUNT"),type:N.data_type,aggregate:"COUNT"};u(E)}if(Si(N.data_type)){const E={...N,role:"groupby",id:wy(N.column_name),name:N.column_name,type:N.data_type,label:lJe(N.column_name,"month"),granularity:"month"};d(E)}if(wi(N.data_type)){const E={...N,role:"metric",id:wy(N.column_name),name:N.column_name,label:TL(N.column_name,"SUM"),type:N.data_type,aggregate:"SUM"};u(E)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=nv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});p(!1);const N=g==="MSSQL"?`SELECT top 10 * FROM ${S}`:`SELECT * FROM ${S} LIMIT 10`;f(N),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=nv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${S}`),h(!0)},isNumberField:S=>wi(S.dataType)}}function cJe({columnName:e,database:t,schemaName:n,tableName:r,connectionType:s,datamodelId:o,modelName:i,field:a}){const l=fi(e),u=fi(t||""),d=fi(n||""),f=fi(r);let h=Jw({schemaName:d,tableName:f,connectionType:s,databaseName:u}),m=`${h}.${l}`;return o&&o!=="none"&&i&&(m=`${Eg}.${i}.${l}`,h=`${Eg}.${i}`),a!=null&&a.qualifiedFieldName&&(m=a.qualifiedFieldName,h=a.qualifiedFieldName.split(".").slice(0,-1).join(".")),{qualifiedColumnName:m,qualifiedTableName:h,formattedColumnName:l,formattedTableName:f,formattedDatabase:u,formattedSchemaName:d}}function zee(){const e=Ee(p=>p.selectedConnectionId),t=Ee(p=>p.selectedDatamodelId),n=Ee(p=>p.selectedDatabaseName),r=Ee(p=>p.selectedSchemaName),s=Ee(p=>p.selectedTableName),o=Q(p=>p.dashboard.filters)||[],i=Q(p=>p.selectedSheetId),a=Q(p=>p.actions.addFilter),l=Q(p=>p.actions.removeFilter),{removeFilterValues:u}=Gt(),{modelItems:d,tableName:f,connectionType:h}=Vx();function m(p,g="sheet",b){var _;const x=(_=d==null?void 0:d.find(E=>E.id===t))==null?void 0:_.name,{qualifiedColumnName:y,qualifiedTableName:v,formattedColumnName:w,formattedTableName:C,formattedDatabase:S}=cJe({columnName:p.column_name,database:n,schemaName:r,tableName:f,connectionType:h,datamodelId:t,modelName:x,field:b});let N;if(g==="sheet"&&i?N=Kke(o,y,C,n||"",S,i):N=o==null?void 0:o.find(E=>E.column===y&&E.table===C&&(E.database===S||E.database===n)),N)u(N.id),l(N.id);else{const E=jr(),k=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:E,column:y,title:p.label||p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:k,sql:NE(p.data_type,v,w)}),E):(a({id:E,location:g,column:y,title:p.label||p.column_name,dataType:p.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:k,sql:NE(p.data_type,v,(b==null?void 0:b.qualifiedFieldName)||w)}),E)}}return{assignFilter:m}}function uJe({column:e}){const[t,n]=j.useState(!1),r=Ee(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=VI(r),a=Ee(x=>x.selectedDatamodelId),l=Ee(x=>x.sqlGen),{modelItems:u,connectionType:d}=Vx(),f=Ee(x=>x.actions.setSqlGen),h=Ee(x=>x.actions.setCardSql),m=Ee(x=>x.actions.setRunSql),p=$ee(r);function g(x,y){var S;if(!p||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=O_(x,l,y),w=(S=u==null?void 0:u.find(N=>N.id===a))==null?void 0:S.name;f(v);const C=P_(v,fi(o||""),fi(s),w||"",d,i||"");C&&(h(C),m(!0)),n(!1)}function b(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>g(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>g(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>g(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>g(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>g(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return p?c.jsxs(Pm,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(Om,{asChild:!0,children:c.jsx(om,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(rf,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function dJe({field:e,fieldState:t}){return c.jsxs("div",{className:"w-64 bg-background p-0",children:[c.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[c.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),c.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&c.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&c.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:c.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),c.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:c.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function fJe({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s}){const o=Ee(q=>q.isDevMode),i=t==="filter"||t==="inline-filter",a=o||i||(n==null?void 0:n.state)==="unreachable"&&!i,l=Q(q=>q.dashboard.filters),u=Q(q=>q.selectedSheetId),d=Q(q=>q.actions.removeFilter),{removeFilterValues:f}=Gt(),{assignFilter:h}=zee(),m=t==="filter"?Jc(l,u):l,p=t==="filter"?m==null?void 0:m.find(q=>{var W;return q.title===e.name||((W=q.column)==null?void 0:W.includes(e.name))}):void 0,g=!!p,b=t==="inline-filter"&&(s==null?void 0:s.some(q=>q.column===e.qualifiedFieldName||q.column===e.name)),x=g||b,y=p&&i?l==null?void 0:l.find(q=>q.id===p.id):void 0,v=y&&(y.applyToSheetIds&&y.applyToSheetIds.length>1||y.excludeSheetIds&&y.excludeSheetIds.length>0||!y.applyToSheetIds&&!y.excludeSheetIds&&!y.sheetId);i&&x&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:x,activeFilterOnSheet:p?{id:p.id,title:p.title,column:p.column,applyToSheetIds:p.applyToSheetIds,excludeSheetIds:p.excludeSheetIds}:null,activeFilterForField:y?{id:y.id,title:y.title,column:y.column,applyToSheetIds:y.applyToSheetIds,excludeSheetIds:y.excludeSheetIds}:null,isMultiSheetFilter:v,selectedSheetId:u});const[w,C]=j.useState(!1),[S,N]=j.useState(null),{attributes:_,listeners:E,setNodeRef:k,transform:M,transition:T,isDragging:O}=PS({id:e.id,disabled:a}),[R,I]=j.useState(!1),L=Ee(q=>q.card),{handleFieldClick:F}=Fee(L),{handleDevModeFieldClick:V,isNumberField:$}=Lee(),P=()=>{y&&(console.log("[SourceField] Removing multi-sheet filter:",y.id),f(y.id),d(y.id)),N(null),C(!1)},U=()=>{if(t==="inline-filter"&&r){r(e);return}if(t==="filter"){const q={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};x&&v?(N({column:q,field:e}),C(!0)):h(q,"sheet",e)}else o?V(e):F(e)},B={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},A={transform:Mi.Transform.toString(M),transition:T},z=(()=>{if(!n||i)return{};const W={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...W},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...W},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...W}}[n.state]||W})();return c.jsxs("div",{ref:k,style:A,...a?{}:_,...a?{}:E,className:X("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",O&&"scale-95 opacity-50",!O&&"border",z.borderColor||"border-transparent",z.bgColor||"",z.hoverBorderColor,z.hoverBgColor||"hover:bg-muted",z.opacity,z.cursor,g&&"border-accent-foreground/20 bg-accent",b&&"border-primary/20 bg-primary/10",{"cursor-pointer":o||i,"cursor-grab active:cursor-grabbing":!a&&!o&&!i}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:U,children:[lb(e.dataType),c.jsx(On,{children:c.jsxs(un,{children:[c.jsx(dn,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${R?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(pn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(dJe,{field:e,fieldState:n})})]})}),o&&!i&&$(e)&&c.jsx("div",{onClick:q=>q.stopPropagation(),children:c.jsx(uJe,{column:B})})]}),R&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(vo,{className:"",children:c.jsxs(ji,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Y8,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.label||e.name})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Zae,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Oe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx(Gb,{open:w,onOpenChange:C,children:c.jsxs(bm,{children:[c.jsxs(xm,{children:[c.jsx(vm,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(wm,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(ym,{children:[c.jsx(Cm,{children:"Cancel"}),c.jsx(Sm,{onClick:P,children:"Remove Filter"})]})]})})]})}const hJe="SEMAPHOR_CALCULATED_FIELD",mJe=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","Week of MMM DD, YYYY","Week of MMMM DD, YYYY","YYYY-WW","MMM YYYY","MMMM YYYY","YYYY-MM","MM/YYYY","YYYY MMM","Q1 YYYY","YYYY Q1","1st Quarter YYYY","YYYY-Q1","Quarter 1, YYYY","YYYY","YY","custom"];function Bee(e){return!!e.expression}function pJe(e){return!!e.expression}function gJe(e){return!!e.expression}var Vee=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(Vee||{}),_l="Accordion",bJe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[HI,xJe,yJe]=d1(_l),[oC]=_r(_l,[yJe,MZ]),UI=MZ(),Hee=j.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(HI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(CJe,{...o,ref:t}):c.jsx(SJe,{...s,ref:t})})});Hee.displayName=_l;var[Uee,vJe]=oC(_l),[Wee,wJe]=oC(_l,{collapsible:!1}),SJe=j.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=zr({prop:n,defaultProp:r,onChange:s});return c.jsx(Uee,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:j.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(Wee,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(qee,{...i,ref:t})})})}),CJe=j.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i=[],a]=zr({prop:n,defaultProp:r,onChange:s}),l=j.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=j.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(Uee,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(Wee,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(qee,{...o,ref:t})})})}),[NJe,iC]=oC(_l),qee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=j.useRef(null),l=bt(a,t),u=xJe(n),f=qd(s)==="ltr",h=De(e.onKeyDown,m=>{var _;if(!bJe.includes(m.key))return;const p=m.target,g=u().filter(E=>{var k;return!((k=E.ref.current)!=null&&k.disabled)}),b=g.findIndex(E=>E.ref.current===p),x=g.length;if(b===-1)return;m.preventDefault();let y=b;const v=0,w=x-1,C=()=>{y=b+1,y>w&&(y=v)},S=()=>{y=b-1,y<v&&(y=w)};switch(m.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?C():S());break;case"ArrowDown":o==="vertical"&&C();break;case"ArrowLeft":o==="horizontal"&&(f?S():C());break;case"ArrowUp":o==="vertical"&&S();break}const N=y%x;(_=g[N].ref.current)==null||_.focus()});return c.jsx(NJe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(HI.Slot,{scope:n,children:c.jsx(Ue.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Uw="AccordionItem",[jJe,WI]=oC(Uw),Yee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=iC(Uw,n),i=vJe(Uw,n),a=UI(n),l=or(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(jJe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(IZ,{"data-orientation":o.orientation,"data-state":Jee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Yee.displayName=Uw;var Gee="AccordionHeader",Kee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=iC(_l,n),o=WI(Gee,n);return c.jsx(Ue.h3,{"data-orientation":s.orientation,"data-state":Jee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Kee.displayName=Gee;var g_="AccordionTrigger",Zee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=iC(_l,n),o=WI(g_,n),i=wJe(g_,n),a=UI(n);return c.jsx(HI.ItemSlot,{scope:n,children:c.jsx(E$e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Zee.displayName=g_;var Xee="AccordionContent",Qee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=iC(_l,n),o=WI(Xee,n),i=UI(n);return c.jsx(_$e,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});Qee.displayName=Xee;function Jee(e){return e?"open":"closed"}var kJe=Hee,EJe=Yee,_Je=Kee,ete=Zee,tte=Qee;const nte=kJe,qI=D.forwardRef(({className:e,...t},n)=>c.jsx(EJe,{ref:n,className:X("border-b",e),...t}));qI.displayName="AccordionItem";const YI=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(_Je,{className:"flex",children:c.jsxs(ete,{ref:r,className:X("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,c.jsx(Ks,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));YI.displayName=ete.displayName;const GI=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(tte,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:X("pb-4 pt-0",e),children:t})}));GI.displayName=tte.displayName;function rte({context:e="editor",onFieldSelect:t,inlineFilters:n}={}){var I,L,F,V;const[r,s]=j.useState(""),[o,i]=j.useState("all");Ee($=>$.isDevMode);const a=Ee($=>$.card.dataSource),l=Ee($=>$.card.config),u=Ee($=>$.card),{autoJoinMetadata:d}=pa(u),{columns:f=[],columnGroups:h=[],isLoading:m,error:p}=zM(),g=(a==null?void 0:a.mode)==="semanticDomain"?a.semanticDomainId:void 0,{data:b}=BI(g),x=[...(l==null?void 0:l.groupByColumns)||[],...(l==null?void 0:l.metricColumns)||[]];(L=(I=l==null?void 0:l.joinPlan)==null?void 0:I.baseEntity)==null||L.name,(V=(F=d==null?void 0:d.resolvedJoinPlan)==null?void 0:F.baseEntity)==null||V.name,Lee();const y=f.filter($=>$.name.toLowerCase().includes(r.toLowerCase())||$.dataType.toLowerCase().includes(r.toLowerCase())||$.label&&$.label.toLowerCase().includes(r.toLowerCase())||$.qualifiedEntityName&&$.qualifiedEntityName.toLowerCase().includes(r.toLowerCase())),v=$=>{if($.role==="metric"&&Bee($)||$.role==="groupby"&&$.expression)return"calculated";if($.dataType==="number"||$.dataType==="integer"||$.dataType==="float"||$.dataType==="decimal"||$.dataType==="currency")return"metrics";const P=Ir($.dataType);return["date","string","boolean"].includes(P)?"dimensions":P==="number"?"metrics":"dimensions"},C=(o==="all"?y:y.filter($=>v($)===o)).reduce(($,P)=>{const U=P.qualifiedEntityName||"Other Fields";return $[U]||($[U]={label:q_(P.entityName),fields:[]}),$[U].fields.push(P),$},{}),N=Object.keys(C),_=y.filter($=>v($)==="dimensions").length,E=y.filter($=>v($)==="metrics").length,k=y.filter($=>v($)==="calculated").length,M=y.length>0&&e!=="inline-filter",T=e==="inline-filter"?"w-full":"w-[290px]";if(m)return c.jsx("div",{className:X("flex h-full flex-col items-center justify-center py-8",T),children:c.jsx(Rc,{size:"md",color:"muted","aria-label":"Loading data"})});if(p)return c.jsxs("div",{className:X("flex h-full flex-col items-center justify-center py-8",T),children:[c.jsx(al,{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:p.message||"Failed to load column data"})]});if(!a||!a.selectedEntities||a.selectedEntities.length===0)return c.jsxs("div",{className:X("flex flex-col items-center justify-center py-8 text-center",T),children:[c.jsx(al,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:e==="filter"||e==="inline-filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]});const O=e==="inline-filter"?"px-3 pb-3":"px-6 pb-6",R=e==="inline-filter"?"overflow-hidden":"";return c.jsxs("div",{className:X("mt-2 flex h-full w-full grow flex-col gap-2",O,R),children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[f.length>0&&c.jsxs("div",{className:"relative",children:[c.jsx(va,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(Nn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:r,onChange:$=>s($.target.value)}),r&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>s(""),type:"button",children:c.jsx(yt,{className:"size-3.5"})})]}),M&&c.jsx(As,{defaultValue:"all",value:o,onValueChange:$=>i($),className:"mb-4",children:c.jsxs(cs,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(qt,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:y.length})]}),c.jsxs(qt,{value:"dimensions",className:"text-xs",children:[c.jsx(a1,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:_})]}),c.jsxs(qt,{value:"metrics",className:"text-xs",children:[c.jsx(sm,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:E})]}),c.jsxs(qt,{value:"calculated",className:"text-xs",children:[c.jsx(eD,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:k})]})]})})]}),c.jsxs(Cl,{className:"min-h-0 overflow-auto",children:[c.jsx(nte,{type:"multiple",defaultValue:N,className:"space-y-2",children:Object.entries(C).map(([$,P])=>{const U=h.find(B=>B.entityName===$)||{entityName:$,label:P.label};return c.jsxs(qI,{value:$,className:"border-none",children:[c.jsx(YI,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:U.label||U.entityName,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:U.label||U.entityName}),c.jsx(Oe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:P.fields.length})]})}),c.jsx(GI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:P.fields.map(B=>{const A=BM(B,{joinabilityMap:(b==null?void 0:b.joinabilityMap)||null,selectedFields:x,cardConfig:l,autoJoinMetadata:d});return c.jsx(fJe,{field:B,context:e,fieldState:A,onFieldSelect:t,inlineFilters:e==="inline-filter"?n:void 0},B.id)})})})]},$)})}),Object.keys(C).length===0&&f.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:e==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(C).length===0&&f.length>0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(Zo,{orientation:"horizontal"}),c.jsx(Zo,{orientation:"vertical"})]})]})}function ste({context:e="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(rte,{context:e})," "]})}function ote(){const e=Ee(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=lr();j.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=VI(e),d=(m=e.selectedEntities)==null?void 0:m[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function DJe(){ote();const e=Q(l=>l.selectedSheetId),t=Q(l=>l.selectedFrameId),n=Q(l=>l.dashboard),r=Q(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Gt(),{setCard:o}=lr(),i=Ee(l=>l.card.dataSource);return j.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(m=>m.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function MJe(){const e=Q(n=>n.actions.setShowFilters),{hasEntities:t}=DJe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(de,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsx(oe,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(NZ,{})})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(al,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow overflow-y-auto",children:c.jsx(IS,{collisionDetection:DS,children:c.jsx(AS,{items:[],strategy:YR,children:c.jsx(ste,{context:"filter"})})})})]})}function TJe(){const e=Q(r=>r.dashboard.filters),t=Q(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:X("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(AR,{filter:r}),c.jsx(Cx,{filter:r})]},r.id))}):null}function RJe(){const e=Q(r=>r.showFilters),t=Q(r=>r.isVisualEditing),n=Q(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:X("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[c.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&c.jsx(TJe,{}),c.jsx(Ree,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(MJe,{})})]})}const IJe=j.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-Dxx6-zR2.js"))),AJe=j.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-AgjWs5LG.js"))),PJe=j.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-DbfqDpJH.js"))),OJe=j.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-CU-aO9tG.js")).then(e=>({default:e.ResourceManagementPanel})));function FJe({showControls:e=!1,showFooter:t=!0,...n}){const r=Q(l=>l.isDashboardPanelOpen),s=Q(l=>l.isVisualEditing),o=Q(l=>l.showDashboardJSON),i=Q(l=>l.actions.setIsDashboardPanelOpen),{preferences:a}=n;return c.jsx(Da,{FallbackComponent:SS,children:c.jsxs(J_,{dashboardProps:n,children:[c.jsx(Cfe,{}),c.jsx(zI,{children:c.jsxs(Iee,{preferences:a,children:[o&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(PJe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(IJe,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(OJe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(sT,{...n,type:"dashboard",children:[s&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(AJe,{})}),c.jsx(RJe,{})]})})]})]})]})})]})})}var $Je=Object.defineProperty,LJe=(e,t,n)=>t in e?$Je(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Sy=(e,t,n)=>LJe(e,typeof t!="symbol"?t+"":t,n);const zJe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},BJe={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}},VJe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},HJe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},UJe={stringify:e=>e,parse:e=>e},n2={string:UJe,number:HJe,boolean:zJe,function:BJe,json:VJe};function WJe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const Cy=Symbol.for("r2wc.render"),Ny=Symbol.for("r2wc.connected"),yu=Symbol.for("r2wc.context"),Aa=Symbol.for("r2wc.props");function qJe(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const m of i){l[m]=Array.isArray(t.props)?"string":t.props[m];const p=WJe(m);d[m]=p,f[p]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),Sy(this,o,!0),Sy(this,s),Sy(this,r,{}),Sy(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Aa].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=l[p],y=x?n2[x]:null;y!=null&&y.parse&&b&&(this[Aa][p]=y.parse(b,g,this))}for(const p of a)this[Aa][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[Ny]=!0,this[Cy]()}disconnectedCallback(){this[Ny]=!1,this[yu]&&n.unmount(this[yu]),delete this[yu]}attributeChangedCallback(p,g,b){const x=f[p],y=l[x],v=y?n2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[Aa][x]=v.parse(b,p,this),this[Cy]())}[(o=Ny,s=yu,r=Aa,Cy)](){this[Ny]&&(this[yu]?n.update(this[yu],this[Aa]):this[yu]=n.mount(this.container,e,this[Aa]))}}for(const m of i){const p=d[m],g=l[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[Aa][m]},set(b){this[Aa][m]=b;const x=g?n2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[Cy]()}})}return h}function YJe(e,t,n){const r=p2(e),s=j.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function GJe({root:e,ReactComponent:t},n){const r=j.createElement(t,n);e.render(r)}function KJe({root:e}){e.unmount()}function ZJe(e,t={}){return qJe(e,t,{mount:YJe,update:GJe,unmount:KJe})}const XJe={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},QJe=ZJe(Aee,{props:XJe});function JJe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function RL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function IL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?RL(Object(n),!0).forEach(function(r){JJe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):RL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function eet(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o<r.length;o++)s=r[o],!(t.indexOf(s)>=0)&&(n[s]=e[s]);return n}function tet(e,t){if(e==null)return{};var n=eet(e,t),r,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(s=0;s<o.length;s++)r=o[s],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function net(e,t){return ret(e)||set(e,t)||oet(e,t)||iet()}function ret(e){if(Array.isArray(e))return e}function set(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var n=[],r=!0,s=!1,o=void 0;try{for(var i=e[Symbol.iterator](),a;!(r=(a=i.next()).done)&&(n.push(a.value),!(t&&n.length===t));r=!0);}catch(l){s=!0,o=l}finally{try{!r&&i.return!=null&&i.return()}finally{if(s)throw o}}return n}}function oet(e,t){if(e){if(typeof e=="string")return AL(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return AL(e,t)}}function AL(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function iet(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1071
+ `)}})}});var YXe=zZe(()=>aee(Ar([qn({type:mt("text-start"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("text-delta"),id:ze(),delta:ze(),providerMetadata:ur.optional()}),qn({type:mt("text-end"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("error"),errorText:ze()}),qn({type:mt("tool-input-start"),toolCallId:ze(),toolName:ze(),providerExecuted:Cr().optional(),dynamic:Cr().optional()}),qn({type:mt("tool-input-delta"),toolCallId:ze(),inputTextDelta:ze()}),qn({type:mt("tool-input-available"),toolCallId:ze(),toolName:ze(),input:fo(),providerExecuted:Cr().optional(),providerMetadata:ur.optional(),dynamic:Cr().optional()}),qn({type:mt("tool-input-error"),toolCallId:ze(),toolName:ze(),input:fo(),providerExecuted:Cr().optional(),providerMetadata:ur.optional(),dynamic:Cr().optional(),errorText:ze()}),qn({type:mt("tool-output-available"),toolCallId:ze(),output:fo(),providerExecuted:Cr().optional(),dynamic:Cr().optional(),preliminary:Cr().optional()}),qn({type:mt("tool-output-error"),toolCallId:ze(),errorText:ze(),providerExecuted:Cr().optional(),dynamic:Cr().optional()}),qn({type:mt("reasoning-start"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("reasoning-delta"),id:ze(),delta:ze(),providerMetadata:ur.optional()}),qn({type:mt("reasoning-end"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("source-url"),sourceId:ze(),url:ze(),title:ze().optional(),providerMetadata:ur.optional()}),qn({type:mt("source-document"),sourceId:ze(),mediaType:ze(),title:ze(),filename:ze().optional(),providerMetadata:ur.optional()}),qn({type:mt("file"),url:ze(),mediaType:ze(),providerMetadata:ur.optional()}),qn({type:nee(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:ze().optional(),data:fo(),transient:Cr().optional()}),qn({type:mt("start-step")}),qn({type:mt("finish-step")}),qn({type:mt("start"),messageId:ze().optional(),messageMetadata:fo().optional()}),qn({type:mt("finish"),messageMetadata:fo().optional()}),qn({type:mt("abort")}),qn({type:mt("message-metadata"),messageMetadata:fo()})])));function GXe(e){return e.type.startsWith("data-")}function pee(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=pee(o,s):n[r]=s}return n}function KXe(e){const t=["ROOT"];let n=-1,r=null;function s(l,u,d){switch(l){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":s(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function gee(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Bw({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Bw({text:KXe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Ky(e){return e.type.startsWith("tool-")}function ZXe(e){return e.type==="dynamic-tool"}function f_(e){return Ky(e)||ZXe(e)}function _L(e){return e.type.split("-").slice(1).join("-")}function XXe({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function QXe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,m,p;function g(w){const S=u.message.parts.filter(Ky).find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function b(w){const S=u.message.parts.filter(N=>N.type==="dynamic-tool").find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function x(w){var C;const S=u.message.parts.find(E=>Ky(E)&&E.toolCallId===w.toolCallId),N=w,_=S;S!=null?(S.state=w.state,_.input=N.input,_.output=N.output,_.errorText=N.errorText,_.rawInput=N.rawInput,_.preliminary=N.preliminary,_.providerExecuted=(C=N.providerExecuted)!=null?C:S.providerExecuted,N.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=N.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:N.input,output:N.output,rawInput:N.rawInput,errorText:N.errorText,providerExecuted:N.providerExecuted,preliminary:N.preliminary,...N.providerMetadata!=null?{callProviderMetadata:N.providerMetadata}:{}})}function y(w){var C;const S=u.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===w.toolCallId),N=w,_=S;S!=null?(S.state=w.state,_.toolName=w.toolName,_.input=N.input,_.output=N.output,_.errorText=N.errorText,_.rawInput=(C=N.rawInput)!=null?C:_.rawInput,_.preliminary=N.preliminary,N.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=N.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:N.input,output:N.output,errorText:N.errorText,preliminary:N.preliminary,...N.providerMetadata!=null?{callProviderMetadata:N.providerMetadata}:{}})}async function v(w){if(w!=null){const C=u.message.metadata!=null?pee(u.message.metadata,w):w;t!=null&&await CL({value:C,schema:t}),u.message.metadata=C}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,w.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const w=u.message.parts.filter(Ky);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:C}=await gee(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:C}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:C}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:_L(w),state:"output-available",input:w.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:_L(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:a.errorText})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(GXe(a)){(n==null?void 0:n[a.type])!=null&&await CL({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const C=w.id!=null?u.message.parts.find(S=>w.type===S.type&&w.id===S.id):void 0;C!=null?C.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function JXe({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}Bx({prefix:"aitxt",size:24});Bx({prefix:"aiobj",size:24});var eQe=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(r){n(r)}}),this.processQueue()})}};Bx({prefix:"aiobj",size:24});var tQe={};FXe(tQe,{object:()=>rQe,text:()=>nQe});var nQe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),rQe=({schema:e})=>{const t=PXe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await gee(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await Bw({text:n});if(!s.success)throw new kL({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await AI({value:s.value,schema:t});if(!o.success)throw new kL({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}},sQe=Yf({name:ze(),version:ze()}),OI=Yf({_meta:xr(Wt({}).loose())}),Cb=OI,oQe=Wt({method:ze(),params:xr(OI)}),iQe=Yf({experimental:xr(Wt({}).loose()),logging:xr(Wt({}).loose()),prompts:xr(Yf({listChanged:xr(Cr())})),resources:xr(Yf({subscribe:xr(Cr()),listChanged:xr(Cr())})),tools:xr(Yf({listChanged:xr(Cr())}))});Cb.extend({protocolVersion:ze(),capabilities:iQe,serverInfo:sQe,instructions:xr(ze())});var aQe=Cb.extend({nextCursor:xr(ze())}),lQe=Wt({name:ze(),description:xr(ze()),inputSchema:Wt({type:mt("object"),properties:xr(Wt({}).loose())}).loose()}).loose();aQe.extend({tools:ou(lQe)});var cQe=Wt({type:mt("text"),text:ze()}).loose(),uQe=Wt({type:mt("image"),data:ZJ(),mimeType:ze()}).loose(),bee=Wt({uri:ze(),mimeType:xr(ze())}).loose(),dQe=bee.extend({text:ze()}),fQe=bee.extend({blob:ZJ()}),hQe=Wt({type:mt("resource"),resource:Ar([dQe,fQe])}).loose();Cb.extend({content:ou(Ar([cQe,uQe,hQe])),isError:Cr().default(!1).optional()}).or(Cb.extend({toolResult:fo()}));var sC="2.0",mQe=Wt({jsonrpc:mt(sC),id:Ar([ze(),wb().int()])}).merge(oQe).strict(),pQe=Wt({jsonrpc:mt(sC),id:Ar([ze(),wb().int()]),result:Cb}).strict(),gQe=Wt({jsonrpc:mt(sC),id:Ar([ze(),wb().int()]),error:Wt({code:wb().int(),message:ze(),data:xr(fo())})}).strict(),bQe=Wt({jsonrpc:mt(sC)}).merge(Wt({method:ze(),params:xr(OI)})).strict();Ar([mQe,bQe,pQe,gQe]);async function xQe(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var yQe=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await Mf(this.body),l=await Mf(this.headers),u=await Mf(this.credentials),d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...l,...t.headers},credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(r=d==null?void 0:d.api)!=null?r:this.api,h=(d==null?void 0:d.headers)!==void 0?d.headers:{...l,...t.headers},m=(d==null?void 0:d.body)!==void 0?d.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},p=(s=d==null?void 0:d.credentials)!=null?s:u,b=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:SL({"Content-Type":"application/json",...h},`ai-sdk/${EL}`,wL()),body:JSON.stringify(m),credentials:p,signal:e});if(!b.ok)throw new Error((i=await b.text())!=null?i:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await Mf(this.body),a=await Mf(this.headers),l=await Mf(this.credentials),u=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:{...a,...e.headers},credentials:l,requestMetadata:e.metadata})),d=(n=u==null?void 0:u.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=(u==null?void 0:u.headers)!==void 0?u.headers:{...a,...e.headers},h=(r=u==null?void 0:u.credentials)!=null?r:l,p=await((s=this.fetch)!=null?s:globalThis.fetch)(d,{method:"GET",headers:SL(f,`ai-sdk/${EL}`,wL()),credentials:h});if(p.status===204)return null;if(!p.ok)throw new Error((o=await p.text())!=null?o:"Failed to fetch the chat response.");if(!p.body)throw new Error("The response body is empty.");return this.processResponseStream(p.body)}},FI=class extends yQe{constructor(e={}){super(e)}processResponseStream(e){return HZe({stream:e,schema:YXe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},vQe=class{constructor({generateId:e=TZe,id:t=e(),transport:n=new FI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new eQe,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await xQe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(p=>p.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>f_(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>f_(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=l,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let u=!1,d=!1,f=!1;try{const h={state:XXe({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};h.abortController.signal.addEventListener("abort",()=>{u=!0}),this.activeResponse=h;let m;if(e==="resume-stream"){const g=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(g==null){this.setStatus({status:"ready"});return}m=g}else m=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:h.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const p=g=>this.jobExecutor.run(()=>g({state:h.state,write:()=>{var b;this.setStatus({status:"streaming"}),h.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,h.state.message):this.state.pushMessage(h.state.message)}}));await JXe({stream:QXe({stream:m,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:p,onError:g=>{throw g}}),onError:g=>{throw g}}),this.setStatus({status:"ready"})}catch(h){if(u||h.name==="AbortError")return u=!0,this.setStatus({status:"ready"}),null;f=!0,h instanceof TypeError&&(h.message.toLowerCase().includes("fetch")||h.message.toLowerCase().includes("network"))&&(d=!0),this.onError&&h instanceof Error&&this.onError(h),this.setStatus({status:"error",error:h})}finally{try{(o=this.onFinish)==null||o.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:u,isDisconnect:d,isError:f})}catch(h){console.error(h)}this.activeResponse=void 0}(i=this.sendAutomaticallyWhen)!=null&&i.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(a=this.lastMessage)==null?void 0:a.id,metadata:t,headers:n,body:r})}};function wQe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(f_);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function SQe(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},l)}}var CQe=SQe;const NQe=Vc(CQe);var xee=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},In=(e,t,n)=>(xee(e,t,"read from private field"),n?n.call(e):t.get(e)),Vi=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Ll=(e,t,n,r)=>(xee(e,t,"write to private field"),t.set(e,n),n);function jQe(e,t){return t!=null?NQe(e,t):e}var ko,Zy,Xy,Yp,Gp,Kp,Of,h_,m_,kQe=class{constructor(e=[]){Vi(this,ko,void 0),Vi(this,Zy,"ready"),Vi(this,Xy,void 0),Vi(this,Yp,new Set),Vi(this,Gp,new Set),Vi(this,Kp,new Set),this.pushMessage=t=>{Ll(this,ko,In(this,ko).concat(t)),In(this,Of).call(this)},this.popMessage=()=>{Ll(this,ko,In(this,ko).slice(0,-1)),In(this,Of).call(this)},this.replaceMessage=(t,n)=>{Ll(this,ko,[...In(this,ko).slice(0,t),this.snapshot(n),...In(this,ko).slice(t+1)]),In(this,Of).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?jQe(t,n):t;return In(this,Yp).add(r),()=>{In(this,Yp).delete(r)}},this["~registerStatusCallback"]=t=>(In(this,Gp).add(t),()=>{In(this,Gp).delete(t)}),this["~registerErrorCallback"]=t=>(In(this,Kp).add(t),()=>{In(this,Kp).delete(t)}),Vi(this,Of,()=>{In(this,Yp).forEach(t=>t())}),Vi(this,h_,()=>{In(this,Gp).forEach(t=>t())}),Vi(this,m_,()=>{In(this,Kp).forEach(t=>t())}),Ll(this,ko,e)}get status(){return In(this,Zy)}set status(e){Ll(this,Zy,e),In(this,h_).call(this)}get error(){return In(this,Xy)}set error(e){Ll(this,Xy,e),In(this,m_).call(this)}get messages(){return In(this,ko)}set messages(e){Ll(this,ko,[...e]),In(this,Of).call(this)}};ko=new WeakMap;Zy=new WeakMap;Xy=new WeakMap;Yp=new WeakMap;Gp=new WeakMap;Kp=new WeakMap;Of=new WeakMap;h_=new WeakMap;m_=new WeakMap;var Ff,DL=class extends vQe{constructor({messages:e,...t}){const n=new kQe(e);super({...t,state:n}),Vi(this,Ff,void 0),this["~registerMessagesCallback"]=(r,s)=>In(this,Ff)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>In(this,Ff)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>In(this,Ff)["~registerErrorCallback"](r),Ll(this,Ff,n)}};Ff=new WeakMap;function yee({experimental_throttle:e,resume:t=!1,...n}={}){const r=j.useRef("chat"in n?n.chat:new DL(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new DL(n));const o="id"in n?n.id:null,i=j.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=j.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=j.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=j.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=j.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return j.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolResult}}function EQe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function _Qe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function DQe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function MQe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function vee(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:MQe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function wee(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function TQe(){var b;const{authToken:e,tokenProps:t}=Ge(),n=Q(x=>x.dashboard.aiScopeTables),r=(b=s1().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=yee({transport:new FI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Oi.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:x.currentAIContext,reasoningEffort:x.reasoningEffort,showReasoning:x.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:x,body:y})=>({body:{...y,messages:$W(x)}})}),onToolCall:m,sendAutomaticallyWhen:wQe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function m({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:vee(n||[])}}),x.toolName==="getDashboardContext"){const y=Q.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const p=!["ready","error"].includes(l),g=wee(d);return{sendMessage:s,regenerate:a,isLoading:p,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function See(){var u;const{authToken:e,tokenProps:t}=Ge(),n=(u=s1().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=cn({queryKey:["assistant-profile",n],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function Cee({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:c.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[c.jsxs("div",{className:"mb-3 flex items-center",children:[c.jsx(M8,{className:"mr-2 h-4 w-4 text-muted-foreground"}),c.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function Vw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(fD,{className:r});case"view":return c.jsx(vd,{className:r});case"materialized view":return c.jsx(Iae,{className:r});case"model":return c.jsx(a1,{className:r});case"file":return c.jsx(ki,{className:r});case"dataset":return c.jsx(al,{className:r});case"upload":return c.jsx(pD,{className:r});case"url":return c.jsx(L8,{className:r});default:return c.jsx(i1,{className:r})}}const Nee=D.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(va,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(ds.Input,{ref:n,className:X("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));Nee.displayName=ds.Input.displayName;const vy=e=>e.label||(e==null?void 0:e.name),ML=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function RQe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=Ge(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=j.useState(""),[p,g]=j.useState(""),b=s.filter(S=>{if(!h)return!0;const N=vy(S).toLowerCase(),_=ML(S).toLowerCase(),E=h.toLowerCase();return N.includes(E)||_.includes(E)});j.useEffect(()=>{e||(m(""),g(""))},[e]),j.useEffect(()=>{b.length>0&&!p&&g(vy(b[0]))},[b,p]);const x=()=>{if(!p)return;const S=b.find(N=>vy(N)===p);S&&(o.some(_=>"id"in S&&"id"in _?S.id===_.id:S.name===_.name&&S.connectionId===_.connectionId)||t(S),i(S),r())},y=S=>{(S.key==="Tab"||S.key==="Enter")&&(S.preventDefault(),x())};if(!e)return null;const v=S=>o.some(N=>"id"in S&&"id"in N?S.id===N.id:S.name===N.name&&S.connectionId===N.connectionId),w=o.length===s.length,C=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(FS,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(Nee,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(kr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),a==null||a()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),C&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),l==null||l()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(yt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs($S,{className:"min-h-60",children:[c.jsx(LS,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(kr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(zS,{children:b.map((S,N)=>{const _=v(S),E="id"in S?S.id:`${S.connectionId}-${S.name}`,k=vy(S);return c.jsxs(BS,{value:k,onSelect:()=>{_?n==null||n(S):t(S)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:X("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:Vw(S.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:k}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:ML(S)})]}),_&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx($r,{className:"h-3 w-3 text-background"})})]},E)})})]})]})})}const p_=e=>e.name||e.name,IQe=e=>{const t=p_(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"font-medium",children:t}),n&&c.jsx("div",{className:"text-sm text-muted-foreground",children:n}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function AQe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=j.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(On,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(un,{children:[c.jsx(dn,{asChild:!0,children:c.jsxs(Oe,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[Vw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:p_(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(yt,{className:"h-3 w-3"})})]})}),c.jsx(pn,{side:"top",className:"max-w-xs",children:IQe(d)})]},h)}),u&&c.jsxs(un,{open:s,onOpenChange:o,children:[c.jsx(dn,{asChild:!0,children:c.jsxs(Oe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(Aae,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(yt,{className:"h-3 w-3"})})]})}),c.jsx(pn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:Vw(d.type,{size:"h-3 w-3"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:p_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(yt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function jee(e){return e.type==="dataset"&&e.label||e.name}function PQe(e){const t=[];return t.push({label:"Type",value:e.type}),t.push({label:"Name",value:e.name}),e.connectionType&&t.push({label:"Connection",value:e.connectionType}),e.database&&t.push({label:"Database",value:e.database}),e.schema&&t.push({label:"Schema",value:e.schema}),e.type==="dataset"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="dataset"&&e.description&&t.push({label:"Description",value:e.description}),e.type==="model"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="model"&&e.description&&t.push({label:"Description",value:e.description}),t}function OQe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(de,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(Oe,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),jee(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(yt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function FQe(e){const{tokenProps:t}=Ge(),n=Q(l=>l.authToken)||e;Ee(l=>l.selectedConnectionId),Ee(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=cn({queryKey:["semantic-domains"],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function $Qe(e,t){const{tokenProps:n}=Ge(),r=Q(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=cn({queryKey:["datasets",e],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function LQe(e){var g,b;const{tokenProps:t}=Ge(),n=Q(x=>x.authToken)||e,{connections:r}=Pi(e),s=Ee(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:m}=cn({queryKey:["databases",s],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:l}}function zQe(e){var g;const{tokenProps:t}=Ge(),n=Q(b=>b.authToken)||e,{connections:r}=Pi(e),s=Ee(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Ee(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:m}=cn({queryKey:["schemas",s,o],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:l}}function kee(e){const{tokenProps:t}=Ge(),n=Q(h=>h.authToken)||e,{connections:r}=Pi(e),s=Ee(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=cn({queryKey:["dataModels",s],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function BQe(){var C,S,N;const e=Ee(_=>_.card.dataSource);Ee(_=>_.actions.updateDirectSource);const t=Ee(_=>_.actions.updateDataSource),[n,r]=j.useState(""),{selectedConnection:s,error:o}=Pi(),{databases:i,isPending:a,error:l,label:u}=LQe(),{schemas:d,isPending:f,error:h,label:m}=zQe(),{error:p}=kee(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=_=>{e&&t({...e,dbSelection:{database:_,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=_=>{var k;if(!((k=e==null?void 0:e.dbSelection)!=null&&k.database))return;const E=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...E,schema:_},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||p)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[m,": ",h.message]}),p&&c.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),c.jsx(oe,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:u}),c.jsxs(rt,{value:((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)||"",onValueChange:v,disabled:a,children:[c.jsx(tt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(Mn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(nt,{children:i.map(_=>c.jsx(ge,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]}),((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:m}),c.jsxs(rt,{value:((N=e==null?void 0:e.dbSelection)==null?void 0:N.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(tt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(Mn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(nt,{children:d.map(_=>c.jsx(ge,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]})]})]})}function VQe(){const e=Ee(l=>l.card.dataSource),t=Ee(l=>l.actions.updateDataSource),[n,r]=j.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(pD,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(de,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(ki,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(yt,{className:"h-3 w-3"})})]},l.id))})]})]})}function HQe(){const e=Ee(f=>f.card.dataSource),t=Ee(f=>f.actions.updateDataSource),[n,r]=j.useState(""),[s,o]=j.useState(""),[i,a]=j.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(m=>m.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(jn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(jn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[c.jsx("option",{value:"api",children:"API Endpoint"}),c.jsx("option",{value:"csv",children:"CSV File"}),c.jsx("option",{value:"json",children:"JSON File"})]})]}),c.jsxs(oe,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(kr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(de,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(i1,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(yt,{className:"h-3 w-3"})})]},f.id))})]})]})}function UQe(e,t){var y,v;const{tokenProps:n}=Ge(),r=Q(w=>w.authToken)||t,{connections:s}=Pi(t),o=Ee(w=>{var C,S;return(S=(C=w==null?void 0:w.card)==null?void 0:C.dataSource)==null?void 0:S.connectionId}),i=Ee(w=>{var C,S,N;return(N=(S=(C=w==null?void 0:w.card)==null?void 0:C.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.database}),a=Ee(w=>{var C,S,N;return(N=(S=(C=w==null?void 0:w.card)==null?void 0:C.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:m,isLoading:p,error:g,refetch:b}=cn({queryKey:[e,o,i,a],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(w=>{var C;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(C=w==null?void 0:w.table_type)==null?void 0:C.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function Hw({title:e,message:t}){return c.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:c.jsxs("div",{className:"flex items-start gap-4",children:[c.jsx(yd,{className:"h-6 w-6 flex-shrink-0"}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h4",{className:"text-base font-semibold",children:e}),t&&c.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function WQe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Pi(),[i,a]=j.useState(""),[l,u]=j.useState(""),[d,f]=j.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=lr(),{entities:p,isLoading:g,error:b}=UQe("table"),{dataModels:x,isPending:y,error:v}=kee(),w=k=>{const M=s.find(O=>O.id===k);if(!M)return;const T=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:k,connectionType:M.type,mode:T,dbSelection:{database:"",schema:"",entityType:"table"}}),m(k)},C=k=>{var R,I;const M=n||[],T=M.some(L=>L.name===k.name&&L.type===k.type);let O;if(T)O=M.filter(L=>!(L.name===k.name&&L.type===k.type));else{const L={connectionId:e.connectionId,connectionType:e.connectionType,type:k.type,dbObjectType:k.dbObjectType,database:((R=e.dbSelection)==null?void 0:R.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:k.name,dialect:k.dialect};O=[...M,L]}t==null||t(O)},S=k=>{const M=n||[],T=M.some(R=>R.type==="model"&&R.name===k.name);let O;T?O=M.filter(R=>!(R.type==="model"&&R.name===k.name)):O=[...M,k],t==null||t(O)},N=p.filter(k=>k.name.toLowerCase().includes(i.toLowerCase())),_=x.filter(k=>k.name.toLowerCase().includes(l.toLowerCase())),E=j.useCallback(()=>{if(!t)return;const k=n||[];let M=[...k];if(d==="tables"){const O=N.filter(R=>!k.some(I=>I.name===R.name&&I.type==="table")).map(R=>{var I,L;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:R.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((L=e.dbSelection)==null?void 0:L.schema)||"",name:R.name,dialect:R.dialect}});M=[...k,...O]}else if(d==="datamodels"){const T=_.filter(O=>!k.some(R=>R.name===O.name&&R.type==="model"));M=[...k,...T]}t(M)},[d,N,_,n,e,t]);return j.useEffect(()=>{r&&r(E)},[r,E]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(rt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(tt,{className:"w-full",children:c.jsx(at,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(nt,{children:s.map(k=>c.jsx(ge,{className:"hover:bg-muted",value:k.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(al,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:k.name}),c.jsx(Oe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:k.type})]})},k.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(VQe,{}),e.connectionType==="url"&&c.jsx(HQe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(BQe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(As,{defaultValue:"tables",value:d,onValueChange:k=>f(k),className:"w-full",children:[c.jsxs(cs,{className:"grid w-full grid-cols-2",children:[c.jsxs(qt,{value:"tables",children:["Tables & Views (",N.length,")"]}),c.jsxs(qt,{value:"datamodels",children:["Data Models (",_.length,")"]})]}),c.jsxs(nr,{value:"tables",className:"space-y-2",children:[c.jsx(Nn,{placeholder:"Search tables and views...",value:i,onChange:k=>a(k.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(Hw,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):N.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):N.map(k=>{const M=n.some(T=>T.name===k.name&&T.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(k),children:[c.jsx(nn,{id:`table-${k.name}`,checked:M,onCheckedChange:()=>C(k),onClick:T=>T.stopPropagation(),disabled:g}),c.jsxs(de,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[k.name,k.dbObjectType==="view"&&c.jsx(Oe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),k.dbObjectType==="materialized view"&&c.jsx(Oe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},k.name)})})]}),c.jsxs(nr,{value:"datamodels",className:"space-y-2",children:[c.jsx(Nn,{placeholder:"Search data models...",value:l,onChange:k=>u(k.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(Hw,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):_.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):_.map(k=>{const M=n.some(T=>T.name===k.name&&T.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(k),children:[c.jsx(nn,{id:`dataModel-${k.name}`,checked:M,onCheckedChange:()=>S(k),onClick:T=>T.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(de,{className:"cursor-pointer",children:k.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:k.description})]})]},k.name)})})]})]})})})]})]})]})}function qQe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var C;const[l,u]=j.useState(""),d=j.useCallback(S=>{const N={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...N})},[e,t]);j.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:m}=FQe(),p=o?f.filter(S=>s.includes(S.id)):f,{datasets:g,isPending:b,error:x}=$Qe(e==null?void 0:e.semanticDomainId),y=S=>{const N=r||[],_=N.some(k=>k.id===S.id&&k.type==="dataset");let E;if(_)E=N.filter(k=>!(k.id===S.id&&k.type==="dataset"));else{const k={id:S.id,datasetType:S.type,name:S.name||S.table,label:S.label,domainId:S.domainId,description:S.description,database:S.database,schema:S.schema,type:"dataset",connectionId:S.connectionId,connectionType:S.connectionType,dialect:S.dialect,datamodelId:S.datamodelId,sql:S.sql};E=[...N,k]}n==null||n(E)},v=g.filter(S=>S.name.toLowerCase().includes(l.toLowerCase())),w=j.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const S=r||[],_=v.filter(k=>!S.some(M=>M.id===k.id&&M.type==="dataset")).map(k=>({id:k.id,datasetType:k.type,name:k.name||k.table,label:k.label,domainId:k.domainId,description:k.description,database:k.database,schema:k.schema,type:"dataset",connectionId:k.connectionId,connectionType:k.connectionType,dialect:k.dialect,datamodelId:k.datamodelId,sql:k.sql})),E=[...S,..._];n(E)},[v,r,e==null?void 0:e.semanticDomainId,n]);return j.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(rt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(tt,{className:"w-full",children:c.jsx(at,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((C=p.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:C.label)||"Select semantic domain"})}),c.jsx(nt,{children:p.map(S=>c.jsx(ge,{className:"hover:bg-muted",value:S.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:S.label}),c.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),m&&c.jsx(Hw,{title:"Error loading semantic models",message:m.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Nn,{placeholder:"Search datasets...",value:l,onChange:S=>u(S.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(Hw,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(S=>{const N=r.some(_=>_.id===S.id&&_.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(S),children:[c.jsx(nn,{id:`dataset-${S.id}`,checked:N,onCheckedChange:()=>y(S),onClick:_=>_.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(de,{className:"cursor-pointer font-medium",children:S.label||S.name}),c.jsx("span",{className:"text-xs text-gray-500",children:S.description})]})]},S.label||S.name)})})]})]})]})}function $I({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Ge(),{allowedSemanticDomains:i}=o,[a,l]=j.useState([]),{updateDataSource:u}=lr(),d=Q(M=>M.isVisualEditing),f=Q(M=>M.dashboard.aiContext),{setAiContext:h}=Gt(),m=j.useRef(null),[p,g]=j.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=j.useCallback(M=>{const T=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:T,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...T!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=j.useCallback(M=>{u({...n,...M})},[n,u]);j.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),j.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),j.useEffect(()=>{e?l(s||[]):(m.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const C=M=>{const T=a.filter(O=>!(O.name===M.name&&O.type===M.type));l(T)},S=()=>{l([])},N=j.useCallback(M=>{l(M)},[]),_=j.useCallback(()=>{m.current&&m.current()},[]),E=j.useCallback(M=>{m.current=M,g(!0)},[]);function k(){var M,T;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const O=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,R=(T=a==null?void 0:a[0])==null?void 0:T.connectionType;u({...n,connectionId:O,connectionType:R,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsx(Ur,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Wr,{className:"flex-shrink-0",children:[c.jsx(qr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(Is,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(As,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(cs,{className:"grid w-full grid-cols-2",children:[c.jsx(qt,{value:"database",children:"Direct Source"}),c.jsx(qt,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(qQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:E}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(WQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,onRegisterSelectAll:E})]})}),c.jsx(OQe,{selectedEntities:a,onDeselectEntity:C}),c.jsx(Rs,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(oe,{variant:"outline",onClick:_,disabled:!p,children:"Select All"}),c.jsx(oe,{variant:"outline",onClick:S,disabled:a.length===0,children:"Clear All"}),c.jsxs(oe,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(yt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(oe,{onClick:k,children:[c.jsx($r,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function YQe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=j.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=Ba-n;if(l.length>u){Fe.error(`You can only attach ${Ba} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=lJ(l);if(f.forEach(({file:h,error:m})=>{Fe.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>jI(m)));e(h)}catch(h){console.error("Failed to process files:",h),Fe.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=Ba}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Ba,title:n>=Ba?`Maximum ${Ba} files allowed`:"Attach files",children:c.jsx(aD,{className:"h-4 w-4 text-muted-foreground"})})]})}function GQe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=j.useState(!1),a=j.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=j.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=j.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=j.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const m=Ba-r;if(h.length>m){Fe.error(`You can only attach ${Ba} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=lJ(h);if(g.forEach(({file:b,error:x})=>{Fe.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>jI(x)));t(b),Fe.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),Fe.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:X("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(pD,{className:"h-8 w-8 text-primary"}),c.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ba-r," slot(s) available"]})]})})]})}const LI=j.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=j.useState(!1),[h,m]=j.useState(!1),[p,g]=j.useState(!1),b=j.useRef(null),x=$m();YNe(),qNe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:C}=G1(),{queueMessage:S}=Lm(),{addFileAttachment:N,removeFileAttachment:_,clearFileAttachments:E,getFileAttachments:k}=rT(),M=nT(l),T=Ee(H=>H.card.dataSource),O=Q(H=>H.dashboard.aiContext),R=Q(H=>{var G;return(G=H.dashboard.aiContext)==null?void 0:G.selectedEntities});j.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=j.useCallback(()=>{const H=b.current;if(H){if(!e||e.length===0){H.style.height="10px";return}H.style.height="auto";const G=Math.min(Math.max(H.scrollHeight,10),200);H.style.height=`${G}px`}},[e]);j.useEffect(()=>{I()},[I]),j.useEffect(()=>{const H=setTimeout(()=>{I()},0);return()=>clearTimeout(H)},[I]);const L=()=>{const H=e.trim();!H&&M.length===0||(a!=="ready"?(S(l,H,M),t(""),E(l)):r({preventDefault:()=>{}}))},F=H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),L()),H.key==="@"&&(W(),f(!0))},V=j.useCallback(H=>{const G=lqe(H.nativeEvent);G.length>0&&(H.preventDefault(),G.forEach(async K=>{const te=await jI(K);N(l,te)}))},[N,l]),$=j.useCallback(H=>{H.forEach(G=>{N(l,G)})},[N,l]),P=j.useCallback(H=>{H.forEach(G=>{N(l,G)})},[N,l]),U=j.useCallback(H=>{_(l,H)},[_,l]),B=H=>{if(x.selectedEntities.some(K=>K.id&&K.id===H.id||K.name===H.name)){const K=x.selectedEntities.filter(te=>!(te.id&&te.id===H.id||te.name===H.name));y({selectedEntities:K})}else{const K=[...x.selectedEntities,H];y({selectedEntities:K})}},A=H=>{B(H)},Y=H=>{var te;if(!x.selectedEntities.some(Z=>Z.id&&Z.id===H.id||Z.name===H.name)){const Z=[...x.selectedEntities,H];y({selectedEntities:Z})}const K="label"in H?H.label:H.name;t(e+`@${K} `),f(!1),(te=b.current)==null||te.focus()},z=H=>{const G=x.selectedEntities.filter(Z=>!(Z.id&&Z.id===H.id||Z.name===H.name));y({selectedEntities:G});const te=`@${"label"in H?H.label:H.name}`;e.includes(te)&&t(e.replace(te,"").trim())},q=H=>{const G=new Set(H.map(Z=>Z.id||Z.name)),K=x.selectedEntities.filter(Z=>!G.has(Z.id||Z.name));y({selectedEntities:K});let te=e;H.forEach(Z=>{const se=`@${"label"in Z?Z.label:Z.name}`;te=te.replace(se,"").trim()}),t(te)},W=j.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})},[x.selectedEntities.length,O==null?void 0:O.selectedEntities,y]);return c.jsxs(GQe,{onFilesDropped:$,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(AQe,{entities:x.selectedEntities,availableEntities:R||[],onRemoveEntity:z,onRemoveEntities:q}),M.length>0&&c.jsx(cqe,{files:M,onRemove:U,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:F,onPaste:V,onFocus:()=>{I(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(ks,{open:d,onOpenChange:H=>{H&&W(),f(H)},children:[c.jsx(Es,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Eae,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(_s,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:H=>H.preventDefault(),children:c.jsx(RQe,{isOpen:!0,onSelect:B,onDeselect:A,onClose:()=>{var H;f(!1),(H=b.current)==null||H.focus()},availableEntities:R||[],selectedEntities:x.selectedEntities,onTabComplete:Y,onSelectAll:()=>{R&&y({selectedEntities:R})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),m(!0)}})})]}),c.jsx(YQe,{onFilesSelected:P,disabled:s,currentFileCount:M.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(oe,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(Wae,{className:"size-3.5 bg-background"})}),!s&&c.jsx(oe,{disabled:!e.trim()&&M.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:L,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(q8,{className:"size-4"})})]})]})]}),c.jsx($I,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:m,dataSource:T||tC,dialogMode:"aiContext"})]})});LI.displayName="ChatInputWithContext";function Eee({assistantType:e,className:t}){const n=LW(e),{removeFromQueue:r}=Lm();return n.length===0?null:c.jsxs("div",{className:X("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(ml,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>c.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(yt,{className:"h-3 w-3"})})]})},s.id))})]})}function _ee({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=LW(e),{dequeueMessage:o}=Lm();j.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function Dee(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=j.useRef(null),[a,l]=j.useState(!0),[u,d]=j.useState(!0),[f,h]=j.useState(!1),[m,p]=j.useState(0),g=j.useRef(0),b=j.useRef(!1),x=j.useRef(0),y=j.useRef(a),v=j.useRef(),w=j.useRef({key:null,count:0,length:0}),C=j.useCallback(()=>{const E=i.current;return E?E.scrollHeight-E.scrollTop-E.clientHeight:0},[]),S=j.useCallback((E={})=>{if(!i.current)return;const{force:M=!1,instant:T=!1}=E;if(!M&&!y.current||!a&&!M)return;const O=T||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!M&&!y.current){b.current=!1,v.current=void 0;return}const R=i.current;if(!R){b.current=!1,v.current=void 0;return}const I=R.scrollHeight;O==="smooth"&&"scrollTo"in R?R.scrollTo({top:I,behavior:O}):R.scrollTop=I,g.current=R.scrollTop,d(!0),l(!0),y.current=!0,h(!1),p(0),b.current=!1,v.current=void 0})},[r,a]),N=j.useCallback(()=>{const E=i.current;if(!E)return;const k=g.current,M=E.scrollTop,T=M-k;if(g.current=M,T<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const O=C()<=n;d(O),l(O),y.current=O,O&&(h(!1),p(0))},[C,n]),_=j.useCallback(()=>{p(0),h(!1)},[]);return j.useEffect(()=>{y.current=a},[a]),j.useEffect(()=>{const E=i.current;if(!E||!e||e.length===0){h(!1),p(0),w.current={key:null,count:0,length:0},g.current=E?E.scrollTop:0,x.current=E?E.scrollHeight:0;return}g.current=E.scrollTop,x.current=E.scrollHeight;const k=w.current,M=e[e.length-1],T=(M==null?void 0:M.id)??(M==null?void 0:M.messageId)??(M==null?void 0:M.createdAt)??(M==null?void 0:M.timestamp)??e.length,O=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce(($,P)=>P?typeof P=="string"?$+P.length:typeof P.text=="string"?$+P.text.length:typeof P.content=="string"?$+P.content.length:typeof P.value=="string"?$+P.value.length:$:$,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,R=e.length>k.count,I=T!==k.key,L=O>k.length,F=s&&(M==null?void 0:M.role)==="assistant"&&!R&&(I||L),V=o||F;if(w.current={key:T,count:e.length,length:O},a&&(R||I||L||V)){S({force:!1,instant:V});return}if(!a&&R){const $=e.length-k.count;$>0&&(h(!0),p(P=>P+$))}else!a&&L&&(h(!0),p($=>$>0?$:1))},[e,S,a,s,o]),j.useEffect(()=>{S({instant:!0})},[S]),j.useEffect(()=>{if(typeof ResizeObserver>"u")return;const E=i.current;if(!E)return;x.current=E.scrollHeight;const k=new ResizeObserver(()=>{const M=i.current;if(!M)return;const T=x.current,O=M.scrollHeight;x.current=O,!b.current&&y.current&&O>T&&S({force:!1,instant:!0})});return k.observe(E),()=>{k.disconnect()}},[S]),j.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:m,scrollToBottom:S,handleScroll:N,resetNewMessageCount:_}}function Mee(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=j.useState(r),a=j.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=j.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=j.useCallback(()=>{i(r)},[r]);return j.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function Tee(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:r.text||"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:cJ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const KQe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function ZQe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=j.useState(!1),[a,l]=j.useState(T_),[u,d]=j.useState(!1),[f,h]=j.useState(!1),[m,p]=j.useState(!1),g=n??m,{isLocalDev:b,isConsoleMode:x}=gm(),y=j.useRef(null);Q(Be=>Be.dashboard.aiScopeTables),Q(Be=>Be.isDashboardEditing);const v=Q(Be=>Be.selectedSheetId),{setDataSource:w}=lr(),{addFrame:C,setSelectedFrameId:S,setIsDashboardEditing:N}=Gt(),_=$m(),{setCurrentAIContext:E,updateSelectedEntities:k,setReasoningEffort:M,setShowReasoning:T}=G1(),{clearQueue:O}=Lm(),{clearFileAttachments:R,getFileAttachments:I}=rT(),L=nT("dashboard"),F=Q(Be=>Be.dashboard.aiContext),V=Ee(Be=>Be.card.dataSource),{assistantProfile:$}=See(),P=Q(Be=>Be.handleOpenAssistantProfile),{sendMessage:U,isLoading:B,messages:A,setMessages:Y,status:z,stop:q,errorMessage:W,clearError:H}=TQe(),G=j.useCallback(Be=>{r==null||r(Be),n===void 0&&p(Be)},[n,r]),K=j.useCallback(()=>{G(!g)},[g,G]);j.useEffect(()=>{if(!g)return;function Be(We){We.key==="Escape"&&G(!1)}return window.addEventListener("keydown",Be),()=>{window.removeEventListener("keydown",Be)}},[g,G]);const[te,Z]=j.useState(""),ee=Be=>{Z(Be.target.value)};function se({sql:Be,data:We,cardTitle:ht,connectionId:qe,cardType:Je,python:Ne,cardConfig:_e,dataSource:Re}){if(console.log("handleAddNewFrame",{sql:Be,data:We,cardTitle:ht,connectionId:qe,cardType:Je,python:Ne,cardConfig:_e,dataSource:Re}),!v)return;const Ve={id:jr(),title:ht||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Je==="horizontalBar"?"y":"x"}},type:Je,sql:Be,python:Ne,dataSource:Re,config:_e,connectionId:qe},it={id:jr(),cards:[Ve],activeCardId:Ve.id};N(!0),C(v,it,"end"),S(it.id)}const ce=Be=>{Be.preventDefault();const We=te.trim();if(!We&&L.length===0)return;const ht=[];We&&ht.push({type:"text",text:We}),L.forEach(qe=>{qe.data&&ht.push({type:"file",mediaType:qe.type,filename:qe.name,url:`data:${qe.type};base64,${qe.data}`})}),U({role:"user",parts:ht}),Z(""),R("dashboard"),le({force:!0})};j.useEffect(()=>{var Be;e&&((Be=y.current)==null||Be.focus())},[e]),_ee({assistantType:"dashboard",status:z,isLoading:B,sendMessage:U});const{hasActiveTools:re}=Tee(A),{visibleMessages:fe,hasMoreMessages:Ce,totalMessageCount:ie,loadMoreMessages:pe,resetMessageWindow:ue}=Mee(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ve,isAtBottom:Se,hasNewMessages:Qe,newMessageCount:Ke,scrollToBottom:le,handleScroll:xe,resetNewMessageCount:Le}=Dee(fe,{threshold:50,behavior:"smooth",isStreaming:B});function me(Be){Ie();const We={role:"user",parts:[{type:"text",text:Be.title+" "+Be.subtitle}]};U(We)}function ke(Be){Ie(),U({role:"user",parts:[{type:"text",text:Be}]})}function $e(Be){Ie(),U({role:"user",parts:[{type:"text",text:Be}]}),le({force:!0})}const He=j.useCallback(async()=>{const Be=JSON.stringify(A??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Be),Fe.success("Conversation copied")}catch(We){console.error("Failed to copy conversation",We),Fe.error("Unable to copy conversation")}},[A]);function Ie(){_.selectedEntities.length===0&&E({selectedEntities:(F==null?void 0:F.selectedEntities)||[]})}const st=(te==null?void 0:te.length)===0&&(A==null?void 0:A.filter(Be=>Be.role==="user").length)===0;function je(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function pt(){return c.jsxs(mm,{children:[c.jsx(pm,{asChild:!0,children:c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(om,{className:"size-3.5"})})}),c.jsxs(Zd,{align:"end",children:[c.jsx(eh,{children:"Options"}),c.jsx(Cd,{}),c.jsx(Qp,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Qp,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Qp,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const It=c.jsxs("div",{"data-role":"dashboard-assistant",className:X("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[je(),P&&c.jsx(oe,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:P,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&pt(),a&&c.jsx(oe,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:He,children:"Copy Conversation"}),c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:K,children:g?c.jsx(iD,{className:"size-4"}):c.jsx(l1,{className:"size-4"})}),c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{Y([]),O("dashboard"),H(),ue()},children:c.jsx(c1,{className:"size-4"})}),c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(yt,{className:"size-4"})})]})]}),c.jsxs(Cl,{"data-role":"dashboard-assistant-scroll-area",ref:ve,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:xe,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[Ce&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:pe,className:"text-xs",children:["Load ",Math.min(5,ie-fe.length)," ","more messages (",ie-fe.length," ","hidden)"]})}),c.jsx(dJ,{showTools:a,showSystemMessage:u,messages:fe,onAddToDashboard:se,onQuickReply:$e,disableQuickReplies:B}),!re&&c.jsx(uJ,{status:z,errorMessage:W})]}),c.jsx(Zo,{orientation:"horizontal"})]}),e&&!Se&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{le({force:!0}),Le()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(Ks,{className:"h-4 w-4"}),Qe&&Ke>0&&c.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:Ke>9?"9+":Ke})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&st&&c.jsx(fJ,{onClick:me,placeholders:KQe}),c.jsx("div",{children:st&&$&&c.jsx(Cee,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:ke})}),c.jsx(Eee,{assistantType:"dashboard",className:"mb-3"}),c.jsx(LI,{ref:y,setInput:Z,stop:q,input:te,handleInputChange:ee,handleSubmit:Be=>{Ie(),ce(Be),le({force:!0})},isLoading:B,status:z,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx($I,{incomingSelectedEntities:(F==null?void 0:F.selectedEntities)||[],open:f,onOpenChange:h,dataSource:V||tC,dialogMode:"aiContext"})]});return g&&s?Pn.createPortal(c.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:c.jsx("div",{className:"flex h-full w-full",children:It})}),s):It}function XQe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Gt(),o=Q(d=>d.dashboard.sheets),a=Q(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=Q(d=>d.isDashboardEditing),u=Q(d=>d.isVisualEditing);j.useEffect(()=>{if(!l||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),Fe.success("Card copied to clipboard"),m.preventDefault()):p&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=_R(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),Fe.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function QQe(e,t){switch(e.interactionMode){case"drillToDetail":JQe(e,t);break;case"drillThrough":eJe(e,t);break;case"drillToURL":tJe(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 JQe(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 eJe(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 tJe(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 nJe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsxs(Ur,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Wr,{children:[c.jsx(qr,{children:i||"Insight Detail"}),c.jsx(Is,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(xZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(wZ,{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 rJe(){const e=Pt(w=>w.interactionStates),t=Pt(w=>w.setInteractionState),n=Pt(w=>w.clearLastInteractionEvent),r=Pt(w=>w.replaceCardWithInsight),s=Pt(w=>w.setPendingDrillThrough),o=Pt(w=>w.pendingDrillThrough),i=Pt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Gt(),{selectDashboard:u}=$b(),d=Q(w=>w.dashboard),f=Q(w=>w.filterValues),{data:h,isLoading:m}=ahe((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=j.useState({open:!1,insightId:""}),b=SZ(p.insightId,{enabled:p.open&&!!p.insightId}),x=j.useRef(new Set),y=j.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:C,contextMode:S})=>{g({open:!0,insightId:w,filters:C,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:S})},replaceCardContent:({cardId:w,insightId:C,filters:S,contextMode:N})=>{r(w,C,S,N)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:C,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:_})=>{const k={sourceCardId:oa,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...Po(),appliedClickFilters:[k],contextMode:C,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:_};t(oa,M)}}),[a,r,f,l,d,s,t]);j.useEffect(()=>{Object.entries(e).forEach(([w,C])=>{if(C!=null&&C.lastInteractionEvent){const S=C.lastInteractionEvent,N=`${w}-${S.interactionMode}-${S.sourceCardId}-${Date.now()}`;if(x.current.has(N))return;x.current.add(N);try{QQe(S,y)}catch(_){console.error("Error executing interaction event:",_)}finally{n(w),setTimeout(()=>{x.current.delete(N)},5e3)}}})},[e,n,y]),j.useEffect(()=>{if(!(!o||!h||m))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,m,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(nJe,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&m&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(Mn,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function sJe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=oJe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function oJe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function iJe(e){return e?`Back to ${e}`:"Back"}function aJe(){var x,y,v,w,C;const e=Pt(S=>S.interactionStates[oa]),t=Q(S=>S.actions.goBackFromDrill),n=Q(S=>S.actions.clearDrillContext),{selectDashboard:r}=$b(),[s,o]=j.useState({x:16,y:16}),[i,a]=j.useState(!1),l=j.useRef({x:0,y:0});j.useEffect(()=>{if(!i)return;const S=_=>{o({x:_.clientX-l.current.x,y:_.clientY-l.current.y})},N=()=>{a(!1)};return document.addEventListener("mousemove",S),document.addEventListener("mouseup",N),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",N)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:w.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((C=e.appliedClickFilters)!=null&&C.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(S){console.error("[DrillBack] Error during back navigation:",S)}},p=()=>{n()},g=S=>{S.target.closest("button")||(a(!0),l.current={x:S.clientX-s.x,y:S.clientY-s.y})};sJe(f);const b=iJe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((S,N)=>{const _=S.field.label||S.field.name,E=String(S.value);return c.jsxs(Oe,{variant:"secondary",className:"pointer-events-none text-xs",children:[_," = ",E]},N)})})]}),c.jsx(oe,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(yt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(oe,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(g8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function Ree(){var Z;const{showAssistant:e,tokenProps:t}=Ge(),{preferences:n,isConsoleMode:r}=gm(),s=((Z=n==null?void 0:n.cardDisplay)==null?void 0:Z.mode)==="print",o=j.useRef(null),i=j.useRef(null),[a,l]=j.useState(!1),u=id(ee=>ee.setFullscreen),d=id(ee=>ee.setPanelOpen),f=id(ee=>ee.setContainer),h=PW("dashboard"),m=OW(),p=FW("dashboard"),g=h.isOpen,b=m==="dashboard",x=Q(ee=>ee.isVisualEditing),y=Q(ee=>ee.themeStyle),v=Q(ee=>{var se;return(se=ee.dashboard)==null?void 0:se.sheets}),w=Q(ee=>ee.isDashboardEditing),C=Q(ee=>ee.selectedSheetId),S=Q(ee=>{var se;return(se=ee.dashboard)==null?void 0:se.id}),N=Q(ee=>ee.isDashboardPanelOpen),_=Q(ee=>ee.actions.setIsDashboardPanelOpen),{getDefaultSheetId:E,setDefaultSheetId:k,clearDefaultSheetId:M}=d8(S),[T,O]=j.useState(null);j1(Ft.DASHBOARD);const{setSelectedSheetId:R,setSheetTitle:I,addSheet:L,setSheets:F}=Gt();XQe(i);const{setActiveAssistantType:V}=G1();j.useEffect(()=>{if(S){const ee=E();O(ee)}},[S,E]),j.useEffect(()=>{g?V("dashboard"):m==="dashboard"&&u(null)},[g,V,m,u]);function $(ee){var se,ce;ee?((se=o.current)==null||se.resize(40),d("dashboard",!0),V("dashboard")):(d("dashboard",!1),u(null),(ce=o.current)==null||ce.resize(0),V(null))}function P(){const ee={id:jr(),title:"New Sheet"};L(ee),R(ee.id)}function U(ee,se){if(!S)return;T===ee?(M(),O(null),Fe.success("Default sheet cleared")):(k(ee),O(ee),Fe.success(`"${se}" set as default sheet`))}function B(ee){ee<1?(d("dashboard",!1),u(null),V(null)):(g||d("dashboard",!0),V("dashboard"))}function A(){return(y==null?void 0:y.canvasTheme)==="muted"||!(y!=null&&y.canvasTheme)?"hsl(var(--semaphor-muted))":(y==null?void 0:y.canvasTheme)==="clear"?"":y==null?void 0:y.canvasTheme}const Y=(ee,se)=>{ee.dataTransfer.setData("tabIndex",se.toString())},z=ee=>{ee.preventDefault()},q=(ee,se)=>{const ce=ee.dataTransfer.getData("tabIndex");if(ce===se.toString())return;const re=Array.from(v||[]),[fe]=re.splice(parseInt(ce),1);re.splice(se,0,fe),F(re)},W=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail;function H(){var ee,se;if(v&&v.length>1||w)return c.jsxs(cs,{role:"tab-list",className:"flex h-11 items-center justify-start gap-2 rounded-none border-b border-b-muted bg-transparent px-2.5 py-3",children:[r&&W&&c.jsx(oe,{variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{_(!N)},className:"h-8 p-2",children:N?c.jsx(_8,{className:"h-4 w-4"}):c.jsx(D8,{className:"h-4 w-4"})}),v==null?void 0:v.map((ce,re)=>{const fe=C===ce.id,Ce=T===ce.id;return c.jsxs(qt,{draggable:!0,onDragStart:ie=>Y(ie,re),onDragOver:z,onDrop:ie=>q(ie,re),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>R(ce.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:ce.id,children:[c.jsx(ib,{enabled:w&&fe,text:ce.title,onSave:ie=>I(ce.id,ie),children:ce.title},ce.id),!w&&fe&&c.jsx("div",{title:Ce?"Clear default sheet":"Set as default sheet",children:c.jsx(dD,{className:X("ml-1 size-3 cursor-pointer transition-all",Ce?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:ie=>{ie.stopPropagation(),U(ce.id,ce.title||"Sheet")}})}),w&&fe&&v.length>1&&c.jsx(yt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},ce.id)}),w&&c.jsx("div",{style:{borderRadius:(se=(ee=y==null?void 0:y.chart)==null?void 0:ee.options)==null?void 0:se.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:P,children:c.jsx(kr,{className:"size-3"})})]})}function G(){return c.jsx("div",{ref:i,style:{},className:"grow",children:v==null?void 0:v.map(ee=>c.jsx(nr,{style:{backgroundColor:A()},className:X("mt-0",{}),value:ee.id,children:c.jsx(C8e,{sheet:ee})},ee.id))})}function K(){var ee;return c.jsxs(As,{"data-role":"dashboard-tabs-container",className:X("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:se=>{R(se)},value:C||((ee=v==null?void 0:v[0])==null?void 0:ee.id),children:[H(),c.jsx(Cl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:G()}),c.jsx(nze,{open:a,setOpen:l})]})}const te=j.useCallback(ee=>{f("dashboard",ee)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(rJe,{}),c.jsx(aJe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(YX,{className:X("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(qE,{children:K()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(tze,{open:g,onTabClick:$,withHandle:!0}),c.jsx(qE,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:B,defaultSize:g?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(ZQe,{open:g,setOpen:$,isFullscreen:b,onFullscreenChange:ee=>u(ee?"dashboard":null),fullscreenContainer:p})})})]})]}),c.jsx("div",{ref:te,className:X("absolute inset-0",!b&&"pointer-events-none")}),e===!0&&!s&&!g&&!x&&c.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:c.jsx(oe,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>$(!0),title:"Open Assistant",children:c.jsx(uD,{className:"h-5 w-5"})})})]})]}):null}function zI({children:e}){return c.jsx(Ca,{style:{height:"100%",width:"100%"},children:c.jsx(qie,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(On,{delayDuration:0,children:e})})})}function Iee({children:e,preferences:t}){const{currentUser:n}=Ts(),r=j.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($9.Provider,{value:r,children:c.jsx(RR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function Aee(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(Da,{FallbackComponent:SS,children:c.jsx(J_,{dashboardProps:e,children:c.jsx(zI,{children:c.jsx(Iee,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(sT,{...e,type:"dashboard",children:c.jsx(Ree,{})})})})})})})}function BI(e){const{tokenProps:t,authToken:n}=Ge(),r=t==null?void 0:t.apiServiceUrl;return cn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return Hn(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 Pee(e,t,n){if(t==="source")return{isValid:!0};const r=Ir(e.dataType);if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function Oee(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=(t==null?void 0:t.comparisonType)==="none";!o&&i||n(r,{groupByColumns:[],comparisonType:"none"})}const Fee=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=BI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=lr(),h=Ee(R=>R.card.type),m=e==null?void 0:e.id,p=j.useCallback(R=>{if(!(e!=null&&e.config))return[];switch(R){case"groupBy":return(e.config.groupByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,dateFormat:I.dateFormat,customFormat:I.customFormat,granularity:I.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,direction:I.direction}));case"source":return[];default:return[]}},[e]),g=j.useCallback((R,I)=>{if(m)switch(R){case"groupBy":{r(m,{groupByColumns:I});break}case"metrics":{r(m,{metricColumns:I});break}case"pivotBy":{r(m,{pivotByColumns:I});break}case"sortBy":{r(m,{sortByColumns:I});break}}},[m,r]),b=j.useCallback((R,I,L)=>{if(!m)return;const V=p(R)[I];if(V)switch(R){case"groupBy":s(m,V.id,{label:L});break;case"metrics":o(m,V.id,{label:L});break;case"pivotBy":i(m,V.id,{label:L});break;case"sortBy":a(m,V.id,{label:L});break}},[m,p,s,o,i,a]),x=j.useCallback((R,I)=>{if(!m)return;const F=p("metrics")[R];F&&o(m,F.id,{aggregate:I,label:hU(F.name,I)})},[m,p,o]),y=j.useCallback((R,I,L)=>{if(!m)return;const V=p("groupBy")[R];if(!V)return;const $={dateFormat:I};I==="custom"&&L?$.customFormat=L:$.customFormat=void 0,s(m,V.id,$)},[m,p,s]),v=j.useCallback((R,I)=>{if(!m)return;const F=p("groupBy")[R];F&&s(m,F.id,{granularity:I})},[m,p,s]),w=j.useCallback((R,I)=>{if(!m)return;const F=p("metrics")[R];F&&o(m,F.id,{aliasTemplate:I})},[m,p,o]),C=j.useCallback((R,I)=>{if(console.log("handleValueAliasesChange",R,I),!m)return;console.log("handleValueAliasesChange",R,I);const F=p("metrics")[R];F&&(console.log("handleValueAliasesChange",I),o(m,F.id,{valueAliases:I}))},[m,p,o]),S=j.useCallback(R=>{if(!m)return;if(p("metrics").length===0){Fe.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(m,{comparisonType:R})},[m,r,p]),N=j.useCallback(R=>{m&&r(m,{showTrendline:R})},[m,r]),_=j.useCallback(R=>{m&&r(m,{trendlineWindow:R})},[m,r]),E=j.useCallback(R=>{m&&r(m,{trendlineGranularity:R})},[m,r]),k=j.useCallback(R=>{m&&r(m,{targetValue:R})},[m,r]),M=j.useCallback(R=>{var U;if(!m)return;const I=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],L=bCe(R,I,{joinPlan:(U=e==null?void 0:e.config)==null?void 0:U.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!L.isValid){L.showError&&uU();return}const F=vCe(R,I,h);if(!F){Fe.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const V=Pee(R,F,h);if(!V.isValid){Fe.error("Invalid Field Type",{description:V.reason,position:"top-center",duration:3e3});return}const $=p(F);if(dU(R,$))return;const P=mU(R,F,$);if(P){const B=[...$,P];g(F,B),F==="metrics"&&Oee(h,e==null?void 0:e.config,r,m,B)}},[m,e==null?void 0:e.config,p,g,t,n,h,r]),T=j.useCallback((R,I)=>{if(!m)return;const F=p(R)[I];if(F){if(R!=="sortBy"){const V=p("sortBy"),$=V.filter(P=>!(P.name===F.name&&P.qualifiedEntityName===F.qualifiedEntityName));$.length!==V.length&&r(m,{sortByColumns:$})}switch(R){case"groupBy":l(m,F.id);break;case"metrics":u(m,F.id);break;case"pivotBy":d(m,F.id);break;case"sortBy":f(m,F.id);break}}},[m,p,l,u,d,f,r]);return{getFieldsForContainer:p,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:C,removeField:T,handleFieldClick:M,handleKpiComparisonTypeChange:S,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:_,handleKpiTrendlineGranularityChange:E,handleKpiTargetValueChange:k,cardType:h}};function Vx(e,t){var ke,$e,He,Ie,st;const{tokenProps:n}=Ge(),r=Qs(),s=Ge().authToken||e,o=Ee(je=>je.selectedConnectionId),i=Ee(je=>je.card),{queryKey:a}=upe(i),l=Ee(je=>je.selectedDatamodelId),u=Ee(je=>je.isDevMode),d=Ee(je=>je.selectedDatabaseName),f=Ee(je=>je.selectedSchemaName),h=Ee(je=>je.selectedTableName),m=Ee(je=>je.actions.setSelectedConnectionId),p=Ee(je=>je.actions.setSelectedDatamodelId),g=Ee(je=>je.actions.setSelectedDatabaseName),b=Ee(je=>je.actions.setSelectedSchemaName),x=Ee(je=>je.actions.setSelectedTableName);Ee(je=>je.actions.setCardSql);const{setQueryConfig:y}=lr();function v(je){var It;return o&&je==="API"?!1:o&&je==="S3"?!0:!(!o||!d||d==="NA"||((It=E==null?void 0:E.capabilities)==null?void 0:It.path.includes("schema"))&&!f)}function w(je){return o&&je?!(je==="API"||je==="S3"):!1}const{refetchConnections:C,connectionsData:S,isConnectionsLoading:N,isConnectionsError:_,selectedConnection:E}=Pi(e),{refetch:k,data:M,isLoading:T,isError:O}=cn({queryKey:["models",o],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),R=E==null?void 0:E.type,I=(E==null?void 0:E.type)==="API"||(E==null?void 0:E.type)==="S3",{data:L,isLoading:F,isFetching:V,isError:$,refetch:P}=cn({queryKey:["databases",o],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(R)}),{data:U,isLoading:B,isFetching:A,isError:Y,refetch:z}=cn({queryKey:["schemas",o,d],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!I&&d!=="NA"}),{data:q,isLoading:W,isFetching:H,isError:G,refetch:K}=cn({queryKey:["tables",o,d,f],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(R)}),{columns:te,isColumnsLoading:Z,isColumnsFetching:ee,isColumnsError:se,refetchColumns:ce}=pU(e);j.useEffect(()=>{(R==="S3"||R==="API")&&(g(""),b(""),p(""),R==="API"&&x("api"))},[R,x,g,b,p]);const re=(E==null?void 0:E.type)==="API"?(ke=E==null?void 0:E.type)==null?void 0:ke.toLowerCase():h||"",fe=I?"":f||"";function Ce(je){x(je),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function ie(je){b(je),x("")}function pe(je){g(je==="none"?"":je),b(""),x(""),je!=="none"&&je!==""&&p("")}function ue(je){m(je)}function ve(je){p(je==="none"?"":je),je!=="none"&&je!==""&&g("")}L&&(($e=L==null?void 0:L.databases)==null?void 0:$e.length)>0,U&&((He=U==null?void 0:U.schemas)==null?void 0:He.length)>0;const Se=S==null?void 0:S.connections.map(je=>({id:je.id,name:je.name,type:je.type})),Qe=(Ie=M==null?void 0:M.datamodels)==null?void 0:Ie.map(je=>({id:je.id,name:je.name})),Ke=L==null?void 0:L.databases.map(je=>({id:je.database_name,name:je.database_name})),le=U==null?void 0:U.schemas.map(je=>({id:je.schema_name,name:je.schema_name})),xe=q==null?void 0:q.tables.map(je=>({id:je.table_name,name:je.table_name})),Le=(st=M==null?void 0:M.datamodels.find(je=>je.id===l))==null?void 0:st.name,me=nv({schemaName:fe,tableName:re,modelName:Le,connectionType:R,databaseName:d||""});return{connectionItems:Se,selectedConnectionId:o,selectedConnection:E,isConnectionsLoading:N,isConnectionsError:_,modelItems:Qe,selectedDatamodelId:l,selectedDatamodelName:Le,isModelsLoading:T,isModelsError:O,selectedDatabaseName:d,databaseItems:Ke,isDatabasesLoadingOrFetching:F||V,isDatabaseError:$,schemaItems:le,selectedSchemaName:f,isSchemaLoadingOrFetching:B||A,isSchemaError:Y,tableItems:xe,selectedTableName:h,isTableLoadingOrFetching:W||H,isTableError:G,columns:te,isColumnsLoadingOrFetching:Z||ee,isColumnsError:se,isNonDbConnection:I,connectionType:R,tableName:re,formattedTableName:me,schemaName:fe,refetchConnections:C,refetchModels:k,refetchDatabases:P,refetchSchemas:z,refetchTables:K,refetchColumns:ce,handleConnectionChange:ue,handleDatamodelChange:ve,handleDatabaseChange:pe,handleSchemaChange:ie,handleTableChange:Ce}}function wy(e){return`${e}-${jr()}`}function TL(e,t){const n=Yo(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function lJe(e,t){const n=Yo(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function VI(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 $ee(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Lee(){const e=Ee(S=>S.sqlGen),t=Ee(S=>S.isDevMode),n=Ee(S=>S.card.dataSource),r=Ee(S=>{var N,_;return(_=(N=S.card)==null?void 0:N.queryConfig)==null?void 0:_.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=VI(n),a=$ee(n),l=Ee(S=>S.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=lr(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Vx(),y=S=>({column_name:S.name,data_type:S.dataType,label:S.label,description:S.description});return{handleDevModeFieldClick:S=>{var _;if(!t)return;const N=y(S);if(t&&a&&s){const E=O_(N,e);m(E);const k=(_=b==null?void 0:b.find(T=>T.id===l))==null?void 0:_.name,M=P_(E,fi(o||""),fi(s),k||"",g,i||"");M&&(f(M),h(!0))}else if(!t){if(Ab(N.data_type))if(r&&r.length>0){const E={...N,role:"groupby",id:wy(N.column_name),name:N.column_name,type:N.data_type};d(E)}else{const E={...N,role:"metric",id:wy(N.column_name),name:N.column_name,label:TL(N.column_name,"COUNT"),type:N.data_type,aggregate:"COUNT"};u(E)}if(Si(N.data_type)){const E={...N,role:"groupby",id:wy(N.column_name),name:N.column_name,type:N.data_type,label:lJe(N.column_name,"month"),granularity:"month"};d(E)}if(wi(N.data_type)){const E={...N,role:"metric",id:wy(N.column_name),name:N.column_name,label:TL(N.column_name,"SUM"),type:N.data_type,aggregate:"SUM"};u(E)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=nv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});p(!1);const N=g==="MSSQL"?`SELECT top 10 * FROM ${S}`:`SELECT * FROM ${S} LIMIT 10`;f(N),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=nv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${S}`),h(!0)},isNumberField:S=>wi(S.dataType)}}function cJe({columnName:e,database:t,schemaName:n,tableName:r,connectionType:s,datamodelId:o,modelName:i,field:a}){const l=fi(e),u=fi(t||""),d=fi(n||""),f=fi(r);let h=Jw({schemaName:d,tableName:f,connectionType:s,databaseName:u}),m=`${h}.${l}`;return o&&o!=="none"&&i&&(m=`${Eg}.${i}.${l}`,h=`${Eg}.${i}`),a!=null&&a.qualifiedFieldName&&(m=a.qualifiedFieldName,h=a.qualifiedFieldName.split(".").slice(0,-1).join(".")),{qualifiedColumnName:m,qualifiedTableName:h,formattedColumnName:l,formattedTableName:f,formattedDatabase:u,formattedSchemaName:d}}function zee(){const e=Ee(p=>p.selectedConnectionId),t=Ee(p=>p.selectedDatamodelId),n=Ee(p=>p.selectedDatabaseName),r=Ee(p=>p.selectedSchemaName),s=Ee(p=>p.selectedTableName),o=Q(p=>p.dashboard.filters)||[],i=Q(p=>p.selectedSheetId),a=Q(p=>p.actions.addFilter),l=Q(p=>p.actions.removeFilter),{removeFilterValues:u}=Gt(),{modelItems:d,tableName:f,connectionType:h}=Vx();function m(p,g="sheet",b){var _;const x=(_=d==null?void 0:d.find(E=>E.id===t))==null?void 0:_.name,{qualifiedColumnName:y,qualifiedTableName:v,formattedColumnName:w,formattedTableName:C,formattedDatabase:S}=cJe({columnName:p.column_name,database:n,schemaName:r,tableName:f,connectionType:h,datamodelId:t,modelName:x,field:b});let N;if(g==="sheet"&&i?N=Kke(o,y,C,n||"",S,i):N=o==null?void 0:o.find(E=>E.column===y&&E.table===C&&(E.database===S||E.database===n)),N)u(N.id),l(N.id);else{const E=jr(),k=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:E,column:y,title:p.label||p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:k,sql:NE(p.data_type,v,w)}),E):(a({id:E,location:g,column:y,title:p.label||p.column_name,dataType:p.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:k,sql:NE(p.data_type,v,(b==null?void 0:b.qualifiedFieldName)||w)}),E)}}return{assignFilter:m}}function uJe({column:e}){const[t,n]=j.useState(!1),r=Ee(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=VI(r),a=Ee(x=>x.selectedDatamodelId),l=Ee(x=>x.sqlGen),{modelItems:u,connectionType:d}=Vx(),f=Ee(x=>x.actions.setSqlGen),h=Ee(x=>x.actions.setCardSql),m=Ee(x=>x.actions.setRunSql),p=$ee(r);function g(x,y){var S;if(!p||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=O_(x,l,y),w=(S=u==null?void 0:u.find(N=>N.id===a))==null?void 0:S.name;f(v);const C=P_(v,fi(o||""),fi(s),w||"",d,i||"");C&&(h(C),m(!0)),n(!1)}function b(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>g(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>g(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>g(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>g(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>g(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return p?c.jsxs(Pm,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(Om,{asChild:!0,children:c.jsx(om,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(rf,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function dJe({field:e,fieldState:t}){return c.jsxs("div",{className:"w-64 bg-background p-0",children:[c.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[c.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),c.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&c.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&c.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:c.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),c.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:c.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function fJe({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s}){const o=Ee(q=>q.isDevMode),i=t==="filter"||t==="inline-filter",a=o||i||(n==null?void 0:n.state)==="unreachable"&&!i,l=Q(q=>q.dashboard.filters),u=Q(q=>q.selectedSheetId),d=Q(q=>q.actions.removeFilter),{removeFilterValues:f}=Gt(),{assignFilter:h}=zee(),m=t==="filter"?Jc(l,u):l,p=t==="filter"?m==null?void 0:m.find(q=>{var W;return q.title===e.name||((W=q.column)==null?void 0:W.includes(e.name))}):void 0,g=!!p,b=t==="inline-filter"&&(s==null?void 0:s.some(q=>q.column===e.qualifiedFieldName||q.column===e.name)),x=g||b,y=p&&i?l==null?void 0:l.find(q=>q.id===p.id):void 0,v=y&&(y.applyToSheetIds&&y.applyToSheetIds.length>1||y.excludeSheetIds&&y.excludeSheetIds.length>0||!y.applyToSheetIds&&!y.excludeSheetIds&&!y.sheetId);i&&x&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:x,activeFilterOnSheet:p?{id:p.id,title:p.title,column:p.column,applyToSheetIds:p.applyToSheetIds,excludeSheetIds:p.excludeSheetIds}:null,activeFilterForField:y?{id:y.id,title:y.title,column:y.column,applyToSheetIds:y.applyToSheetIds,excludeSheetIds:y.excludeSheetIds}:null,isMultiSheetFilter:v,selectedSheetId:u});const[w,C]=j.useState(!1),[S,N]=j.useState(null),{attributes:_,listeners:E,setNodeRef:k,transform:M,transition:T,isDragging:O}=PS({id:e.id,disabled:a}),[R,I]=j.useState(!1),L=Ee(q=>q.card),{handleFieldClick:F}=Fee(L),{handleDevModeFieldClick:V,isNumberField:$}=Lee(),P=()=>{y&&(console.log("[SourceField] Removing multi-sheet filter:",y.id),f(y.id),d(y.id)),N(null),C(!1)},U=()=>{if(t==="inline-filter"&&r){r(e);return}if(t==="filter"){const q={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};x&&v?(N({column:q,field:e}),C(!0)):h(q,"sheet",e)}else o?V(e):F(e)},B={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},A={transform:Mi.Transform.toString(M),transition:T},z=(()=>{if(!n||i)return{};const W={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...W},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...W},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...W}}[n.state]||W})();return c.jsxs("div",{ref:k,style:A,...a?{}:_,...a?{}:E,className:X("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",O&&"scale-95 opacity-50",!O&&"border",z.borderColor||"border-transparent",z.bgColor||"",z.hoverBorderColor,z.hoverBgColor||"hover:bg-muted",z.opacity,z.cursor,g&&"border-accent-foreground/20 bg-accent",b&&"border-primary/20 bg-primary/10",{"cursor-pointer":o||i,"cursor-grab active:cursor-grabbing":!a&&!o&&!i}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:U,children:[lb(e.dataType),c.jsx(On,{children:c.jsxs(un,{children:[c.jsx(dn,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${R?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(pn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(dJe,{field:e,fieldState:n})})]})}),o&&!i&&$(e)&&c.jsx("div",{onClick:q=>q.stopPropagation(),children:c.jsx(uJe,{column:B})})]}),R&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(vo,{className:"",children:c.jsxs(ji,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Y8,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.label||e.name})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Zae,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Oe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx(Gb,{open:w,onOpenChange:C,children:c.jsxs(bm,{children:[c.jsxs(xm,{children:[c.jsx(vm,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(wm,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(ym,{children:[c.jsx(Cm,{children:"Cancel"}),c.jsx(Sm,{onClick:P,children:"Remove Filter"})]})]})})]})}const hJe="SEMAPHOR_CALCULATED_FIELD",mJe=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","Week of MMM DD, YYYY","Week of MMMM DD, YYYY","YYYY-WW","MMM YYYY","MMMM YYYY","YYYY-MM","MM/YYYY","YYYY MMM","Q1 YYYY","YYYY Q1","1st Quarter YYYY","YYYY-Q1","Quarter 1, YYYY","YYYY","YY","custom"];function Bee(e){return!!e.expression}function pJe(e){return!!e.expression}function gJe(e){return!!e.expression}var Vee=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(Vee||{}),_l="Accordion",bJe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[HI,xJe,yJe]=d1(_l),[oC]=_r(_l,[yJe,MZ]),UI=MZ(),Hee=j.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(HI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(CJe,{...o,ref:t}):c.jsx(SJe,{...s,ref:t})})});Hee.displayName=_l;var[Uee,vJe]=oC(_l),[Wee,wJe]=oC(_l,{collapsible:!1}),SJe=j.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=zr({prop:n,defaultProp:r,onChange:s});return c.jsx(Uee,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:j.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(Wee,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(qee,{...i,ref:t})})})}),CJe=j.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i=[],a]=zr({prop:n,defaultProp:r,onChange:s}),l=j.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=j.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(Uee,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(Wee,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(qee,{...o,ref:t})})})}),[NJe,iC]=oC(_l),qee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=j.useRef(null),l=bt(a,t),u=xJe(n),f=qd(s)==="ltr",h=De(e.onKeyDown,m=>{var _;if(!bJe.includes(m.key))return;const p=m.target,g=u().filter(E=>{var k;return!((k=E.ref.current)!=null&&k.disabled)}),b=g.findIndex(E=>E.ref.current===p),x=g.length;if(b===-1)return;m.preventDefault();let y=b;const v=0,w=x-1,C=()=>{y=b+1,y>w&&(y=v)},S=()=>{y=b-1,y<v&&(y=w)};switch(m.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?C():S());break;case"ArrowDown":o==="vertical"&&C();break;case"ArrowLeft":o==="horizontal"&&(f?S():C());break;case"ArrowUp":o==="vertical"&&S();break}const N=y%x;(_=g[N].ref.current)==null||_.focus()});return c.jsx(NJe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(HI.Slot,{scope:n,children:c.jsx(Ue.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Uw="AccordionItem",[jJe,WI]=oC(Uw),Yee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=iC(Uw,n),i=vJe(Uw,n),a=UI(n),l=or(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(jJe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(IZ,{"data-orientation":o.orientation,"data-state":Jee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Yee.displayName=Uw;var Gee="AccordionHeader",Kee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=iC(_l,n),o=WI(Gee,n);return c.jsx(Ue.h3,{"data-orientation":s.orientation,"data-state":Jee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Kee.displayName=Gee;var g_="AccordionTrigger",Zee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=iC(_l,n),o=WI(g_,n),i=wJe(g_,n),a=UI(n);return c.jsx(HI.ItemSlot,{scope:n,children:c.jsx(E$e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Zee.displayName=g_;var Xee="AccordionContent",Qee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=iC(_l,n),o=WI(Xee,n),i=UI(n);return c.jsx(_$e,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});Qee.displayName=Xee;function Jee(e){return e?"open":"closed"}var kJe=Hee,EJe=Yee,_Je=Kee,ete=Zee,tte=Qee;const nte=kJe,qI=D.forwardRef(({className:e,...t},n)=>c.jsx(EJe,{ref:n,className:X("border-b",e),...t}));qI.displayName="AccordionItem";const YI=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(_Je,{className:"flex",children:c.jsxs(ete,{ref:r,className:X("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,c.jsx(Ks,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));YI.displayName=ete.displayName;const GI=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(tte,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:X("pb-4 pt-0",e),children:t})}));GI.displayName=tte.displayName;function rte({context:e="editor",onFieldSelect:t,inlineFilters:n}={}){var I,L,F,V;const[r,s]=j.useState(""),[o,i]=j.useState("all");Ee($=>$.isDevMode);const a=Ee($=>$.card.dataSource),l=Ee($=>$.card.config),u=Ee($=>$.card),{autoJoinMetadata:d}=pa(u),{columns:f=[],columnGroups:h=[],isLoading:m,error:p}=zM(),g=(a==null?void 0:a.mode)==="semanticDomain"?a.semanticDomainId:void 0,{data:b}=BI(g),x=[...(l==null?void 0:l.groupByColumns)||[],...(l==null?void 0:l.metricColumns)||[]];(L=(I=l==null?void 0:l.joinPlan)==null?void 0:I.baseEntity)==null||L.name,(V=(F=d==null?void 0:d.resolvedJoinPlan)==null?void 0:F.baseEntity)==null||V.name,Lee();const y=f.filter($=>$.name.toLowerCase().includes(r.toLowerCase())||$.dataType.toLowerCase().includes(r.toLowerCase())||$.label&&$.label.toLowerCase().includes(r.toLowerCase())||$.qualifiedEntityName&&$.qualifiedEntityName.toLowerCase().includes(r.toLowerCase())),v=$=>{if($.role==="metric"&&Bee($)||$.role==="groupby"&&$.expression)return"calculated";if($.dataType==="number"||$.dataType==="integer"||$.dataType==="float"||$.dataType==="decimal"||$.dataType==="currency")return"metrics";const P=Ir($.dataType);return["date","string","boolean"].includes(P)?"dimensions":P==="number"?"metrics":"dimensions"},C=(o==="all"?y:y.filter($=>v($)===o)).reduce(($,P)=>{const U=P.qualifiedEntityName||"Other Fields";return $[U]||($[U]={label:q_(P.entityName),fields:[]}),$[U].fields.push(P),$},{}),N=Object.keys(C),_=y.filter($=>v($)==="dimensions").length,E=y.filter($=>v($)==="metrics").length,k=y.filter($=>v($)==="calculated").length,M=y.length>0&&e!=="inline-filter",T=e==="inline-filter"?"w-full":"w-[290px]";if(m)return c.jsx("div",{className:X("flex h-full flex-col items-center justify-center py-8",T),children:c.jsx(Rc,{size:"md",color:"muted","aria-label":"Loading data"})});if(p)return c.jsxs("div",{className:X("flex h-full flex-col items-center justify-center py-8",T),children:[c.jsx(al,{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:p.message||"Failed to load column data"})]});if(!a||!a.selectedEntities||a.selectedEntities.length===0)return c.jsxs("div",{className:X("flex flex-col items-center justify-center py-8 text-center",T),children:[c.jsx(al,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:e==="filter"||e==="inline-filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]});const O=e==="inline-filter"?"px-3 pb-3":"px-6 pb-6",R=e==="inline-filter"?"overflow-hidden":"";return c.jsxs("div",{className:X("mt-2 flex h-full w-full grow flex-col gap-2",O,R),children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[f.length>0&&c.jsxs("div",{className:"relative",children:[c.jsx(va,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(Nn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:r,onChange:$=>s($.target.value)}),r&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>s(""),type:"button",children:c.jsx(yt,{className:"size-3.5"})})]}),M&&c.jsx(As,{defaultValue:"all",value:o,onValueChange:$=>i($),className:"mb-4",children:c.jsxs(cs,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(qt,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:y.length})]}),c.jsxs(qt,{value:"dimensions",className:"text-xs",children:[c.jsx(a1,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:_})]}),c.jsxs(qt,{value:"metrics",className:"text-xs",children:[c.jsx(sm,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:E})]}),c.jsxs(qt,{value:"calculated",className:"text-xs",children:[c.jsx(eD,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:k})]})]})})]}),c.jsxs(Cl,{className:"min-h-0 overflow-auto",children:[c.jsx(nte,{type:"multiple",defaultValue:N,className:"space-y-2",children:Object.entries(C).map(([$,P])=>{const U=h.find(B=>B.entityName===$)||{entityName:$,label:P.label};return c.jsxs(qI,{value:$,className:"border-none",children:[c.jsx(YI,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:U.label||U.entityName,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:U.label||U.entityName}),c.jsx(Oe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:P.fields.length})]})}),c.jsx(GI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:P.fields.map(B=>{const A=BM(B,{joinabilityMap:(b==null?void 0:b.joinabilityMap)||null,selectedFields:x,cardConfig:l,autoJoinMetadata:d});return c.jsx(fJe,{field:B,context:e,fieldState:A,onFieldSelect:t,inlineFilters:e==="inline-filter"?n:void 0},B.id)})})})]},$)})}),Object.keys(C).length===0&&f.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:e==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(C).length===0&&f.length>0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(Zo,{orientation:"horizontal"}),c.jsx(Zo,{orientation:"vertical"})]})]})}function ste({context:e="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(rte,{context:e})," "]})}function ote(){const e=Ee(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=lr();j.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=VI(e),d=(m=e.selectedEntities)==null?void 0:m[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function DJe(){ote();const e=Q(l=>l.selectedSheetId),t=Q(l=>l.selectedFrameId),n=Q(l=>l.dashboard),r=Q(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Gt(),{setCard:o}=lr(),i=Ee(l=>l.card.dataSource);return j.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(m=>m.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function MJe(){const e=Q(n=>n.actions.setShowFilters),{hasEntities:t}=DJe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(de,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsx(oe,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(NZ,{})})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(al,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow overflow-y-auto",children:c.jsx(IS,{collisionDetection:DS,children:c.jsx(AS,{items:[],strategy:YR,children:c.jsx(ste,{context:"filter"})})})})]})}function TJe(){const e=Q(r=>r.dashboard.filters),t=Q(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:X("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(AR,{filter:r}),c.jsx(Cx,{filter:r})]},r.id))}):null}function RJe(){const e=Q(r=>r.showFilters),t=Q(r=>r.isVisualEditing),n=Q(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:X("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[c.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&c.jsx(TJe,{}),c.jsx(Ree,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(MJe,{})})]})}const IJe=j.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-hLb7d4n_.js"))),AJe=j.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-C8ZQJfdk.js"))),PJe=j.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-CSK4231d.js"))),OJe=j.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-Di5Mg69T.js")).then(e=>({default:e.ResourceManagementPanel})));function FJe({showControls:e=!1,showFooter:t=!0,...n}){const r=Q(l=>l.isDashboardPanelOpen),s=Q(l=>l.isVisualEditing),o=Q(l=>l.showDashboardJSON),i=Q(l=>l.actions.setIsDashboardPanelOpen),{preferences:a}=n;return c.jsx(Da,{FallbackComponent:SS,children:c.jsxs(J_,{dashboardProps:n,children:[c.jsx(Cfe,{}),c.jsx(zI,{children:c.jsxs(Iee,{preferences:a,children:[o&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(PJe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(IJe,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(OJe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(sT,{...n,type:"dashboard",children:[s&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(AJe,{})}),c.jsx(RJe,{})]})})]})]})]})})]})})}var $Je=Object.defineProperty,LJe=(e,t,n)=>t in e?$Je(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Sy=(e,t,n)=>LJe(e,typeof t!="symbol"?t+"":t,n);const zJe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},BJe={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}},VJe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},HJe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},UJe={stringify:e=>e,parse:e=>e},n2={string:UJe,number:HJe,boolean:zJe,function:BJe,json:VJe};function WJe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const Cy=Symbol.for("r2wc.render"),Ny=Symbol.for("r2wc.connected"),yu=Symbol.for("r2wc.context"),Aa=Symbol.for("r2wc.props");function qJe(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const m of i){l[m]=Array.isArray(t.props)?"string":t.props[m];const p=WJe(m);d[m]=p,f[p]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),Sy(this,o,!0),Sy(this,s),Sy(this,r,{}),Sy(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Aa].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=l[p],y=x?n2[x]:null;y!=null&&y.parse&&b&&(this[Aa][p]=y.parse(b,g,this))}for(const p of a)this[Aa][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[Ny]=!0,this[Cy]()}disconnectedCallback(){this[Ny]=!1,this[yu]&&n.unmount(this[yu]),delete this[yu]}attributeChangedCallback(p,g,b){const x=f[p],y=l[x],v=y?n2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[Aa][x]=v.parse(b,p,this),this[Cy]())}[(o=Ny,s=yu,r=Aa,Cy)](){this[Ny]&&(this[yu]?n.update(this[yu],this[Aa]):this[yu]=n.mount(this.container,e,this[Aa]))}}for(const m of i){const p=d[m],g=l[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[Aa][m]},set(b){this[Aa][m]=b;const x=g?n2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[Cy]()}})}return h}function YJe(e,t,n){const r=p2(e),s=j.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function GJe({root:e,ReactComponent:t},n){const r=j.createElement(t,n);e.render(r)}function KJe({root:e}){e.unmount()}function ZJe(e,t={}){return qJe(e,t,{mount:YJe,update:GJe,unmount:KJe})}const XJe={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},QJe=ZJe(Aee,{props:XJe});function JJe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function RL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function IL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?RL(Object(n),!0).forEach(function(r){JJe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):RL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function eet(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o<r.length;o++)s=r[o],!(t.indexOf(s)>=0)&&(n[s]=e[s]);return n}function tet(e,t){if(e==null)return{};var n=eet(e,t),r,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(s=0;s<o.length;s++)r=o[s],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function net(e,t){return ret(e)||set(e,t)||oet(e,t)||iet()}function ret(e){if(Array.isArray(e))return e}function set(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var n=[],r=!0,s=!1,o=void 0;try{for(var i=e[Symbol.iterator](),a;!(r=(a=i.next()).done)&&(n.push(a.value),!(t&&n.length===t));r=!0);}catch(l){s=!0,o=l}finally{try{!r&&i.return!=null&&i.return()}finally{if(s)throw o}}return n}}function oet(e,t){if(e){if(typeof e=="string")return AL(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return AL(e,t)}}function AL(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function iet(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1072
1072
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function aet(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function PL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function OL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?PL(Object(n),!0).forEach(function(r){aet(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):PL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function cet(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(r){return t.reduceRight(function(s,o){return o(s)},r)}}function Zp(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(s,a))}}}function Ww(e){return{}.toString.call(e).includes("Object")}function uet(e){return!Object.keys(e).length}function Nb(e){return typeof e=="function"}function det(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function fet(e,t){return Ww(t)||vc("changeType"),Object.keys(t).some(function(n){return!det(e,n)})&&vc("changeField"),t}function het(e){Nb(e)||vc("selectorType")}function met(e){Nb(e)||Ww(e)||vc("handlerType"),Ww(e)&&Object.values(e).some(function(t){return!Nb(t)})&&vc("handlersType")}function pet(e){e||vc("initialIsRequired"),Ww(e)||vc("initialType"),uet(e)&&vc("initialContent")}function get(e,t){throw new Error(e[t]||e.default)}var bet={initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"},vc=Zp(get)(bet),jy={changes:fet,selector:het,handler:met,initial:pet};function xet(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};jy.initial(e),jy.handler(t);var n={current:e},r=Zp(wet)(n,t),s=Zp(vet)(n),o=Zp(jy.changes)(e),i=Zp(yet)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return jy.selector(u),u(n.current)}function l(u){cet(r,s,o,i)(u)}return[a,l]}function yet(e,t){return Nb(t)?t(e.current):t}function vet(e,t){return e.current=OL(OL({},e.current),t),t}function wet(e,t,n){return Nb(t)?t(e.current):Object.keys(n).forEach(function(r){var s;return(s=t[r])===null||s===void 0?void 0:s.call(t,e.current[r])}),n}var Cet={create:xet},Net={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs"}};function jet(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(s,a))}}}function ket(e){return{}.toString.call(e).includes("Object")}function Eet(e){return e||FL("configIsRequired"),ket(e)||FL("configType"),e.urls?(_et(),{paths:{vs:e.urls.monacoBase}}):e}function _et(){console.warn(ite.deprecation)}function Det(e,t){throw new Error(e[t]||e.default)}var ite={configIsRequired:"the configuration object is required",configType:"the configuration object should be an object",default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
1073
1073
  You are using deprecated way of configuration.
1074
1074
 
@@ -1078,4 +1078,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1078
1078
  monaco.config({ paths: { vs: '...' } })
1079
1079
 
1080
1080
  For more please check the link https://github.com/suren-atoyan/monaco-loader#config
1081
- `},FL=jet(Det)(ite),Met={config:Eet},Tet=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return function(s){return n.reduceRight(function(o,i){return i(o)},s)}};function ate(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],ate(e[n],t[n]))}),IL(IL({},e),t)}var Ret={type:"cancelation",msg:"operation is manually canceled"};function r2(e){var t=!1,n=new Promise(function(r,s){e.then(function(o){return t?s(Ret):r(o)}),e.catch(s)});return n.cancel=function(){return t=!0},n}var Iet=Cet.create({config:Net,isInitialized:!1,resolve:null,reject:null,monaco:null}),lte=net(Iet,2),Hx=lte[0],aC=lte[1];function Aet(e){var t=Met.config(e),n=t.monaco,r=tet(t,["monaco"]);aC(function(s){return{config:ate(s.config,r),monaco:n}})}function Pet(){var e=Hx(function(t){var n=t.monaco,r=t.isInitialized,s=t.resolve;return{monaco:n,isInitialized:r,resolve:s}});if(!e.isInitialized){if(aC({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),r2(s2);if(window.monaco&&window.monaco.editor)return cte(window.monaco),e.resolve(window.monaco),r2(s2);Tet(Oet,$et)(Let)}return r2(s2)}function Oet(e){return document.body.appendChild(e)}function Fet(e){var t=document.createElement("script");return e&&(t.src=e),t}function $et(e){var t=Hx(function(r){var s=r.config,o=r.reject;return{config:s,reject:o}}),n=Fet("".concat(t.config.paths.vs,"/loader.js"));return n.onload=function(){return e()},n.onerror=t.reject,n}function Let(){var e=Hx(function(n){var r=n.config,s=n.resolve,o=n.reject;return{config:r,resolve:s,reject:o}}),t=window.require;t.config(e.config),t(["vs/editor/editor.main"],function(n){cte(n),e.resolve(n)},function(n){e.reject(n)})}function cte(e){Hx().monaco||aC({monaco:e})}function zet(){return Hx(function(e){var t=e.monaco;return t})}var s2=new Promise(function(e,t){return aC({resolve:e,reject:t})}),qw={config:Aet,init:Pet,__getMonacoInstance:zet},Bet={wrapper:{display:"flex",position:"relative",textAlign:"initial"},fullWidth:{width:"100%"},hide:{display:"none"}},o2=Bet,Vet={container:{display:"flex",height:"100%",width:"100%",justifyContent:"center",alignItems:"center"}},Het=Vet;function Uet({children:e}){return j.createElement("div",{style:Het.container},e)}var Wet=Uet,qet=Wet;function Yet({width:e,height:t,isEditorReady:n,loading:r,_ref:s,className:o,wrapperProps:i}){return j.createElement("section",{style:{...o2.wrapper,width:e,height:t},...i},!n&&j.createElement(qet,null,r),j.createElement("div",{ref:s,style:{...o2.fullWidth,...!n&&o2.hide},className:o}))}var Get=Yet,ute=j.memo(Get);function Ket(e){j.useEffect(e,[])}var KI=Ket;function Zet(e,t,n=!0){let r=j.useRef(!0);j.useEffect(r.current||!n?()=>{r.current=!1}:e,t)}var ho=Zet;function Cg(){}function Gf(e,t,n,r){return Xet(e,r)||Qet(e,t,n,r)}function Xet(e,t){return e.editor.getModel(dte(e,t))}function Qet(e,t,n,r){return e.editor.createModel(t,n,r?dte(e,r):void 0)}function dte(e,t){return e.Uri.parse(t)}function Jet({original:e,modified:t,language:n,originalLanguage:r,modifiedLanguage:s,originalModelPath:o,modifiedModelPath:i,keepCurrentOriginalModel:a=!1,keepCurrentModifiedModel:l=!1,theme:u="light",loading:d="Loading...",options:f={},height:h="100%",width:m="100%",className:p,wrapperProps:g={},beforeMount:b=Cg,onMount:x=Cg}){let[y,v]=j.useState(!1),[w,C]=j.useState(!0),S=j.useRef(null),N=j.useRef(null),_=j.useRef(null),E=j.useRef(x),k=j.useRef(b),M=j.useRef(!1);KI(()=>{let I=qw.init();return I.then(L=>(N.current=L)&&C(!1)).catch(L=>(L==null?void 0:L.type)!=="cancelation"&&console.error("Monaco initialization: error:",L)),()=>S.current?R():I.cancel()}),ho(()=>{if(S.current&&N.current){let I=S.current.getOriginalEditor(),L=Gf(N.current,e||"",r||n||"text",o||"");L!==I.getModel()&&I.setModel(L)}},[o],y),ho(()=>{if(S.current&&N.current){let I=S.current.getModifiedEditor(),L=Gf(N.current,t||"",s||n||"text",i||"");L!==I.getModel()&&I.setModel(L)}},[i],y),ho(()=>{let I=S.current.getModifiedEditor();I.getOption(N.current.editor.EditorOption.readOnly)?I.setValue(t||""):t!==I.getValue()&&(I.executeEdits("",[{range:I.getModel().getFullModelRange(),text:t||"",forceMoveMarkers:!0}]),I.pushUndoStop())},[t],y),ho(()=>{var I,L;(L=(I=S.current)==null?void 0:I.getModel())==null||L.original.setValue(e||"")},[e],y),ho(()=>{let{original:I,modified:L}=S.current.getModel();N.current.editor.setModelLanguage(I,r||n||"text"),N.current.editor.setModelLanguage(L,s||n||"text")},[n,r,s],y),ho(()=>{var I;(I=N.current)==null||I.editor.setTheme(u)},[u],y),ho(()=>{var I;(I=S.current)==null||I.updateOptions(f)},[f],y);let T=j.useCallback(()=>{var F;if(!N.current)return;k.current(N.current);let I=Gf(N.current,e||"",r||n||"text",o||""),L=Gf(N.current,t||"",s||n||"text",i||"");(F=S.current)==null||F.setModel({original:I,modified:L})},[n,t,s,e,r,o,i]),O=j.useCallback(()=>{var I;!M.current&&_.current&&(S.current=N.current.editor.createDiffEditor(_.current,{automaticLayout:!0,...f}),T(),(I=N.current)==null||I.editor.setTheme(u),v(!0),M.current=!0)},[f,u,T]);j.useEffect(()=>{y&&E.current(S.current,N.current)},[y]),j.useEffect(()=>{!w&&!y&&O()},[w,y,O]);function R(){var L,F,V,$;let I=(L=S.current)==null?void 0:L.getModel();a||((F=I==null?void 0:I.original)==null||F.dispose()),l||((V=I==null?void 0:I.modified)==null||V.dispose()),($=S.current)==null||$.dispose()}return j.createElement(ute,{width:m,height:h,isEditorReady:y,loading:d,_ref:_,className:p,wrapperProps:g})}var ett=Jet;j.memo(ett);function ttt(){let[e,t]=j.useState(qw.__getMonacoInstance());return KI(()=>{let n;return e||(n=qw.init(),n.then(r=>{t(r)})),()=>n==null?void 0:n.cancel()}),e}var ntt=ttt;function rtt(e){let t=j.useRef();return j.useEffect(()=>{t.current=e},[e]),t.current}var stt=rtt,ky=new Map;function ott({defaultValue:e,defaultLanguage:t,defaultPath:n,value:r,language:s,path:o,theme:i="light",line:a,loading:l="Loading...",options:u={},overrideServices:d={},saveViewState:f=!0,keepCurrentModel:h=!1,width:m="100%",height:p="100%",className:g,wrapperProps:b={},beforeMount:x=Cg,onMount:y=Cg,onChange:v,onValidate:w=Cg}){let[C,S]=j.useState(!1),[N,_]=j.useState(!0),E=j.useRef(null),k=j.useRef(null),M=j.useRef(null),T=j.useRef(y),O=j.useRef(x),R=j.useRef(),I=j.useRef(r),L=stt(o),F=j.useRef(!1),V=j.useRef(!1);KI(()=>{let U=qw.init();return U.then(B=>(E.current=B)&&_(!1)).catch(B=>(B==null?void 0:B.type)!=="cancelation"&&console.error("Monaco initialization: error:",B)),()=>k.current?P():U.cancel()}),ho(()=>{var B,A,Y,z;let U=Gf(E.current,e||r||"",t||s||"",o||n||"");U!==((B=k.current)==null?void 0:B.getModel())&&(f&&ky.set(L,(A=k.current)==null?void 0:A.saveViewState()),(Y=k.current)==null||Y.setModel(U),f&&((z=k.current)==null||z.restoreViewState(ky.get(o))))},[o],C),ho(()=>{var U;(U=k.current)==null||U.updateOptions(u)},[u],C),ho(()=>{!k.current||r===void 0||(k.current.getOption(E.current.editor.EditorOption.readOnly)?k.current.setValue(r):r!==k.current.getValue()&&(V.current=!0,k.current.executeEdits("",[{range:k.current.getModel().getFullModelRange(),text:r,forceMoveMarkers:!0}]),k.current.pushUndoStop(),V.current=!1))},[r],C),ho(()=>{var B,A;let U=(B=k.current)==null?void 0:B.getModel();U&&s&&((A=E.current)==null||A.editor.setModelLanguage(U,s))},[s],C),ho(()=>{var U;a!==void 0&&((U=k.current)==null||U.revealLine(a))},[a],C),ho(()=>{var U;(U=E.current)==null||U.editor.setTheme(i)},[i],C);let $=j.useCallback(()=>{var U;if(!(!M.current||!E.current)&&!F.current){O.current(E.current);let B=o||n,A=Gf(E.current,r||e||"",t||s||"",B||"");k.current=(U=E.current)==null?void 0:U.editor.create(M.current,{model:A,automaticLayout:!0,...u},d),f&&k.current.restoreViewState(ky.get(B)),E.current.editor.setTheme(i),a!==void 0&&k.current.revealLine(a),S(!0),F.current=!0}},[e,t,n,r,s,o,u,d,f,i,a]);j.useEffect(()=>{C&&T.current(k.current,E.current)},[C]),j.useEffect(()=>{!N&&!C&&$()},[N,C,$]),I.current=r,j.useEffect(()=>{var U,B;C&&v&&((U=R.current)==null||U.dispose(),R.current=(B=k.current)==null?void 0:B.onDidChangeModelContent(A=>{V.current||v(k.current.getValue(),A)}))},[C,v]),j.useEffect(()=>{if(C){let U=E.current.editor.onDidChangeMarkers(B=>{var Y;let A=(Y=k.current.getModel())==null?void 0:Y.uri;if(A&&B.find(z=>z.path===A.path)){let z=E.current.editor.getModelMarkers({resource:A});w==null||w(z)}});return()=>{U==null||U.dispose()}}return()=>{}},[C,w]);function P(){var U,B;(U=R.current)==null||U.dispose(),h?f&&ky.set(o,k.current.saveViewState()):(B=k.current.getModel())==null||B.dispose(),k.current.dispose()}return j.createElement(ute,{width:m,height:p,isEditorReady:C,loading:l,_ref:M,className:g,wrapperProps:b})}var itt=ott,fte=j.memo(itt),att=fte;function ltt({card:e}){var R,I,L,F,V,$,P,U,B,A,Y;const[t,n]=j.useState(!1),[r,s]=j.useState([]),{authToken:o}=Ge(),{theme:i}=Ob(),a=V6(o==null?void 0:o.accessToken),l=Q(z=>z.themeStyle),u={mode:i||"system",colors:((I=(R=l==null?void 0:l.chart)==null?void 0:R.dataset)==null?void 0:I.backgroundColor)||[]};(L=e.customCardPreferences)!=null&&L.inputData;const{getCard:d}=pS(((F=e.customCardPreferences)==null?void 0:F.url)||""),f=((V=e.customCardPreferences)==null?void 0:V.visualType)||"single",h=Ee(z=>z.frame),{setCustomCardPreferences:m}=lr(),{data:p}=pa(e),g=Pt(z=>z.interactionStates),b=Q(z=>{var q;return(q=z.dashboard)==null?void 0:q.id}),x=Q(z=>z.dashboard.filters),y=Q(z=>z.filterValues),v=Q(z=>z.selectedSheetId),w=Q(z=>z.inlineFilterValuesMap[e.id]),C=j.useMemo(()=>UK({card:e,sheetId:v||"",inlineFilterValues:w}),[e,v,w]),{cardFilters:S,cardFilterValues:N,shouldApplyDashboardFilters:_,contextMode:E}=j.useMemo(()=>rM({card:e,interactionStates:g,currentDashboardId:b,filters:x,filterValues:y,selectedSheetId:v}),[e,g,b,x,y,v]),k=j.useCallback((z,q)=>{s(W=>({...W,[z]:q}))},[]);if(!(($=e.customCardPreferences)!=null&&$.componentName))return null;const M=d((P=e.customCardPreferences)==null?void 0:P.componentName);function T(z){n(z)}const O=Object.keys(((U=e.customCardPreferences)==null?void 0:U.dataInputCardIds)||{}).map(z=>{var H,G,K;const q=(G=(H=e.customCardPreferences)==null?void 0:H.dataInputCardIds)==null?void 0:G[z].cardId,W=(K=h==null?void 0:h.cards)==null?void 0:K.find(te=>te.id===q);return W||null});return c.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:c.jsxs(j.Suspense,{fallback:c.jsx(c.Fragment,{}),children:[M&&f==="single"&&c.jsx(M,{editing:!0,params:a,theme:u,settings:(B=e.customCardPreferences)==null?void 0:B.settings,onDataChange:k,data:(p==null?void 0:p.records)||[],filters:S,filterValues:[...N||[],...w||[]],inlineFilters:C}),M&&f==="multiple"&&c.jsxs(c.Fragment,{children:[Object.keys(((A=e.customCardPreferences)==null?void 0:A.dataInputCardIds)||{}).map(z=>{var H,G,K;const q=(G=(H=e.customCardPreferences)==null?void 0:H.dataInputCardIds)==null?void 0:G[z].cardId,W=(K=h==null?void 0:h.cards)==null?void 0:K.find(te=>te.id===q);if(W)return c.jsx(xG,{onLoadingStatus:T,onDataChange:k,dataInputIndex:z,card:W},W.id+z)}),c.jsx("div",{className:"flex flex-col gap-2",children:c.jsx(M,{theme:u,onDataChange:k,settings:O.map(z=>{var q;return(q=z==null?void 0:z.customCardPreferences)==null?void 0:q.settings}),data:O.map(z=>z!=null&&z.id?r==null?void 0:r[z.id]:[]),filters:S,filterValues:[...N||[],...w||[]],inlineFilters:C})})]})]},(Y=e.customCardPreferences)==null?void 0:Y.componentName)})}const ctt=j.memo(ltt,(e,t)=>{var n,r,s,o;return e.card.id===t.card.id&&((n=e.card.customCardPreferences)==null?void 0:n.url)===((r=t.card.customCardPreferences)==null?void 0:r.url)&&((s=e.card.customCardPreferences)==null?void 0:s.componentName)===((o=t.card.customCardPreferences)==null?void 0:o.componentName)}),hte=D.forwardRef(({className:e,...t},n)=>c.jsx(Ax,{className:X("peer inline-flex h-[22px] w-[36px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:c.jsx(QR,{className:X("pointer-events-none block size-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));hte.displayName=Ax.displayName;function mte(e,[t,n]){return Math.min(n,Math.max(t,e))}function Kf(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e==null||e(s),n===!1||!s.defaultPrevented)return t==null?void 0:t(s)}}function $L(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function utt(...e){return t=>{let n=!1;const r=e.map(s=>{const o=$L(s,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let s=0;s<r.length;s++){const o=r[s];typeof o=="function"?o():$L(e[s],null)}}}}function Bc(...e){return D.useCallback(utt(...e),e)}function pte(e,t=[]){let n=[];function r(o,i){const a=D.createContext(i),l=n.length;n=[...n,i];const u=f=>{var x;const{scope:h,children:m,...p}=f,g=((x=h==null?void 0:h[e])==null?void 0:x[l])||a,b=D.useMemo(()=>p,Object.values(p));return c.jsx(g.Provider,{value:b,children:m})};u.displayName=o+"Provider";function d(f,h){var g;const m=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,p=D.useContext(m);if(p)return p;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${o}\``)}return[u,d]}const s=()=>{const o=n.map(i=>D.createContext(i));return function(a){const l=(a==null?void 0:a[e])||o;return D.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return s.scopeName=e,[r,dtt(s,...t)]}function dtt(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(o){const i=r.reduce((a,{useScope:l,scopeName:u})=>{const f=l(o)[`__scope${u}`];return{...a,...f}},{});return D.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var gte=globalThis!=null&&globalThis.document?D.useLayoutEffect:()=>{},ftt=D[" useInsertionEffect ".trim().toString()]||gte;function htt({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[s,o,i]=mtt({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:s;{const d=D.useRef(e!==void 0);D.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const u=D.useCallback(d=>{var f;if(a){const h=ptt(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else o(d)},[a,e,o,i]);return[l,u]}function mtt({defaultProp:e,onChange:t}){const[n,r]=D.useState(e),s=D.useRef(n),o=D.useRef(t);return ftt(()=>{o.current=t},[t]),D.useEffect(()=>{var i;s.current!==n&&((i=o.current)==null||i.call(o,n),s.current=n)},[n,s]),[n,r,o]}function ptt(e){return typeof e=="function"}var gtt=D.createContext(void 0);function btt(e){const t=D.useContext(gtt);return e||t||"ltr"}function xtt(e){const t=D.useRef({value:e,previous:e});return D.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}function ytt(e){const[t,n]=D.useState(void 0);return gte(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const o=s[0];let i,a;if("borderBoxSize"in o){const l=o.borderBoxSize,u=Array.isArray(l)?l[0]:l;i=u.inlineSize,a=u.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var vtt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ux=vtt.reduce((e,t)=>{const n=wd(`Primitive.${t}`),r=D.forwardRef((s,o)=>{const{asChild:i,...a}=s,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c.jsx(l,{...a,ref:o})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function wtt(e){const t=e+"CollectionProvider",[n,r]=pte(t),[s,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=g=>{const{scope:b,children:x}=g,y=j.useRef(null),v=j.useRef(new Map).current;return c.jsx(s,{scope:b,itemMap:v,collectionRef:y,children:x})};i.displayName=t;const a=e+"CollectionSlot",l=wd(a),u=j.forwardRef((g,b)=>{const{scope:x,children:y}=g,v=o(a,x),w=Bc(b,v.collectionRef);return c.jsx(l,{ref:w,children:y})});u.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=wd(d),m=j.forwardRef((g,b)=>{const{scope:x,children:y,...v}=g,w=j.useRef(null),C=Bc(b,w),S=o(d,x);return j.useEffect(()=>(S.itemMap.set(w,{ref:w,...v}),()=>void S.itemMap.delete(w))),c.jsx(h,{[f]:"",ref:C,children:y})});m.displayName=d;function p(g){const b=o(e+"CollectionConsumer",g);return j.useCallback(()=>{const y=b.collectionRef.current;if(!y)return[];const v=Array.from(y.querySelectorAll(`[${f}]`));return Array.from(b.itemMap.values()).sort((S,N)=>v.indexOf(S.ref.current)-v.indexOf(N.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:i,Slot:u,ItemSlot:m},p,r]}var bte=["PageUp","PageDown"],xte=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],yte={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},ep="Slider",[b_,Stt,Ctt]=wtt(ep),[vte]=pte(ep,[Ctt]),[Ntt,lC]=vte(ep),wte=D.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:p,...g}=e,b=D.useRef(new Set),x=D.useRef(0),v=i==="horizontal"?jtt:ktt,[w=[],C]=htt({prop:d,defaultProp:u,onChange:M=>{var O;(O=[...b.current][x.current])==null||O.focus(),f(M)}}),S=D.useRef(w);function N(M){const T=Ttt(w,M);k(M,T)}function _(M){k(M,x.current)}function E(){const M=S.current[x.current];w[x.current]!==M&&h(w)}function k(M,T,{commit:O}={commit:!1}){const R=Ptt(o),I=Ott(Math.round((M-r)/o)*o+r,R),L=mte(I,[r,s]);C((F=[])=>{const V=Dtt(F,L,T);if(Att(V,l*o)){x.current=V.indexOf(L);const $=String(V)!==String(F);return $&&O&&h(V),$?V:F}else return F})}return c.jsx(Ntt,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:s,valueIndexToChangeRef:x,thumbs:b.current,values:w,orientation:i,form:p,children:c.jsx(b_.Provider,{scope:e.__scopeSlider,children:c.jsx(b_.Slot,{scope:e.__scopeSlider,children:c.jsx(v,{"aria-disabled":a,"data-disabled":a?"":void 0,...g,ref:t,onPointerDown:Kf(g.onPointerDown,()=>{a||(S.current=w)}),min:r,max:s,inverted:m,onSlideStart:a?void 0:N,onSlideMove:a?void 0:_,onSlideEnd:a?void 0:E,onHomeKeyDown:()=>!a&&k(r,0,{commit:!0}),onEndKeyDown:()=>!a&&k(s,w.length-1,{commit:!0}),onStepKeyDown:({event:M,direction:T})=>{if(!a){const I=bte.includes(M.key)||M.shiftKey&&xte.includes(M.key)?10:1,L=x.current,F=w[L],V=o*I*T;k(F+V,L,{commit:!0})}}})})})})});wte.displayName=ep;var[Ste,Cte]=vte(ep,{startEdge:"left",endEdge:"right",size:"width",direction:1}),jtt=D.forwardRef((e,t)=>{const{min:n,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:l,onStepKeyDown:u,...d}=e,[f,h]=D.useState(null),m=Bc(t,v=>h(v)),p=D.useRef(void 0),g=btt(s),b=g==="ltr",x=b&&!o||!b&&o;function y(v){const w=p.current||f.getBoundingClientRect(),C=[0,w.width],N=ZI(C,x?[n,r]:[r,n]);return p.current=w,N(v-w.left)}return c.jsx(Ste,{scope:e.__scopeSlider,startEdge:x?"left":"right",endEdge:x?"right":"left",direction:x?1:-1,size:"width",children:c.jsx(Nte,{dir:g,"data-orientation":"horizontal",...d,ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{const w=y(v.clientX);i==null||i(w)},onSlideMove:v=>{const w=y(v.clientX);a==null||a(w)},onSlideEnd:()=>{p.current=void 0,l==null||l()},onStepKeyDown:v=>{const C=yte[x?"from-left":"from-right"].includes(v.key);u==null||u({event:v,direction:C?-1:1})}})})}),ktt=D.forwardRef((e,t)=>{const{min:n,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:l,...u}=e,d=D.useRef(null),f=Bc(t,d),h=D.useRef(void 0),m=!s;function p(g){const b=h.current||d.current.getBoundingClientRect(),x=[0,b.height],v=ZI(x,m?[r,n]:[n,r]);return h.current=b,v(g-b.top)}return c.jsx(Ste,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:c.jsx(Nte,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{const b=p(g.clientY);o==null||o(b)},onSlideMove:g=>{const b=p(g.clientY);i==null||i(b)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:g=>{const x=yte[m?"from-bottom":"from-top"].includes(g.key);l==null||l({event:g,direction:x?-1:1})}})})}),Nte=D.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:l,...u}=e,d=lC(ep,n);return c.jsx(Ux.span,{...u,ref:t,onKeyDown:Kf(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):bte.concat(xte).includes(f.key)&&(l(f),f.preventDefault())}),onPointerDown:Kf(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus():r(f)}),onPointerMove:Kf(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f)}),onPointerUp:Kf(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),o(f))})})}),jte="SliderTrack",kte=D.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=lC(jte,n);return c.jsx(Ux.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:t})});kte.displayName=jte;var x_="SliderRange",Ete=D.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=lC(x_,n),o=Cte(x_,n),i=D.useRef(null),a=Bc(t,i),l=s.values.length,u=s.values.map(h=>Mte(h,s.min,s.max)),d=l>1?Math.min(...u):0,f=100-Math.max(...u);return c.jsx(Ux.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...e.style,[o.startEdge]:d+"%",[o.endEdge]:f+"%"}})});Ete.displayName=x_;var y_="SliderThumb",_te=D.forwardRef((e,t)=>{const n=Stt(e.__scopeSlider),[r,s]=D.useState(null),o=Bc(t,a=>s(a)),i=D.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return c.jsx(Ett,{...e,ref:o,index:i})}),Ett=D.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:s,...o}=e,i=lC(y_,n),a=Cte(y_,n),[l,u]=D.useState(null),d=Bc(t,y=>u(y)),f=l?i.form||!!l.closest("form"):!0,h=ytt(l),m=i.values[r],p=m===void 0?0:Mte(m,i.min,i.max),g=Mtt(r,i.values.length),b=h==null?void 0:h[a.size],x=b?Rtt(b,p,a.direction):0;return D.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(${p}% + ${x}px)`},children:[c.jsx(b_.ItemSlot,{scope:e.__scopeSlider,children:c.jsx(Ux.span,{role:"slider","aria-label":e["aria-label"]||g,"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:Kf(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&c.jsx(Dte,{name:s??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:m},r)]})});_te.displayName=y_;var _tt="RadioBubbleInput",Dte=D.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const s=D.useRef(null),o=Bc(s,r),i=xtt(t);return D.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(Ux.input,{style:{display:"none"},...n,ref:o,defaultValue:t})});Dte.displayName=_tt;function Dtt(e=[],t,n){const r=[...e];return r[n]=t,r.sort((s,o)=>s-o)}function Mte(e,t,n){const o=100/(n-t)*(e-t);return mte(o,[0,100])}function Mtt(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Ttt(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 Rtt(e,t,n){const r=e/2,o=ZI([0,50],[0,r]);return(r-o(t)*n)*n}function Itt(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Att(e,t){if(t>0){const n=Itt(e);return Math.min(...n)>=t}return!0}function ZI(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 Ptt(e){return(String(e).split(".")[1]||"").length}function Ott(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var Tte=wte,Ftt=kte,$tt=Ete,Ltt=_te;const Rte=D.forwardRef(({className:e,...t},n)=>c.jsxs(Tte,{ref:n,className:X("relative flex w-full touch-none select-none items-center",e),...t,children:[c.jsx(Ftt,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:c.jsx($tt,{className:"absolute h-full bg-primary"})}),c.jsx(Ltt,{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"})]}));Rte.displayName=Tte.displayName;const ztt=Lb("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),Ite=D.forwardRef(({className:e,variant:t,...n},r)=>c.jsx("div",{ref:r,role:"alert",className:X(ztt({variant:t}),e),...n}));Ite.displayName="Alert";const Btt=D.forwardRef(({className:e,...t},n)=>c.jsx("h5",{ref:n,className:X("mb-1 font-medium leading-none tracking-tight",e),...t}));Btt.displayName="AlertTitle";const Ate=D.forwardRef(({className:e,...t},n)=>c.jsx("div",{ref:n,className:X("text-sm [&_p]:leading-relaxed",e),...t}));Ate.displayName="AlertDescription";const Pte=D.forwardRef(({className:e,icon:t,tooltip:n,...r},s)=>{const o=c.jsx(Ax,{className:X("peer inline-flex h-8 w-12 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...r,ref:s,children:c.jsx(QR,{className:X("pointer-events-none block h-7 w-7 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"),children:t&&c.jsx("span",{className:"flex h-full items-center justify-center text-primary",children:t})})});return n?c.jsx(On,{children:c.jsxs(un,{delayDuration:0,children:[c.jsx(dn,{asChild:!0,children:c.jsx("span",{className:"inline-flex",children:o})}),c.jsxs(pn,{side:"bottom",className:"border-0 bg-foreground text-background shadow-md",children:[c.jsx(N1,{className:"fill-foreground"}),c.jsx("p",{children:n})]})]})}):o});Pte.displayName="DevModeSwitch";exports.Accordion=nte;exports.AccordionContent=GI;exports.AccordionItem=qI;exports.AccordionTrigger=YI;exports.AggregateTable=fS;exports.Alert=Ite;exports.AlertDescription=Ate;exports.AlertDialog=Gb;exports.AlertDialogAction=Sm;exports.AlertDialogCancel=Cm;exports.AlertDialogContent=bm;exports.AlertDialogDescription=wm;exports.AlertDialogFooter=ym;exports.AlertDialogHeader=xm;exports.AlertDialogTitle=vm;exports.ArrowDown=ta;exports.ArrowRight=b8;exports.ArrowUp=Fo;exports.AssistantStatus=uJ;exports.AxisConfigurator=Nm;exports.Badge=Oe;exports.BookType=x8;exports.BulletChartIcon=eZ;exports.Button=oe;exports.CALCULATED_FIELD_ENTITY_MARKER=hJe;exports.COMPARISON_SUPPORTED_CHART_TYPES=h6;exports.CSS=Mi;exports.Calculator=eD;exports.Calendar=os;exports.Card=vo;exports.CardContent=ji;exports.CardHeader=Ci;exports.CardTitle=Ni;exports.CaretSortIcon=c$e;exports.ChartArea=y8;exports.ChartColumn=sm;exports.ChartColumnIncreasing=v8;exports.ChartColumnStacked=w8;exports.ChartJsVisual=dx;exports.ChartLine=S8;exports.ChartNoAxesGantt=j8;exports.ChartPie=k8;exports.ChartScatter=E8;exports.ChatInputWithContext=LI;exports.Check=$r;exports.CheckIcon=CZ;exports.Checkbox=nn;exports.ChevronDown=Ks;exports.ChevronRight=Go;exports.ChevronUp=Xp;exports.Circle=nD;exports.CircleAlert=yd;exports.CircleHelp=M8;exports.Clock=ml;exports.Code=T8;exports.CodeHighlighter=yc;exports.CodeXml=H2;exports.Collapsible=Ic;exports.CollapsibleContent=Pc;exports.CollapsibleTrigger=Ac;exports.Command=FS;exports.CommandEmpty=LS;exports.CommandGroup=zS;exports.CommandInput=ZR;exports.CommandItem=BS;exports.CommandList=$S;exports.ComparisonMetadataBadge=gZ;exports.Container=sT;exports.Copy=Rg;exports.CopyButton=Jh;exports.CopyPlus=R8;exports.CreateDashboardDialog=$7;exports.Cross2Icon=NZ;exports.CustomFilterPopover=_Z;exports.CustomScrollArea=Cl;exports.DATE_FORMAT_VALUES=mJe;exports.DEFAULT_HEATMAP_CUSTOM_RANGE=oU;exports.Dashboard=Aee;exports.DashboardActionsMenu=L9;exports.DashboardCard=vZ;exports.DashboardPlus=FJe;exports.DashboardWC=QJe;exports.DataSourceDialog=$I;exports.Database=al;exports.DateRangePicker=mR;exports.DefaultChatTransport=FI;exports.DevModeSwitch=Pte;exports.Dialog=ls;exports.DialogContent=Ur;exports.DialogDescription=Is;exports.DialogFooter=Rs;exports.DialogHeader=Wr;exports.DialogTitle=qr;exports.DialogTrigger=eme;exports.DisplayPreferencesProvider=RR;exports.DndContext=IS;exports.Donut=I8;exports.Download=o1;exports.DragOverlay=rX;exports.DropdownMenu=mm;exports.DropdownMenuCheckboxItem=Qp;exports.DropdownMenuContent=Zd;exports.DropdownMenuItem=$o;exports.DropdownMenuLabel=eh;exports.DropdownMenuRadioGroup=Zde;exports.DropdownMenuRadioItem=F9;exports.DropdownMenuSeparator=Cd;exports.DropdownMenuSub=O9;exports.DropdownMenuSubContent=$D;exports.DropdownMenuSubTrigger=FD;exports.DropdownMenuTrigger=pm;exports.EMPTY_DATA_SOURCE=tC;exports.Editable=ib;exports.EditableText=Wo;exports.EditorCustomVisual=ctt;exports.EllipsisVertical=om;exports.EmailScheduleDialog=tZ;exports.ErrorBoundary=Da;exports.Eye=vd;exports.EyeOff=rD;exports.Fallback=SS;exports.FallbackVisual=wS;exports.FeedbackCategory=Fc;exports.FeedbackDialog=bb;exports.FieldsList=rte;exports.FieldsSection=ste;exports.Filter=fc;exports.FilterComponent=Cx;exports.FilterHeader=AR;exports.FilterInfo=$E;exports.Ft=att;exports.GenIcon=ru;exports.Grid3x3=P8;exports.GripVertical=O8;exports.HEATMAP_PRESET_PALETTES=Yk;exports.Hash=F8;exports.House=sD;exports.HoverCard=Pm;exports.HoverCardContent=rf;exports.HoverCardTrigger=Om;exports.IconButton=dc;exports.Info=tr;exports.InlineFilterBar=yZ;exports.Input=Nn;exports.Input$1=jn;exports.KPICard=ab;exports.KeyboardSensor=Dx;exports.LOCALE_CURRENCY_PAIRS=cse;exports.Label=de;exports.Layers=a1;exports.Le=ntt;exports.Link=L8;exports.List=z8;exports.LoaderCircle=Mn;exports.LoadingDots=Rc;exports.Lock=B8;exports.METADATA_KEYS=w6;exports.Map=V8;exports.Maximize2=l1;exports.MdStackedLineChart=QK;exports.MessageSquareWarning=oD;exports.Minimize2=iD;exports.PYTHON_DEFAULT_CODE=R_;exports.PenLine=W2;exports.Pencil=lD;exports.PendingMessagesDisplay=Eee;exports.PiChartPolar=GK;exports.PiFileCsv=z4e;exports.PivotMarkerEnum=Vee;exports.PivotTableTanstack=Nx;exports.Placeholders=fJ;exports.Play=H8;exports.Plus=kr;exports.PointerSensor=Mx;exports.Popover=ks;exports.PopoverContent=_s;exports.PopoverTrigger=Es;exports.PortalTooltipContent=MR;exports.PrintMessages=dJ;exports.Radar=U8;exports.RadioGroup=gi;exports.RadioGroupItem=Jn;exports.RefreshCcw=W8;exports.ResizableHandle=eze;exports.ResizablePanel=qE;exports.ResizablePanelGroup=YX;exports.ResourceEditDialog=AW;exports.ResourceType=Ft;exports.ScrollArea=Xs;exports.ScrollBar=Zo;exports.Search=va;exports.SeedQuestions=Cee;exports.Select=rt;exports.SelectContent=nt;exports.SelectGroup=DW;exports.SelectItem=ge;exports.SelectLabel=eT;exports.SelectTrigger=tt;exports.SelectValue=at;exports.SemaphorContext=Fb;exports.SemaphorContextProvider=J_;exports.SemaphorQueryClient=c8;exports.Separator=Ss;exports.Settings=im;exports.Settings2=Ju;exports.Share2=ed;exports.ShareDialog=IW;exports.Skeleton=Ns;exports.Slider=Rte;exports.SmallSwitch=hte;exports.SortableContext=AS;exports.Sparkles=uD;exports.SquarePen=c1;exports.Star=dD;exports.Switch=Ew;exports.Table2=Ty;exports.TableSkeleton=pZ;exports.TableVisual=lx;exports.Tabs=As;exports.TabsContent=nr;exports.TabsList=cs;exports.TabsTrigger=qt;exports.Tag=Y8;exports.TbChartBubble=KK;exports.TbChartFunnel=ZK;exports.TbChartTreemap=XK;exports.TextCard=Gh;exports.Textarea=Qd;exports.TiSortNumerically=JK;exports.Toggle=jx;exports.Tooltip=un;exports.TooltipArrow=N1;exports.TooltipContent=pn;exports.TooltipProvider=On;exports.TooltipTrigger=dn;exports.Tornado=G8;exports.Trash2=Wd;exports.TreePalm=hD;exports.TriangleAlert=u1;exports.Type=q2;exports.UXProvider=zI;exports.User=Sc;exports.UserPlus=K8;exports.Users=is;exports.X=yt;exports.areEntitiesJoined=cU;exports.arrayMove=Rx;exports.calculateFieldState=BM;exports.canUserManageGroups=zke;exports.chartSupportsDataLabels=iV;exports.chartSupportsLegend=sV;exports.chartTypes=CS;exports.cleanupIncompleteMessages=$W;exports.cleanupKpiMetricComparisonMode=Oee;exports.cloneDeep=bd;exports.cloneFrameWithNewIds=_R;exports.closestCenter=DS;exports.cn=X;exports.colors=Cn;exports.createChartConfig=LM;exports.createEmptyKpiConfig=lpe;exports.createLucideIcon=be;exports.createSlot=wd;exports.createSqlGenConfig=O_;exports.de=fte;exports.dedup=_Qe;exports.downloadPdf=Xke;exports.emitDashboardLoad=Rre;exports.emitDashboardUnload=Ire;exports.fieldAlreadyExists=dU;exports.fmt=fi;exports.format=Ka;exports.getAutoDetectedChartIcon=B4e;exports.getCacheConfig=e1;exports.getCanvasBackgroundColor=il;exports.getChartGridStyle=Epe;exports.getColorForValue=uk;exports.getColumnDataType=mse;exports.getContrastColor=Vo;exports.getDataType=Ir;exports.getDateFormatOptionsForGranularity=xX;exports.getDefaultAxisConfig=fk;exports.getDefaultChartColors=Jd;exports.getDefaultDataLabelsConfig=Zb;exports.getDefaultFilterSql=NE;exports.getDefaultLegendConfig=oM;exports.getDisplayName=jee;exports.getEntityDetails=PQe;exports.getEntityIcon=Vw;exports.getErrorMessage=wee;exports.getFieldIconComponent=lb;exports.getFilterCount=yw;exports.getFilterValueType=hi;exports.getFormattedTableNameForQuery=nv;exports.getKeys=ir;exports.getMetricDisplayLabel=xCe;exports.getNewField=mU;exports.getObjectDiff=u8;exports.getQualifiedTableName=Jw;exports.getSql=P_;exports.handleAggregationChange=LE;exports.handleAggregationLabelChange=bZ;exports.hasValidCardConfig=jc;exports.horizontalListSortingStrategy=sX;exports.hslStringToHex=rV;exports.invalidateToken=Bie;exports.isBooleanDataType=A_;exports.isCalculatedDimension=pJe;exports.isCalculatedField=gJe;exports.isCalculatedMetric=Bee;exports.isColumnInSqlGen=pse;exports.isDateDataType=Si;exports.isDefaultColor=gpe;exports.isDevEnv=T_;exports.isInAiScopeArray=EQe;exports.isNumberDataType=wi;exports.isObjectEmpty=Lie;exports.isTextDataType=Ab;exports.merge=Eh;exports.mergeAxisConfig=hk;exports.pivotData=M1;exports.postRequest=W_;exports.postRequestRegular=yl;exports.prepareFeedbackData=eC;exports.removeFromScopeArray=DQe;exports.removeRing=Vl;exports.requireShim=C_;exports.resolveDataType=F_;exports.resolveDatamodelName=S6;exports.sanitizeAIScope=vee;exports.setupEditorWithCard=_q;exports.showJoinRequiredNotification=uU;exports.sortByColumnsToSortState=CY;exports.sortStateToSortByColumns=NY;exports.sortableKeyboardCoordinates=GR;exports.titleCase=Mg;exports.toTitleCase=Yo;exports.ue=Fe;exports.useAIActions=G1;exports.useAIInteractionStore=Oi;exports.useActiveToolStatus=Tee;exports.useAddNewFrame=DZ;exports.useAssignFilter=zee;exports.useAssistantContainer=FW;exports.useAssistantLayoutStore=id;exports.useAssistantPanel=PW;exports.useAssistantProfile=See;exports.useAutoScroll=Dee;exports.useAutoSubmitQueue=_ee;exports.useCard=SCe;exports.useCardFilterValues=D1;exports.useChat=yee;exports.useColumns=zM;exports.useCreateVisualWithFrame=che;exports.useCurrentAIContext=$m;exports.useCurrentActiveCard=$6;exports.useCurrentCardConfig=z6;exports.useCurrentSheetActiveCards=L6;exports.useCurrentUserInfo=Ts;exports.useCustomVisual=pS;exports.useCustomVisualsQuery=kZ;exports.useDashboardActions=Gt;exports.useDashboardCardQuery=pa;exports.useDashboardCreation=l7;exports.useDashboardManagement=a7;exports.useDashboardPreferences=gm;exports.useDashboardQuery=s1;exports.useDashboardStore=Q;exports.useDataColumns=pU;exports.useDateFilterHook=oOe;exports.useDefaultDashboardMutation=z9;exports.useDroppable=nX;exports.useDynamicIcon=EZ;exports.useEditorActions=lr;exports.useEditorAside=Vx;exports.useEditorStore=Ee;exports.useEnsureReactGlobals=bG;exports.useFieldManagement=Fee;exports.useFileActions=rT;exports.useFileAttachments=nT;exports.useFullscreenAssistant=OW;exports.useGroupMembers=iNe;exports.useGroups=QM;exports.useHasDashboardId=zW;exports.useIsDashboardSelected=vae;exports.useIsVisualSelected=wae;exports.useJoinabilityMap=BI;exports.useManagementActions=$b;exports.useManagementStore=Cs;exports.useMessageWindow=Mee;exports.useMutation=Ri;exports.usePivotTableConfig=zm;exports.usePluginQuery=jZ;exports.useQuery=cn;exports.useQueryClient=Qs;exports.useQueueActions=Lm;exports.useResourceManagement=j1;exports.useResourceUpdateState=i7;exports.useRoleAwareDisplayPreferences=Mq;exports.useSelectedVisual=yae;exports.useSemaphorContext=Ge;exports.useSensor=db;exports.useSensors=HR;exports.useSortable=PS;exports.useSyncLegacyEditorState=ote;exports.useTextFilterHook=uOe;exports.useTheme=Ob;exports.useTopoJson=lU;exports.useUnifiedUsers=XM;exports.useUpdateResource=n7;exports.useUpdateVisualMutation=uhe;exports.useUserPreferences=L7;exports.useVisualById=HD;exports.useVisualManagement=lhe;exports.v4=jr;exports.validateFieldForChartType=Pee;exports.verticalListSortingStrategy=YR;
1081
+ `},FL=jet(Det)(ite),Met={config:Eet},Tet=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return function(s){return n.reduceRight(function(o,i){return i(o)},s)}};function ate(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],ate(e[n],t[n]))}),IL(IL({},e),t)}var Ret={type:"cancelation",msg:"operation is manually canceled"};function r2(e){var t=!1,n=new Promise(function(r,s){e.then(function(o){return t?s(Ret):r(o)}),e.catch(s)});return n.cancel=function(){return t=!0},n}var Iet=Cet.create({config:Net,isInitialized:!1,resolve:null,reject:null,monaco:null}),lte=net(Iet,2),Hx=lte[0],aC=lte[1];function Aet(e){var t=Met.config(e),n=t.monaco,r=tet(t,["monaco"]);aC(function(s){return{config:ate(s.config,r),monaco:n}})}function Pet(){var e=Hx(function(t){var n=t.monaco,r=t.isInitialized,s=t.resolve;return{monaco:n,isInitialized:r,resolve:s}});if(!e.isInitialized){if(aC({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),r2(s2);if(window.monaco&&window.monaco.editor)return cte(window.monaco),e.resolve(window.monaco),r2(s2);Tet(Oet,$et)(Let)}return r2(s2)}function Oet(e){return document.body.appendChild(e)}function Fet(e){var t=document.createElement("script");return e&&(t.src=e),t}function $et(e){var t=Hx(function(r){var s=r.config,o=r.reject;return{config:s,reject:o}}),n=Fet("".concat(t.config.paths.vs,"/loader.js"));return n.onload=function(){return e()},n.onerror=t.reject,n}function Let(){var e=Hx(function(n){var r=n.config,s=n.resolve,o=n.reject;return{config:r,resolve:s,reject:o}}),t=window.require;t.config(e.config),t(["vs/editor/editor.main"],function(n){cte(n),e.resolve(n)},function(n){e.reject(n)})}function cte(e){Hx().monaco||aC({monaco:e})}function zet(){return Hx(function(e){var t=e.monaco;return t})}var s2=new Promise(function(e,t){return aC({resolve:e,reject:t})}),qw={config:Aet,init:Pet,__getMonacoInstance:zet},Bet={wrapper:{display:"flex",position:"relative",textAlign:"initial"},fullWidth:{width:"100%"},hide:{display:"none"}},o2=Bet,Vet={container:{display:"flex",height:"100%",width:"100%",justifyContent:"center",alignItems:"center"}},Het=Vet;function Uet({children:e}){return j.createElement("div",{style:Het.container},e)}var Wet=Uet,qet=Wet;function Yet({width:e,height:t,isEditorReady:n,loading:r,_ref:s,className:o,wrapperProps:i}){return j.createElement("section",{style:{...o2.wrapper,width:e,height:t},...i},!n&&j.createElement(qet,null,r),j.createElement("div",{ref:s,style:{...o2.fullWidth,...!n&&o2.hide},className:o}))}var Get=Yet,ute=j.memo(Get);function Ket(e){j.useEffect(e,[])}var KI=Ket;function Zet(e,t,n=!0){let r=j.useRef(!0);j.useEffect(r.current||!n?()=>{r.current=!1}:e,t)}var ho=Zet;function Cg(){}function Gf(e,t,n,r){return Xet(e,r)||Qet(e,t,n,r)}function Xet(e,t){return e.editor.getModel(dte(e,t))}function Qet(e,t,n,r){return e.editor.createModel(t,n,r?dte(e,r):void 0)}function dte(e,t){return e.Uri.parse(t)}function Jet({original:e,modified:t,language:n,originalLanguage:r,modifiedLanguage:s,originalModelPath:o,modifiedModelPath:i,keepCurrentOriginalModel:a=!1,keepCurrentModifiedModel:l=!1,theme:u="light",loading:d="Loading...",options:f={},height:h="100%",width:m="100%",className:p,wrapperProps:g={},beforeMount:b=Cg,onMount:x=Cg}){let[y,v]=j.useState(!1),[w,C]=j.useState(!0),S=j.useRef(null),N=j.useRef(null),_=j.useRef(null),E=j.useRef(x),k=j.useRef(b),M=j.useRef(!1);KI(()=>{let I=qw.init();return I.then(L=>(N.current=L)&&C(!1)).catch(L=>(L==null?void 0:L.type)!=="cancelation"&&console.error("Monaco initialization: error:",L)),()=>S.current?R():I.cancel()}),ho(()=>{if(S.current&&N.current){let I=S.current.getOriginalEditor(),L=Gf(N.current,e||"",r||n||"text",o||"");L!==I.getModel()&&I.setModel(L)}},[o],y),ho(()=>{if(S.current&&N.current){let I=S.current.getModifiedEditor(),L=Gf(N.current,t||"",s||n||"text",i||"");L!==I.getModel()&&I.setModel(L)}},[i],y),ho(()=>{let I=S.current.getModifiedEditor();I.getOption(N.current.editor.EditorOption.readOnly)?I.setValue(t||""):t!==I.getValue()&&(I.executeEdits("",[{range:I.getModel().getFullModelRange(),text:t||"",forceMoveMarkers:!0}]),I.pushUndoStop())},[t],y),ho(()=>{var I,L;(L=(I=S.current)==null?void 0:I.getModel())==null||L.original.setValue(e||"")},[e],y),ho(()=>{let{original:I,modified:L}=S.current.getModel();N.current.editor.setModelLanguage(I,r||n||"text"),N.current.editor.setModelLanguage(L,s||n||"text")},[n,r,s],y),ho(()=>{var I;(I=N.current)==null||I.editor.setTheme(u)},[u],y),ho(()=>{var I;(I=S.current)==null||I.updateOptions(f)},[f],y);let T=j.useCallback(()=>{var F;if(!N.current)return;k.current(N.current);let I=Gf(N.current,e||"",r||n||"text",o||""),L=Gf(N.current,t||"",s||n||"text",i||"");(F=S.current)==null||F.setModel({original:I,modified:L})},[n,t,s,e,r,o,i]),O=j.useCallback(()=>{var I;!M.current&&_.current&&(S.current=N.current.editor.createDiffEditor(_.current,{automaticLayout:!0,...f}),T(),(I=N.current)==null||I.editor.setTheme(u),v(!0),M.current=!0)},[f,u,T]);j.useEffect(()=>{y&&E.current(S.current,N.current)},[y]),j.useEffect(()=>{!w&&!y&&O()},[w,y,O]);function R(){var L,F,V,$;let I=(L=S.current)==null?void 0:L.getModel();a||((F=I==null?void 0:I.original)==null||F.dispose()),l||((V=I==null?void 0:I.modified)==null||V.dispose()),($=S.current)==null||$.dispose()}return j.createElement(ute,{width:m,height:h,isEditorReady:y,loading:d,_ref:_,className:p,wrapperProps:g})}var ett=Jet;j.memo(ett);function ttt(){let[e,t]=j.useState(qw.__getMonacoInstance());return KI(()=>{let n;return e||(n=qw.init(),n.then(r=>{t(r)})),()=>n==null?void 0:n.cancel()}),e}var ntt=ttt;function rtt(e){let t=j.useRef();return j.useEffect(()=>{t.current=e},[e]),t.current}var stt=rtt,ky=new Map;function ott({defaultValue:e,defaultLanguage:t,defaultPath:n,value:r,language:s,path:o,theme:i="light",line:a,loading:l="Loading...",options:u={},overrideServices:d={},saveViewState:f=!0,keepCurrentModel:h=!1,width:m="100%",height:p="100%",className:g,wrapperProps:b={},beforeMount:x=Cg,onMount:y=Cg,onChange:v,onValidate:w=Cg}){let[C,S]=j.useState(!1),[N,_]=j.useState(!0),E=j.useRef(null),k=j.useRef(null),M=j.useRef(null),T=j.useRef(y),O=j.useRef(x),R=j.useRef(),I=j.useRef(r),L=stt(o),F=j.useRef(!1),V=j.useRef(!1);KI(()=>{let U=qw.init();return U.then(B=>(E.current=B)&&_(!1)).catch(B=>(B==null?void 0:B.type)!=="cancelation"&&console.error("Monaco initialization: error:",B)),()=>k.current?P():U.cancel()}),ho(()=>{var B,A,Y,z;let U=Gf(E.current,e||r||"",t||s||"",o||n||"");U!==((B=k.current)==null?void 0:B.getModel())&&(f&&ky.set(L,(A=k.current)==null?void 0:A.saveViewState()),(Y=k.current)==null||Y.setModel(U),f&&((z=k.current)==null||z.restoreViewState(ky.get(o))))},[o],C),ho(()=>{var U;(U=k.current)==null||U.updateOptions(u)},[u],C),ho(()=>{!k.current||r===void 0||(k.current.getOption(E.current.editor.EditorOption.readOnly)?k.current.setValue(r):r!==k.current.getValue()&&(V.current=!0,k.current.executeEdits("",[{range:k.current.getModel().getFullModelRange(),text:r,forceMoveMarkers:!0}]),k.current.pushUndoStop(),V.current=!1))},[r],C),ho(()=>{var B,A;let U=(B=k.current)==null?void 0:B.getModel();U&&s&&((A=E.current)==null||A.editor.setModelLanguage(U,s))},[s],C),ho(()=>{var U;a!==void 0&&((U=k.current)==null||U.revealLine(a))},[a],C),ho(()=>{var U;(U=E.current)==null||U.editor.setTheme(i)},[i],C);let $=j.useCallback(()=>{var U;if(!(!M.current||!E.current)&&!F.current){O.current(E.current);let B=o||n,A=Gf(E.current,r||e||"",t||s||"",B||"");k.current=(U=E.current)==null?void 0:U.editor.create(M.current,{model:A,automaticLayout:!0,...u},d),f&&k.current.restoreViewState(ky.get(B)),E.current.editor.setTheme(i),a!==void 0&&k.current.revealLine(a),S(!0),F.current=!0}},[e,t,n,r,s,o,u,d,f,i,a]);j.useEffect(()=>{C&&T.current(k.current,E.current)},[C]),j.useEffect(()=>{!N&&!C&&$()},[N,C,$]),I.current=r,j.useEffect(()=>{var U,B;C&&v&&((U=R.current)==null||U.dispose(),R.current=(B=k.current)==null?void 0:B.onDidChangeModelContent(A=>{V.current||v(k.current.getValue(),A)}))},[C,v]),j.useEffect(()=>{if(C){let U=E.current.editor.onDidChangeMarkers(B=>{var Y;let A=(Y=k.current.getModel())==null?void 0:Y.uri;if(A&&B.find(z=>z.path===A.path)){let z=E.current.editor.getModelMarkers({resource:A});w==null||w(z)}});return()=>{U==null||U.dispose()}}return()=>{}},[C,w]);function P(){var U,B;(U=R.current)==null||U.dispose(),h?f&&ky.set(o,k.current.saveViewState()):(B=k.current.getModel())==null||B.dispose(),k.current.dispose()}return j.createElement(ute,{width:m,height:p,isEditorReady:C,loading:l,_ref:M,className:g,wrapperProps:b})}var itt=ott,fte=j.memo(itt),att=fte;function ltt({card:e}){var R,I,L,F,V,$,P,U,B,A,Y;const[t,n]=j.useState(!1),[r,s]=j.useState([]),{authToken:o}=Ge(),{theme:i}=Ob(),a=V6(o==null?void 0:o.accessToken),l=Q(z=>z.themeStyle),u={mode:i||"system",colors:((I=(R=l==null?void 0:l.chart)==null?void 0:R.dataset)==null?void 0:I.backgroundColor)||[]};(L=e.customCardPreferences)!=null&&L.inputData;const{getCard:d}=pS(((F=e.customCardPreferences)==null?void 0:F.url)||""),f=((V=e.customCardPreferences)==null?void 0:V.visualType)||"single",h=Ee(z=>z.frame),{setCustomCardPreferences:m}=lr(),{data:p}=pa(e),g=Pt(z=>z.interactionStates),b=Q(z=>{var q;return(q=z.dashboard)==null?void 0:q.id}),x=Q(z=>z.dashboard.filters),y=Q(z=>z.filterValues),v=Q(z=>z.selectedSheetId),w=Q(z=>z.inlineFilterValuesMap[e.id]),C=j.useMemo(()=>UK({card:e,sheetId:v||"",inlineFilterValues:w}),[e,v,w]),{cardFilters:S,cardFilterValues:N,shouldApplyDashboardFilters:_,contextMode:E}=j.useMemo(()=>rM({card:e,interactionStates:g,currentDashboardId:b,filters:x,filterValues:y,selectedSheetId:v}),[e,g,b,x,y,v]),k=j.useCallback((z,q)=>{s(W=>({...W,[z]:q}))},[]);if(!(($=e.customCardPreferences)!=null&&$.componentName))return null;const M=d((P=e.customCardPreferences)==null?void 0:P.componentName);function T(z){n(z)}const O=Object.keys(((U=e.customCardPreferences)==null?void 0:U.dataInputCardIds)||{}).map(z=>{var H,G,K;const q=(G=(H=e.customCardPreferences)==null?void 0:H.dataInputCardIds)==null?void 0:G[z].cardId,W=(K=h==null?void 0:h.cards)==null?void 0:K.find(te=>te.id===q);return W||null});return c.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:c.jsxs(j.Suspense,{fallback:c.jsx(c.Fragment,{}),children:[M&&f==="single"&&c.jsx(M,{editing:!0,params:a,theme:u,settings:(B=e.customCardPreferences)==null?void 0:B.settings,onDataChange:k,data:(p==null?void 0:p.records)||[],filters:S,filterValues:[...N||[],...w||[]],inlineFilters:C}),M&&f==="multiple"&&c.jsxs(c.Fragment,{children:[Object.keys(((A=e.customCardPreferences)==null?void 0:A.dataInputCardIds)||{}).map(z=>{var H,G,K;const q=(G=(H=e.customCardPreferences)==null?void 0:H.dataInputCardIds)==null?void 0:G[z].cardId,W=(K=h==null?void 0:h.cards)==null?void 0:K.find(te=>te.id===q);if(W)return c.jsx(xG,{onLoadingStatus:T,onDataChange:k,dataInputIndex:z,card:W},W.id+z)}),c.jsx("div",{className:"flex flex-col gap-2",children:c.jsx(M,{theme:u,onDataChange:k,settings:O.map(z=>{var q;return(q=z==null?void 0:z.customCardPreferences)==null?void 0:q.settings}),data:O.map(z=>z!=null&&z.id?r==null?void 0:r[z.id]:[]),filters:S,filterValues:[...N||[],...w||[]],inlineFilters:C})})]})]},(Y=e.customCardPreferences)==null?void 0:Y.componentName)})}const ctt=j.memo(ltt,(e,t)=>{var n,r,s,o,i,a;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.url)===((o=t.card.customCardPreferences)==null?void 0:o.url)&&((i=e.card.customCardPreferences)==null?void 0:i.componentName)===((a=t.card.customCardPreferences)==null?void 0:a.componentName)}),hte=D.forwardRef(({className:e,...t},n)=>c.jsx(Ax,{className:X("peer inline-flex h-[22px] w-[36px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:c.jsx(QR,{className:X("pointer-events-none block size-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));hte.displayName=Ax.displayName;function mte(e,[t,n]){return Math.min(n,Math.max(t,e))}function Kf(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e==null||e(s),n===!1||!s.defaultPrevented)return t==null?void 0:t(s)}}function $L(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function utt(...e){return t=>{let n=!1;const r=e.map(s=>{const o=$L(s,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let s=0;s<r.length;s++){const o=r[s];typeof o=="function"?o():$L(e[s],null)}}}}function Bc(...e){return D.useCallback(utt(...e),e)}function pte(e,t=[]){let n=[];function r(o,i){const a=D.createContext(i),l=n.length;n=[...n,i];const u=f=>{var x;const{scope:h,children:m,...p}=f,g=((x=h==null?void 0:h[e])==null?void 0:x[l])||a,b=D.useMemo(()=>p,Object.values(p));return c.jsx(g.Provider,{value:b,children:m})};u.displayName=o+"Provider";function d(f,h){var g;const m=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,p=D.useContext(m);if(p)return p;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${o}\``)}return[u,d]}const s=()=>{const o=n.map(i=>D.createContext(i));return function(a){const l=(a==null?void 0:a[e])||o;return D.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return s.scopeName=e,[r,dtt(s,...t)]}function dtt(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(o){const i=r.reduce((a,{useScope:l,scopeName:u})=>{const f=l(o)[`__scope${u}`];return{...a,...f}},{});return D.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var gte=globalThis!=null&&globalThis.document?D.useLayoutEffect:()=>{},ftt=D[" useInsertionEffect ".trim().toString()]||gte;function htt({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[s,o,i]=mtt({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:s;{const d=D.useRef(e!==void 0);D.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const u=D.useCallback(d=>{var f;if(a){const h=ptt(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else o(d)},[a,e,o,i]);return[l,u]}function mtt({defaultProp:e,onChange:t}){const[n,r]=D.useState(e),s=D.useRef(n),o=D.useRef(t);return ftt(()=>{o.current=t},[t]),D.useEffect(()=>{var i;s.current!==n&&((i=o.current)==null||i.call(o,n),s.current=n)},[n,s]),[n,r,o]}function ptt(e){return typeof e=="function"}var gtt=D.createContext(void 0);function btt(e){const t=D.useContext(gtt);return e||t||"ltr"}function xtt(e){const t=D.useRef({value:e,previous:e});return D.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}function ytt(e){const[t,n]=D.useState(void 0);return gte(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const o=s[0];let i,a;if("borderBoxSize"in o){const l=o.borderBoxSize,u=Array.isArray(l)?l[0]:l;i=u.inlineSize,a=u.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var vtt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ux=vtt.reduce((e,t)=>{const n=wd(`Primitive.${t}`),r=D.forwardRef((s,o)=>{const{asChild:i,...a}=s,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c.jsx(l,{...a,ref:o})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function wtt(e){const t=e+"CollectionProvider",[n,r]=pte(t),[s,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=g=>{const{scope:b,children:x}=g,y=j.useRef(null),v=j.useRef(new Map).current;return c.jsx(s,{scope:b,itemMap:v,collectionRef:y,children:x})};i.displayName=t;const a=e+"CollectionSlot",l=wd(a),u=j.forwardRef((g,b)=>{const{scope:x,children:y}=g,v=o(a,x),w=Bc(b,v.collectionRef);return c.jsx(l,{ref:w,children:y})});u.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=wd(d),m=j.forwardRef((g,b)=>{const{scope:x,children:y,...v}=g,w=j.useRef(null),C=Bc(b,w),S=o(d,x);return j.useEffect(()=>(S.itemMap.set(w,{ref:w,...v}),()=>void S.itemMap.delete(w))),c.jsx(h,{[f]:"",ref:C,children:y})});m.displayName=d;function p(g){const b=o(e+"CollectionConsumer",g);return j.useCallback(()=>{const y=b.collectionRef.current;if(!y)return[];const v=Array.from(y.querySelectorAll(`[${f}]`));return Array.from(b.itemMap.values()).sort((S,N)=>v.indexOf(S.ref.current)-v.indexOf(N.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:i,Slot:u,ItemSlot:m},p,r]}var bte=["PageUp","PageDown"],xte=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],yte={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},ep="Slider",[b_,Stt,Ctt]=wtt(ep),[vte]=pte(ep,[Ctt]),[Ntt,lC]=vte(ep),wte=D.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:p,...g}=e,b=D.useRef(new Set),x=D.useRef(0),v=i==="horizontal"?jtt:ktt,[w=[],C]=htt({prop:d,defaultProp:u,onChange:M=>{var O;(O=[...b.current][x.current])==null||O.focus(),f(M)}}),S=D.useRef(w);function N(M){const T=Ttt(w,M);k(M,T)}function _(M){k(M,x.current)}function E(){const M=S.current[x.current];w[x.current]!==M&&h(w)}function k(M,T,{commit:O}={commit:!1}){const R=Ptt(o),I=Ott(Math.round((M-r)/o)*o+r,R),L=mte(I,[r,s]);C((F=[])=>{const V=Dtt(F,L,T);if(Att(V,l*o)){x.current=V.indexOf(L);const $=String(V)!==String(F);return $&&O&&h(V),$?V:F}else return F})}return c.jsx(Ntt,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:s,valueIndexToChangeRef:x,thumbs:b.current,values:w,orientation:i,form:p,children:c.jsx(b_.Provider,{scope:e.__scopeSlider,children:c.jsx(b_.Slot,{scope:e.__scopeSlider,children:c.jsx(v,{"aria-disabled":a,"data-disabled":a?"":void 0,...g,ref:t,onPointerDown:Kf(g.onPointerDown,()=>{a||(S.current=w)}),min:r,max:s,inverted:m,onSlideStart:a?void 0:N,onSlideMove:a?void 0:_,onSlideEnd:a?void 0:E,onHomeKeyDown:()=>!a&&k(r,0,{commit:!0}),onEndKeyDown:()=>!a&&k(s,w.length-1,{commit:!0}),onStepKeyDown:({event:M,direction:T})=>{if(!a){const I=bte.includes(M.key)||M.shiftKey&&xte.includes(M.key)?10:1,L=x.current,F=w[L],V=o*I*T;k(F+V,L,{commit:!0})}}})})})})});wte.displayName=ep;var[Ste,Cte]=vte(ep,{startEdge:"left",endEdge:"right",size:"width",direction:1}),jtt=D.forwardRef((e,t)=>{const{min:n,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:l,onStepKeyDown:u,...d}=e,[f,h]=D.useState(null),m=Bc(t,v=>h(v)),p=D.useRef(void 0),g=btt(s),b=g==="ltr",x=b&&!o||!b&&o;function y(v){const w=p.current||f.getBoundingClientRect(),C=[0,w.width],N=ZI(C,x?[n,r]:[r,n]);return p.current=w,N(v-w.left)}return c.jsx(Ste,{scope:e.__scopeSlider,startEdge:x?"left":"right",endEdge:x?"right":"left",direction:x?1:-1,size:"width",children:c.jsx(Nte,{dir:g,"data-orientation":"horizontal",...d,ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{const w=y(v.clientX);i==null||i(w)},onSlideMove:v=>{const w=y(v.clientX);a==null||a(w)},onSlideEnd:()=>{p.current=void 0,l==null||l()},onStepKeyDown:v=>{const C=yte[x?"from-left":"from-right"].includes(v.key);u==null||u({event:v,direction:C?-1:1})}})})}),ktt=D.forwardRef((e,t)=>{const{min:n,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:l,...u}=e,d=D.useRef(null),f=Bc(t,d),h=D.useRef(void 0),m=!s;function p(g){const b=h.current||d.current.getBoundingClientRect(),x=[0,b.height],v=ZI(x,m?[r,n]:[n,r]);return h.current=b,v(g-b.top)}return c.jsx(Ste,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:c.jsx(Nte,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{const b=p(g.clientY);o==null||o(b)},onSlideMove:g=>{const b=p(g.clientY);i==null||i(b)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:g=>{const x=yte[m?"from-bottom":"from-top"].includes(g.key);l==null||l({event:g,direction:x?-1:1})}})})}),Nte=D.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:l,...u}=e,d=lC(ep,n);return c.jsx(Ux.span,{...u,ref:t,onKeyDown:Kf(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):bte.concat(xte).includes(f.key)&&(l(f),f.preventDefault())}),onPointerDown:Kf(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus():r(f)}),onPointerMove:Kf(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f)}),onPointerUp:Kf(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),o(f))})})}),jte="SliderTrack",kte=D.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=lC(jte,n);return c.jsx(Ux.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:t})});kte.displayName=jte;var x_="SliderRange",Ete=D.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=lC(x_,n),o=Cte(x_,n),i=D.useRef(null),a=Bc(t,i),l=s.values.length,u=s.values.map(h=>Mte(h,s.min,s.max)),d=l>1?Math.min(...u):0,f=100-Math.max(...u);return c.jsx(Ux.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...e.style,[o.startEdge]:d+"%",[o.endEdge]:f+"%"}})});Ete.displayName=x_;var y_="SliderThumb",_te=D.forwardRef((e,t)=>{const n=Stt(e.__scopeSlider),[r,s]=D.useState(null),o=Bc(t,a=>s(a)),i=D.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return c.jsx(Ett,{...e,ref:o,index:i})}),Ett=D.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:s,...o}=e,i=lC(y_,n),a=Cte(y_,n),[l,u]=D.useState(null),d=Bc(t,y=>u(y)),f=l?i.form||!!l.closest("form"):!0,h=ytt(l),m=i.values[r],p=m===void 0?0:Mte(m,i.min,i.max),g=Mtt(r,i.values.length),b=h==null?void 0:h[a.size],x=b?Rtt(b,p,a.direction):0;return D.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(${p}% + ${x}px)`},children:[c.jsx(b_.ItemSlot,{scope:e.__scopeSlider,children:c.jsx(Ux.span,{role:"slider","aria-label":e["aria-label"]||g,"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:Kf(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&c.jsx(Dte,{name:s??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:m},r)]})});_te.displayName=y_;var _tt="RadioBubbleInput",Dte=D.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const s=D.useRef(null),o=Bc(s,r),i=xtt(t);return D.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(Ux.input,{style:{display:"none"},...n,ref:o,defaultValue:t})});Dte.displayName=_tt;function Dtt(e=[],t,n){const r=[...e];return r[n]=t,r.sort((s,o)=>s-o)}function Mte(e,t,n){const o=100/(n-t)*(e-t);return mte(o,[0,100])}function Mtt(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Ttt(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 Rtt(e,t,n){const r=e/2,o=ZI([0,50],[0,r]);return(r-o(t)*n)*n}function Itt(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Att(e,t){if(t>0){const n=Itt(e);return Math.min(...n)>=t}return!0}function ZI(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 Ptt(e){return(String(e).split(".")[1]||"").length}function Ott(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var Tte=wte,Ftt=kte,$tt=Ete,Ltt=_te;const Rte=D.forwardRef(({className:e,...t},n)=>c.jsxs(Tte,{ref:n,className:X("relative flex w-full touch-none select-none items-center",e),...t,children:[c.jsx(Ftt,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:c.jsx($tt,{className:"absolute h-full bg-primary"})}),c.jsx(Ltt,{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"})]}));Rte.displayName=Tte.displayName;const ztt=Lb("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),Ite=D.forwardRef(({className:e,variant:t,...n},r)=>c.jsx("div",{ref:r,role:"alert",className:X(ztt({variant:t}),e),...n}));Ite.displayName="Alert";const Btt=D.forwardRef(({className:e,...t},n)=>c.jsx("h5",{ref:n,className:X("mb-1 font-medium leading-none tracking-tight",e),...t}));Btt.displayName="AlertTitle";const Ate=D.forwardRef(({className:e,...t},n)=>c.jsx("div",{ref:n,className:X("text-sm [&_p]:leading-relaxed",e),...t}));Ate.displayName="AlertDescription";const Pte=D.forwardRef(({className:e,icon:t,tooltip:n,...r},s)=>{const o=c.jsx(Ax,{className:X("peer inline-flex h-8 w-12 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...r,ref:s,children:c.jsx(QR,{className:X("pointer-events-none block h-7 w-7 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"),children:t&&c.jsx("span",{className:"flex h-full items-center justify-center text-primary",children:t})})});return n?c.jsx(On,{children:c.jsxs(un,{delayDuration:0,children:[c.jsx(dn,{asChild:!0,children:c.jsx("span",{className:"inline-flex",children:o})}),c.jsxs(pn,{side:"bottom",className:"border-0 bg-foreground text-background shadow-md",children:[c.jsx(N1,{className:"fill-foreground"}),c.jsx("p",{children:n})]})]})}):o});Pte.displayName="DevModeSwitch";exports.Accordion=nte;exports.AccordionContent=GI;exports.AccordionItem=qI;exports.AccordionTrigger=YI;exports.AggregateTable=fS;exports.Alert=Ite;exports.AlertDescription=Ate;exports.AlertDialog=Gb;exports.AlertDialogAction=Sm;exports.AlertDialogCancel=Cm;exports.AlertDialogContent=bm;exports.AlertDialogDescription=wm;exports.AlertDialogFooter=ym;exports.AlertDialogHeader=xm;exports.AlertDialogTitle=vm;exports.ArrowDown=ta;exports.ArrowRight=b8;exports.ArrowUp=Fo;exports.AssistantStatus=uJ;exports.AxisConfigurator=Nm;exports.Badge=Oe;exports.BookType=x8;exports.BulletChartIcon=eZ;exports.Button=oe;exports.CALCULATED_FIELD_ENTITY_MARKER=hJe;exports.COMPARISON_SUPPORTED_CHART_TYPES=h6;exports.CSS=Mi;exports.Calculator=eD;exports.Calendar=os;exports.Card=vo;exports.CardContent=ji;exports.CardHeader=Ci;exports.CardTitle=Ni;exports.CaretSortIcon=c$e;exports.ChartArea=y8;exports.ChartColumn=sm;exports.ChartColumnIncreasing=v8;exports.ChartColumnStacked=w8;exports.ChartJsVisual=dx;exports.ChartLine=S8;exports.ChartNoAxesGantt=j8;exports.ChartPie=k8;exports.ChartScatter=E8;exports.ChatInputWithContext=LI;exports.Check=$r;exports.CheckIcon=CZ;exports.Checkbox=nn;exports.ChevronDown=Ks;exports.ChevronRight=Go;exports.ChevronUp=Xp;exports.Circle=nD;exports.CircleAlert=yd;exports.CircleHelp=M8;exports.Clock=ml;exports.Code=T8;exports.CodeHighlighter=yc;exports.CodeXml=H2;exports.Collapsible=Ic;exports.CollapsibleContent=Pc;exports.CollapsibleTrigger=Ac;exports.Command=FS;exports.CommandEmpty=LS;exports.CommandGroup=zS;exports.CommandInput=ZR;exports.CommandItem=BS;exports.CommandList=$S;exports.ComparisonMetadataBadge=gZ;exports.Container=sT;exports.Copy=Rg;exports.CopyButton=Jh;exports.CopyPlus=R8;exports.CreateDashboardDialog=$7;exports.Cross2Icon=NZ;exports.CustomFilterPopover=_Z;exports.CustomScrollArea=Cl;exports.DATE_FORMAT_VALUES=mJe;exports.DEFAULT_HEATMAP_CUSTOM_RANGE=oU;exports.Dashboard=Aee;exports.DashboardActionsMenu=L9;exports.DashboardCard=vZ;exports.DashboardPlus=FJe;exports.DashboardWC=QJe;exports.DataSourceDialog=$I;exports.Database=al;exports.DateRangePicker=mR;exports.DefaultChatTransport=FI;exports.DevModeSwitch=Pte;exports.Dialog=ls;exports.DialogContent=Ur;exports.DialogDescription=Is;exports.DialogFooter=Rs;exports.DialogHeader=Wr;exports.DialogTitle=qr;exports.DialogTrigger=eme;exports.DisplayPreferencesProvider=RR;exports.DndContext=IS;exports.Donut=I8;exports.Download=o1;exports.DragOverlay=rX;exports.DropdownMenu=mm;exports.DropdownMenuCheckboxItem=Qp;exports.DropdownMenuContent=Zd;exports.DropdownMenuItem=$o;exports.DropdownMenuLabel=eh;exports.DropdownMenuRadioGroup=Zde;exports.DropdownMenuRadioItem=F9;exports.DropdownMenuSeparator=Cd;exports.DropdownMenuSub=O9;exports.DropdownMenuSubContent=$D;exports.DropdownMenuSubTrigger=FD;exports.DropdownMenuTrigger=pm;exports.EMPTY_DATA_SOURCE=tC;exports.Editable=ib;exports.EditableText=Wo;exports.EditorCustomVisual=ctt;exports.EllipsisVertical=om;exports.EmailScheduleDialog=tZ;exports.ErrorBoundary=Da;exports.Eye=vd;exports.EyeOff=rD;exports.Fallback=SS;exports.FallbackVisual=wS;exports.FeedbackCategory=Fc;exports.FeedbackDialog=bb;exports.FieldsList=rte;exports.FieldsSection=ste;exports.Filter=fc;exports.FilterComponent=Cx;exports.FilterHeader=AR;exports.FilterInfo=$E;exports.Ft=att;exports.GenIcon=ru;exports.Grid3x3=P8;exports.GripVertical=O8;exports.HEATMAP_PRESET_PALETTES=Yk;exports.Hash=F8;exports.House=sD;exports.HoverCard=Pm;exports.HoverCardContent=rf;exports.HoverCardTrigger=Om;exports.IconButton=dc;exports.Info=tr;exports.InlineFilterBar=yZ;exports.Input=Nn;exports.Input$1=jn;exports.KPICard=ab;exports.KeyboardSensor=Dx;exports.LOCALE_CURRENCY_PAIRS=cse;exports.Label=de;exports.Layers=a1;exports.Le=ntt;exports.Link=L8;exports.List=z8;exports.LoaderCircle=Mn;exports.LoadingDots=Rc;exports.Lock=B8;exports.METADATA_KEYS=w6;exports.Map=V8;exports.Maximize2=l1;exports.MdStackedLineChart=QK;exports.MessageSquareWarning=oD;exports.Minimize2=iD;exports.PYTHON_DEFAULT_CODE=R_;exports.PenLine=W2;exports.Pencil=lD;exports.PendingMessagesDisplay=Eee;exports.PiChartPolar=GK;exports.PiFileCsv=z4e;exports.PivotMarkerEnum=Vee;exports.PivotTableTanstack=Nx;exports.Placeholders=fJ;exports.Play=H8;exports.Plus=kr;exports.PointerSensor=Mx;exports.Popover=ks;exports.PopoverContent=_s;exports.PopoverTrigger=Es;exports.PortalTooltipContent=MR;exports.PrintMessages=dJ;exports.Radar=U8;exports.RadioGroup=gi;exports.RadioGroupItem=Jn;exports.RefreshCcw=W8;exports.ResizableHandle=eze;exports.ResizablePanel=qE;exports.ResizablePanelGroup=YX;exports.ResourceEditDialog=AW;exports.ResourceType=Ft;exports.ScrollArea=Xs;exports.ScrollBar=Zo;exports.Search=va;exports.SeedQuestions=Cee;exports.Select=rt;exports.SelectContent=nt;exports.SelectGroup=DW;exports.SelectItem=ge;exports.SelectLabel=eT;exports.SelectTrigger=tt;exports.SelectValue=at;exports.SemaphorContext=Fb;exports.SemaphorContextProvider=J_;exports.SemaphorQueryClient=c8;exports.Separator=Ss;exports.Settings=im;exports.Settings2=Ju;exports.Share2=ed;exports.ShareDialog=IW;exports.Skeleton=Ns;exports.Slider=Rte;exports.SmallSwitch=hte;exports.SortableContext=AS;exports.Sparkles=uD;exports.SquarePen=c1;exports.Star=dD;exports.Switch=Ew;exports.Table2=Ty;exports.TableSkeleton=pZ;exports.TableVisual=lx;exports.Tabs=As;exports.TabsContent=nr;exports.TabsList=cs;exports.TabsTrigger=qt;exports.Tag=Y8;exports.TbChartBubble=KK;exports.TbChartFunnel=ZK;exports.TbChartTreemap=XK;exports.TextCard=Gh;exports.Textarea=Qd;exports.TiSortNumerically=JK;exports.Toggle=jx;exports.Tooltip=un;exports.TooltipArrow=N1;exports.TooltipContent=pn;exports.TooltipProvider=On;exports.TooltipTrigger=dn;exports.Tornado=G8;exports.Trash2=Wd;exports.TreePalm=hD;exports.TriangleAlert=u1;exports.Type=q2;exports.UXProvider=zI;exports.User=Sc;exports.UserPlus=K8;exports.Users=is;exports.X=yt;exports.areEntitiesJoined=cU;exports.arrayMove=Rx;exports.calculateFieldState=BM;exports.canUserManageGroups=zke;exports.chartSupportsDataLabels=iV;exports.chartSupportsLegend=sV;exports.chartTypes=CS;exports.cleanupIncompleteMessages=$W;exports.cleanupKpiMetricComparisonMode=Oee;exports.cloneDeep=bd;exports.cloneFrameWithNewIds=_R;exports.closestCenter=DS;exports.cn=X;exports.colors=Cn;exports.createChartConfig=LM;exports.createEmptyKpiConfig=lpe;exports.createLucideIcon=be;exports.createSlot=wd;exports.createSqlGenConfig=O_;exports.de=fte;exports.dedup=_Qe;exports.downloadPdf=Xke;exports.emitDashboardLoad=Rre;exports.emitDashboardUnload=Ire;exports.fieldAlreadyExists=dU;exports.fmt=fi;exports.format=Ka;exports.getAutoDetectedChartIcon=B4e;exports.getCacheConfig=e1;exports.getCanvasBackgroundColor=il;exports.getChartGridStyle=Epe;exports.getColorForValue=uk;exports.getColumnDataType=mse;exports.getContrastColor=Vo;exports.getDataType=Ir;exports.getDateFormatOptionsForGranularity=xX;exports.getDefaultAxisConfig=fk;exports.getDefaultChartColors=Jd;exports.getDefaultDataLabelsConfig=Zb;exports.getDefaultFilterSql=NE;exports.getDefaultLegendConfig=oM;exports.getDisplayName=jee;exports.getEntityDetails=PQe;exports.getEntityIcon=Vw;exports.getErrorMessage=wee;exports.getFieldIconComponent=lb;exports.getFilterCount=yw;exports.getFilterValueType=hi;exports.getFormattedTableNameForQuery=nv;exports.getKeys=ir;exports.getMetricDisplayLabel=xCe;exports.getNewField=mU;exports.getObjectDiff=u8;exports.getQualifiedTableName=Jw;exports.getSql=P_;exports.handleAggregationChange=LE;exports.handleAggregationLabelChange=bZ;exports.hasValidCardConfig=jc;exports.horizontalListSortingStrategy=sX;exports.hslStringToHex=rV;exports.invalidateToken=Bie;exports.isBooleanDataType=A_;exports.isCalculatedDimension=pJe;exports.isCalculatedField=gJe;exports.isCalculatedMetric=Bee;exports.isColumnInSqlGen=pse;exports.isDateDataType=Si;exports.isDefaultColor=gpe;exports.isDevEnv=T_;exports.isInAiScopeArray=EQe;exports.isNumberDataType=wi;exports.isObjectEmpty=Lie;exports.isTextDataType=Ab;exports.merge=Eh;exports.mergeAxisConfig=hk;exports.pivotData=M1;exports.postRequest=W_;exports.postRequestRegular=yl;exports.prepareFeedbackData=eC;exports.removeFromScopeArray=DQe;exports.removeRing=Vl;exports.requireShim=C_;exports.resolveDataType=F_;exports.resolveDatamodelName=S6;exports.sanitizeAIScope=vee;exports.setupEditorWithCard=_q;exports.showJoinRequiredNotification=uU;exports.sortByColumnsToSortState=CY;exports.sortStateToSortByColumns=NY;exports.sortableKeyboardCoordinates=GR;exports.titleCase=Mg;exports.toTitleCase=Yo;exports.ue=Fe;exports.useAIActions=G1;exports.useAIInteractionStore=Oi;exports.useActiveToolStatus=Tee;exports.useAddNewFrame=DZ;exports.useAssignFilter=zee;exports.useAssistantContainer=FW;exports.useAssistantLayoutStore=id;exports.useAssistantPanel=PW;exports.useAssistantProfile=See;exports.useAutoScroll=Dee;exports.useAutoSubmitQueue=_ee;exports.useCard=SCe;exports.useCardFilterValues=D1;exports.useChat=yee;exports.useColumns=zM;exports.useCreateVisualWithFrame=che;exports.useCurrentAIContext=$m;exports.useCurrentActiveCard=$6;exports.useCurrentCardConfig=z6;exports.useCurrentSheetActiveCards=L6;exports.useCurrentUserInfo=Ts;exports.useCustomVisual=pS;exports.useCustomVisualsQuery=kZ;exports.useDashboardActions=Gt;exports.useDashboardCardQuery=pa;exports.useDashboardCreation=l7;exports.useDashboardManagement=a7;exports.useDashboardPreferences=gm;exports.useDashboardQuery=s1;exports.useDashboardStore=Q;exports.useDataColumns=pU;exports.useDateFilterHook=oOe;exports.useDefaultDashboardMutation=z9;exports.useDroppable=nX;exports.useDynamicIcon=EZ;exports.useEditorActions=lr;exports.useEditorAside=Vx;exports.useEditorStore=Ee;exports.useEnsureReactGlobals=bG;exports.useFieldManagement=Fee;exports.useFileActions=rT;exports.useFileAttachments=nT;exports.useFullscreenAssistant=OW;exports.useGroupMembers=iNe;exports.useGroups=QM;exports.useHasDashboardId=zW;exports.useIsDashboardSelected=vae;exports.useIsVisualSelected=wae;exports.useJoinabilityMap=BI;exports.useManagementActions=$b;exports.useManagementStore=Cs;exports.useMessageWindow=Mee;exports.useMutation=Ri;exports.usePivotTableConfig=zm;exports.usePluginQuery=jZ;exports.useQuery=cn;exports.useQueryClient=Qs;exports.useQueueActions=Lm;exports.useResourceManagement=j1;exports.useResourceUpdateState=i7;exports.useRoleAwareDisplayPreferences=Mq;exports.useSelectedVisual=yae;exports.useSemaphorContext=Ge;exports.useSensor=db;exports.useSensors=HR;exports.useSortable=PS;exports.useSyncLegacyEditorState=ote;exports.useTextFilterHook=uOe;exports.useTheme=Ob;exports.useTopoJson=lU;exports.useUnifiedUsers=XM;exports.useUpdateResource=n7;exports.useUpdateVisualMutation=uhe;exports.useUserPreferences=L7;exports.useVisualById=HD;exports.useVisualManagement=lhe;exports.v4=jr;exports.validateFieldForChartType=Pee;exports.verticalListSortingStrategy=YR;