react-semaphor 0.1.116 → 0.1.117

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 (23) hide show
  1. package/dist/chunks/{dashboard-controls-CqcS1J54.js → dashboard-controls-BVyKYGSS.js} +3 -3
  2. package/dist/chunks/{dashboard-controls-CRc6gw-F.js → dashboard-controls-BfjTgw7o.js} +1 -1
  3. package/dist/chunks/{dashboard-json-BOlcQgKG.js → dashboard-json-D6wa6YoM.js} +1 -1
  4. package/dist/chunks/{dashboard-json-D-75FAgQ.js → dashboard-json-DT3-XQFT.js} +1 -1
  5. package/dist/chunks/{edit-dashboard-visual-tRQ806YP.js → edit-dashboard-visual-B783wHIy.js} +1 -1
  6. package/dist/chunks/{edit-dashboard-visual-COf6UbOg.js → edit-dashboard-visual-BiAkxXjP.js} +3 -3
  7. package/dist/chunks/{editor-action-buttons-Bh-TPwiy.js → editor-action-buttons-BmFpFk-_.js} +2 -2
  8. package/dist/chunks/{editor-action-buttons-2B96j5tL.js → editor-action-buttons-CiZYTAan.js} +1 -1
  9. package/dist/chunks/{index-CRDKevb0.js → index-BYYUZIiS.js} +6 -13
  10. package/dist/chunks/{index-F4v-XjnM.js → index-Cwi4U3XN.js} +2 -2
  11. package/dist/chunks/{resource-management-panel-CwGyO8S9.js → resource-management-panel-C9DAKT2s.js} +1 -1
  12. package/dist/chunks/{resource-management-panel-DtwM8NVN.js → resource-management-panel-xtVaOdeV.js} +2 -2
  13. package/dist/chunks/{schedule-dashboard-DWh6NWL5.js → schedule-dashboard-BjjU3_uS.js} +1 -1
  14. package/dist/chunks/{schedule-dashboard-CtXspopT.js → schedule-dashboard-bnGqtUi1.js} +3 -3
  15. package/dist/chunks/{use-visual-utils-Ce0Sq8Hn.js → use-visual-utils-B-h2YrMC.js} +1 -1
  16. package/dist/chunks/{use-visual-utils-DyKq-_On.js → use-visual-utils-DTdxZgvk.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
@@ -973,7 +973,7 @@ Defaulting to \`null\`.`}const mK=fK,tFe=XOe,cR=E.forwardRef(({className:e,value
973
973
  `),"","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(`
974
974
  `)].join(`
975
975
  `))}else{let h=d.props,p=h==null?void 0:h.className,m=typeof p=="function"?(...x)=>W4(p(...x),l.className):W4(p,l.className),g=m?{className:m}:{},b=AK(d.props,Su(y2(l,["ref"])));for(let x in f)x in b&&delete f[x];return N.cloneElement(d,Object.assign({},b,f,u,{ref:s(qFe(d),u.ref)},g))}return N.createElement(o,Object.assign({},y2(l,["ref"]),o!==N.Fragment&&u,o!==N.Fragment&&f),d)}function UFe(){let e=N.useRef([]),t=N.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 WFe(...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 AK(...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 pR(...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 Fi(e){var t;return Object.assign(N.forwardRef(e),{displayName:(t=e.displayName)!=null?t:e.name})}function Su(e){let t=Object.assign({},e);for(let n in t)t[n]===void 0&&delete t[n];return t}function y2(e,t=[]){let n=Object.assign({},e);for(let r of t)r in n&&delete n[r];return n}function qFe(e){return N.version.split(".")[0]>="19"?e.props.ref:e.ref}function YFe(e,t,n){let[r,s]=N.useState(n),o=e!==void 0,i=N.useRef(o),a=N.useRef(!1),l=N.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,yt(u=>(o||s(u),t==null?void 0:t(u)))]}function GFe(e){let[t]=N.useState(e);return t}function PK(e={},t=null,n=[]){for(let[r,s]of Object.entries(e))FK(n,OK(t,r),s);return n}function OK(e,t){return e?e+"["+t+"]":t}function FK(e,t,n){if(Array.isArray(n))for(let[r,s]of n.entries())FK(e,OK(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,""]):PK(n,t,e)}let KFe="span";var mR=(e=>(e[e.None=1]="None",e[e.Focusable=2]="Focusable",e[e.Hidden=4]="Hidden",e))(mR||{});function ZFe(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 Oi()({ourProps:o,theirProps:s,slot:{},defaultTag:KFe,name:"Hidden"})}let $K=Fi(ZFe),XFe=N.createContext(null);function QFe({children:e}){let t=N.useContext(XFe);if(!t)return N.createElement(N.Fragment,null,e);let{target:n}=t;return n?In.createPortal(N.createElement(N.Fragment,null,e),n):null}function JFe({data:e,form:t,disabled:n,onReset:r,overrides:s}){let[o,i]=N.useState(null),a=gx();return N.useEffect(()=>{if(r&&o)return a.addEventListener(o,"reset",r)},[o,t,r]),N.createElement(QFe,null,N.createElement(e5e,{setForm:i,formId:t}),PK(e).map(([l,u])=>N.createElement($K,{features:mR.Hidden,...Su({key:l,as:"input",type:"hidden",hidden:!0,readOnly:!0,form:t,disabled:n,name:l,value:u,...s})})))}function e5e({setForm:e,formId:t}){return N.useEffect(()=>{if(t){let n=document.getElementById(t);n&&e(n)}},[e,t]),t?null:N.createElement($K,{features:mR.Hidden,as:"input",type:"hidden",hidden:!0,readOnly:!0,ref:n=>{if(!n)return;let r=n.closest("form");r&&e(r)}})}let t5e=N.createContext(void 0);function LK(){return N.useContext(t5e)}function n5e(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&&r5e(n)?!1:r}function r5e(e){if(!e)return!1;let t=e.previousElementSibling;for(;t!==null;){if(t instanceof HTMLLegendElement)return!1;t=t.previousElementSibling}return!0}let zK=Symbol();function s5e(e,t=!0){return Object.assign(e,{[zK]:t})}function Cl(...e){let t=N.useRef(e);N.useEffect(()=>{t.current=e},[e]);let n=yt(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[zK]))?void 0:n}let gR=N.createContext(null);gR.displayName="DescriptionContext";function BK(){let e=N.useContext(gR);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,BK),t}return e}function o5e(){var e,t;return(t=(e=N.useContext(gR))==null?void 0:e.value)!=null?t:void 0}let i5e="p";function a5e(e,t){let n=N.useId(),r=hR(),{id:s=`headlessui-description-${n}`,...o}=e,i=BK(),a=Cl(t);Kn(()=>i.register(s),[s,i.register]);let l=r||!1,u=N.useMemo(()=>({...i.slot,disabled:l}),[i.slot,l]),d={ref:a,...i.props,id:s};return Oi()({ourProps:d,theirProps:o,slot:u,defaultTag:i5e,name:i.name||"Description"})}let l5e=Fi(a5e);Object.assign(l5e,{});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=N.createContext(null);xS.displayName="LabelContext";function VK(){let e=N.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,VK),t}return e}function yS(e){var t,n,r;let s=(n=(t=N.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 c5e({inherit:e=!1}={}){let t=yS(),[n,r]=N.useState([]),s=e?[t,...n].filter(Boolean):n;return[s.length>0?s.join(" "):void 0,N.useMemo(()=>function(o){let i=yt(l=>(r(u=>[...u,l]),()=>r(u=>{let d=u.slice(),f=d.indexOf(l);return f!==-1&&d.splice(f,1),d}))),a=N.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 N.createElement(xS.Provider,{value:a},o.children)},[r])]}let u5e="label";function d5e(e,t){var n;let r=N.useId(),s=VK(),o=LK(),i=hR(),{id:a=`headlessui-label-${r}`,htmlFor:l=o??((n=s.props)==null?void 0:n.htmlFor),passive:u=!1,...d}=e,f=Cl(t);Kn(()=>s.register(a),[a,s.register]);let h=yt(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})}}}),p=i||!1,m=N.useMemo(()=>({...s.slot,disabled:p}),[s.slot,p]),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),Oi()({ourProps:g,theirProps:d,slot:m,defaultTag:l?u5e:"div",name:s.name||"Label"})}let f5e=Fi(d5e),h5e=Object.assign(f5e,{});function p5e(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 m5e(e=p5e){return N.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 g5e(e){if(e===null)return{width:0,height:0};let{width:t,height:n}=e.getBoundingClientRect();return{width:t,height:n}}function q4(e,t=!1){let[n,r]=N.useReducer(()=>({}),{}),s=N.useMemo(()=>g5e(e),[e,n]);return Kn(()=>{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 b5e=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 HK(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 UK(e){return N.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}let x5e=new b5e(()=>HK(()=>[],{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 bR(e,t){let n=x5e.get(t),r=N.useId(),s=UK(n);if(Kn(()=>{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 TE=new Map,dg=new Map;function Y4(e){var t;let n=(t=dg.get(e))!=null?t:0;return dg.set(e,n+1),n!==0?()=>G4(e):(TE.set(e,{"aria-hidden":e.getAttribute("aria-hidden"),inert:e.inert}),e.setAttribute("aria-hidden","true"),e.inert=!0,()=>G4(e))}function G4(e){var t;let n=(t=dg.get(e))!=null?t:1;if(n===1?dg.delete(e):dg.set(e,n-1),n!==1)return;let r=TE.get(e);r&&(r["aria-hidden"]===null?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",r["aria-hidden"]),e.inert=r.inert,TE.delete(e))}function y5e(e,{allowed:t,disallowed:n}={}){let r=bR(e,"inert-others");Kn(()=>{var s,o;if(!r)return;let i=ba();for(let l of(s=n==null?void 0:n())!=null?s:[])l&&i.add(Y4(l));let a=(o=t==null?void 0:t())!=null?o:[];for(let l of a){if(!l)continue;let u=mx(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(Y4(f));d=d.parentElement}}return i.dispose},[r,t,n])}function v5e(e,t,n){let r=ef(s=>{let o=s.getBoundingClientRect();o.x===0&&o.y===0&&o.width===0&&o.height===0&&n()});N.useEffect(()=>{if(!e)return;let s=t===null?null:t instanceof HTMLElement?t:t.current;if(!s)return;let o=ba();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 RE=["[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 w5e=(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))(w5e||{}),S5e=(e=>(e[e.Error=0]="Error",e[e.Overflow=1]="Overflow",e[e.Success=2]="Success",e[e.Underflow=3]="Underflow",e))(S5e||{}),C5e=(e=>(e[e.Previous=-1]="Previous",e[e.Next=1]="Next",e))(C5e||{}),WK=(e=>(e[e.Strict=0]="Strict",e[e.Loose=1]="Loose",e))(WK||{});function N5e(e,t=0){var n;return e===((n=mx(e))==null?void 0:n.body)?!1:cl(t,{0(){return e.matches(RE)},1(){let r=e;for(;r!==null;){if(r.matches(RE))return!0;r=r.parentElement}return!1}})}var j5e=(e=>(e[e.Keyboard=0]="Keyboard",e[e.Mouse=1]="Mouse",e))(j5e||{});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 k5e(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 qK(){return/iPhone/gi.test(window.navigator.platform)||/Mac/gi.test(window.navigator.platform)&&window.navigator.maxTouchPoints>0}function E5e(){return/Android/gi.test(window.navigator.userAgent)}function YK(){return qK()||E5e()}function gm(e,t,n,r){let s=ef(n);N.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 _5e(e,t,n,r){let s=ef(n);N.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 K4=30;function D5e(e,t,n){let r=bR(e,"outside-click"),s=ef(n),o=N.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(p){return typeof p=="function"?h(p()):Array.isArray(p)||p instanceof Set?p:[p]}(t);for(let h of f)if(h!==null&&(h.contains(d)||l.composed&&l.composedPath().includes(h)))return;return!N5e(d,WK.Loose)&&d.tabIndex!==-1&&l.preventDefault(),s.current(l,d)},[s,t]),i=N.useRef(null);gm(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),gm(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),gm(r,"click",l=>{YK()||i.current&&(o(l,()=>i.current),i.current=null)},!0);let a=N.useRef({x:0,y:0});gm(r,"touchstart",l=>{a.current.x=l.touches[0].clientX,a.current.y=l.touches[0].clientY},!0),gm(r,"touchend",l=>{let u={x:l.changedTouches[0].clientX,y:l.changedTouches[0].clientY};if(!(Math.abs(u.x-a.current.x)>=K4||Math.abs(u.y-a.current.y)>=K4))return o(l,()=>l.target instanceof HTMLElement?l.target:null)},!0),_5e(r,"blur",l=>o(l,()=>window.document.activeElement instanceof HTMLIFrameElement?window.document.activeElement:null),!0)}function vS(...e){return N.useMemo(()=>mx(...e),[...e])}function M5e(e,t,n,r){let s=ef(n);N.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 GK(e){let t=N.useRef({value:"",selectionStart:null,selectionEnd:null});return M5e(e,"blur",n=>{let r=n.target;r instanceof HTMLInputElement&&(t.current={value:r.value,selectionStart:r.selectionStart,selectionEnd:r.selectionEnd})}),yt(()=>{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 T5e(e,t){return N.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 R5e(){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 I5e(){return qK()?{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=ba();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 A5e(){return{before({doc:e,d:t}){t.style(e.documentElement,"overflow","hidden")}}}function P5e(e){let t={};for(let n of e)Object.assign(t,n(t));return t}let Fu=HK(()=>new Map,{PUSH(e,t){var n;let r=(n=this.get(e))!=null?n:{doc:e,count:0,d:ba(),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:P5e(n)},s=[I5e(),R5e(),A5e()];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)}});Fu.subscribe(()=>{let e=Fu.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)&&Fu.dispatch(n.count>0?"SCROLL_PREVENT":"SCROLL_ALLOW",n),n.count===0&&Fu.dispatch("TEARDOWN",n)}});function O5e(e,t,n=()=>({containers:[]})){let r=UK(Fu),s=t?r.get(t):void 0,o=s?s.count>0:!1;return Kn(()=>{if(!(!t||!e))return Fu.dispatch("PUSH",t,n),()=>Fu.dispatch("POP",t,n)},[e,t]),o}function F5e(e,t,n=()=>[document.body]){let r=bR(e,"scroll-lock");O5e(r,t,s=>{var o;return{containers:[...(o=s.containers)!=null?o:[],n]}})}function Z4(e){return[e.screenX,e.screenY]}function $5e(){let e=N.useRef([-1,-1]);return{wasMoved(t){let n=Z4(t);return e.current[0]===n[0]&&e.current[1]===n[1]?!1:(e.current=n,!0)},update(t){e.current=Z4(t)}}}function L5e(e=0){let[t,n]=N.useState(e),r=N.useCallback(l=>n(l),[t]),s=N.useCallback(l=>n(u=>u|l),[t]),o=N.useCallback(l=>(t&l)===l,[t]),i=N.useCallback(l=>n(u=>u&~l),[n]),a=N.useCallback(l=>n(u=>u^l),[n]);return{flags:t,setFlag:r,addFlag:s,hasFlag:o,removeFlag:i,toggleFlag:a}}var X4,Q4;typeof process<"u"&&typeof globalThis<"u"&&typeof Element<"u"&&((X4=process==null?void 0:process.env)==null?void 0:X4.NODE_ENV)==="test"&&typeof((Q4=Element==null?void 0:Element.prototype)==null?void 0:Q4.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(`
976
- `)),[]});var z5e=(e=>(e[e.None=0]="None",e[e.Closed=1]="Closed",e[e.Enter=2]="Enter",e[e.Leave=4]="Leave",e))(z5e||{});function B5e(e){let t={};for(let n in e)e[n]===!0&&(t[`data-${n}`]="");return t}function V5e(e,t,n,r){let[s,o]=N.useState(n),{hasFlag:i,addFlag:a,removeFlag:l}=L5e(e&&s?3:0),u=N.useRef(!1),d=N.useRef(!1),f=gx();return Kn(()=>{var h;if(e){if(n&&o(!0),!t){n&&a(3);return}return(h=void 0)==null||h.call(r,n),H5e(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 p;d.current&&typeof t.getAnimations=="function"&&t.getAnimations().length>0||(u.current=!1,l(7),n||o(!1),(p=void 0)==null||p.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 H5e(e,{prepare:t,run:n,done:r,inFlight:s}){let o=ba();return W5e(e,{prepare:t,inFlight:s}),o.nextFrame(()=>{n(),o.requestAnimationFrame(()=>{o.add(U5e(e,r))})}),o.dispose}function U5e(e,t){var n,r;let s=ba();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 W5e(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 q5e(e,{container:t,accept:n,walk:r}){let s=N.useRef(n),o=N.useRef(r);N.useEffect(()=>{s.current=n,o.current=r},[n,r]),Kn(()=>{if(!t||!e)return;let i=mx(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 J4(e,t){let n=N.useRef([]),r=yt(e);N.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 Y5e(){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 KK={...E},G5e=KK.useInsertionEffect,K5e=G5e||(e=>e());function ZK(e){const t=E.useRef(()=>{if(process.env.NODE_ENV!=="production")throw new Error("Cannot call an event handler while rendering.")});return K5e(()=>{t.current=e}),E.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 IE=typeof document<"u"?N.useLayoutEffect:N.useEffect;let e3=!1,Z5e=0;const t3=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+Z5e++;function X5e(){const[e,t]=E.useState(()=>e3?t3():void 0);return IE(()=>{e==null&&t(t3())},[]),E.useEffect(()=>{e3=!0},[]),e}const Q5e=KK.useId,J5e=Q5e||X5e;let tb;process.env.NODE_ENV!=="production"&&(tb=new Set);function e4e(){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=tb)!=null&&e.has(s))){var o;(o=tb)==null||o.add(s),console.warn(s)}}function t4e(){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=tb)!=null&&e.has(s))){var o;(o=tb)==null||o.add(s),console.error(s)}}function n4e(){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 r4e=E.createContext(null),s4e=E.createContext(null),o4e=()=>{var e;return((e=E.useContext(r4e))==null?void 0:e.id)||null},i4e=()=>E.useContext(s4e),a4e="data-floating-ui-focusable";function l4e(e){const{open:t=!1,onOpenChange:n,elements:r}=e,s=J5e(),o=E.useRef({}),[i]=E.useState(()=>n4e()),a=o4e()!=null;if(process.env.NODE_ENV!=="production"){const p=r.reference;p&&!es(p)&&t4e("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]=E.useState(r.reference),d=ZK((p,m,g)=>{o.current.openEvent=p?m:void 0,i.emit("openchange",{open:p,event:m,reason:g,nested:a}),n==null||n(p,m,g)}),f=E.useMemo(()=>({setPositionReference:u}),[]),h=E.useMemo(()=>({reference:l||r.reference||null,floating:r.floating||null,domReference:r.reference}),[l,r.reference,r.floating]);return E.useMemo(()=>({dataRef:o,open:t,onOpenChange:d,elements:h,events:i,floatingId:s,refs:f}),[t,d,h,i,s,f])}function c4e(e){e===void 0&&(e={});const{nodeId:t}=e,n=l4e({...e,elements:{reference:null,floating:null,...e.elements}}),r=e.rootContext||n,s=r.elements,[o,i]=E.useState(null),[a,l]=E.useState(null),d=(s==null?void 0:s.domReference)||o,f=E.useRef(null),h=i4e();IE(()=>{d&&(f.current=d)},[d]);const p=nz({...e,elements:{...s,...a&&{reference:a}}}),m=E.useCallback(v=>{const w=es(v)?{getBoundingClientRect:()=>v.getBoundingClientRect(),contextElement:v}:v;l(w),p.refs.setReference(w)},[p.refs]),g=E.useCallback(v=>{(es(v)||v===null)&&(f.current=v,i(v)),(es(p.refs.reference.current)||p.refs.reference.current===null||v!==null&&!es(v))&&p.refs.setReference(v)},[p.refs]),b=E.useMemo(()=>({...p.refs,setReference:g,setPositionReference:m,domReference:f}),[p.refs,g,m]),x=E.useMemo(()=>({...p.elements,domReference:d}),[p.elements,d]),y=E.useMemo(()=>({...p,...r,refs:b,elements:x,nodeId:t}),[p,b,x,t,r]);return IE(()=>{r.dataRef.current.floatingContext=y;const v=h==null?void 0:h.nodesRef.current.find(w=>w.id===t);v&&(v.context=y)}),E.useMemo(()=>({...p,context:y,refs:b,elements:x}),[p,b,x,y])}const n3="active",r3="selected";function v2(e,t,n){const r=new Map,s=n==="item";let o=e;if(s&&e){const{[n3]:i,[r3]:a,...l}=e;o=l}return{...n==="floating"&&{tabIndex:-1,[a4e]:""},...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&&[n3,r3].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,p=arguments.length,m=new Array(p),g=0;g<p;g++)m[g]=arguments[g];return(h=r.get(u))==null?void 0:h.map(b=>b(...m)).find(b=>b!==void 0)}}}else i[u]=d}),i),{})}}function u4e(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=E.useCallback(a=>v2(a,e,"reference"),t),o=E.useCallback(a=>v2(a,e,"floating"),n),i=E.useCallback(a=>v2(a,e,"item"),r);return E.useMemo(()=>({getReferenceProps:s,getFloatingProps:o,getItemProps:i}),[s,o,i])}function s3(e,t){return{...e,rects:{...e.rects,floating:{...e.rects.floating,height:t}}}}const d4e=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}=da(e,t),{rects:f,elements:{floating:h}}=t,p=n.current[i],m=(u==null?void 0:u.current)||h,g=h.clientTop||m.clientTop,b=h.clientTop!==0,x=m.clientTop!==0,y=h===m;if(process.env.NODE_ENV!=="production"&&(t.placement.startsWith("bottom")||e4e('`placement` side must be "bottom" when using the `inner`',"middleware.")),!p)return{};const v={...t,...await mD(-p.offsetTop-h.clientTop-f.reference.height/2-p.offsetHeight/2-o).fn(t)},w=await FC(s3(v,m.scrollHeight+g+h.clientTop),d),S=await FC(v,{...d,elementContext:"reference"}),C=Jr(0,w.top),j=v.y+C,_=(m.scrollHeight>m.clientHeight?M=>M:Mg)(Jr(0,m.scrollHeight+(b&&y||x?g*2:0)-C-Jr(0,w.bottom)));if(m.style.maxHeight=_+"px",m.scrollTop=C,s){const M=m.offsetHeight<p.offsetHeight*fl(a,n.current.length)-1||S.top>=-l||S.bottom>=-l;gc.flushSync(()=>s(M))}return r&&(r.current=await FC(s3({...v,y:j},m.offsetHeight+g+h.clientTop),d)),{y:j}}});function f4e(e,t){const{open:n,elements:r}=e,{enabled:s=!0,overflowRef:o,scrollRef:i,onChange:a}=t,l=ZK(a),u=E.useRef(!1),d=E.useRef(null),f=E.useRef(null);E.useEffect(()=>{if(!s)return;function p(g){if(g.ctrlKey||!m||o.current==null)return;const b=g.deltaY,x=o.current.top>=-.5,y=o.current.bottom>=-.5,v=m.scrollHeight-m.clientHeight,w=b<0?-1:1,S=b<0?"max":"min";m.scrollHeight<=m.clientHeight||(!x&&b>0||!y&&b<0?(g.preventDefault(),gc.flushSync(()=>{l(C=>C+Math[S](b,v*w))})):/firefox/i.test(Y5e())&&(m.scrollTop+=b))}const m=(i==null?void 0:i.current)||r.floating;if(n&&m)return m.addEventListener("wheel",p),requestAnimationFrame(()=>{d.current=m.scrollTop,o.current!=null&&(f.current={...o.current})}),()=>{d.current=null,f.current=null,m.removeEventListener("wheel",p)}},[s,n,r.floating,o,i,l]);const h=E.useMemo(()=>({onKeyDown(){u.current=!0},onWheel(){u.current=!1},onPointerMove(){u.current=!1},onScroll(){const p=(i==null?void 0:i.current)||r.floating;if(!(!o.current||!p||!u.current)){if(d.current!==null){const m=p.scrollTop-d.current;(o.current.bottom<-.5&&m<-1||o.current.top<-.5&&m>1)&&gc.flushSync(()=>l(g=>g+m))}requestAnimationFrame(()=>{d.current=p.scrollTop})}}}),[r.floating,l,o,i]);return E.useMemo(()=>s?{floating:h}:{},[s,h])}let bx=N.createContext({styles:void 0,setReference:()=>{},setFloating:()=>{},getReferenceProps:()=>({}),getFloatingProps:()=>({}),slot:{}});bx.displayName="FloatingContext";let xR=N.createContext(null);xR.displayName="PlacementContext";function h4e(e){return N.useMemo(()=>e?typeof e=="string"?{to:e}:e:null,[e])}function p4e(){return N.useContext(bx).setReference}function m4e(){let{getFloatingProps:e,slot:t}=N.useContext(bx);return N.useCallback((...n)=>Object.assign({},e(...n),{"data-anchor":t.anchor}),[e,t])}function g4e(e=null){e===!1&&(e=null),typeof e=="string"&&(e={to:e});let t=N.useContext(xR),n=N.useMemo(()=>e,[JSON.stringify(e,(s,o)=>{var i;return(i=o==null?void 0:o.outerHTML)!=null?i:o})]);Kn(()=>{t==null||t(n??null)},[t,n]);let r=N.useContext(bx);return N.useMemo(()=>[r.setFloating,e?r.styles:{}],[r.setFloating,e,r.styles])}let o3=4;function b4e({children:e,enabled:t=!0}){let[n,r]=N.useState(null),[s,o]=N.useState(0),i=N.useRef(null),[a,l]=N.useState(null);x4e(a);let u=t&&n!==null&&a!==null,{to:d="bottom",gap:f=0,offset:h=0,padding:p=0,inner:m}=y4e(n,a),[g,b="center"]=d.split(" ");Kn(()=>{u&&o(0)},[u]);let{refs:x,floatingStyles:y,context:v}=c4e({open:u,placement:g==="selection"?b==="center"?"bottom":`bottom-${b}`:b==="center"?`${g}`:`${g}-${b}`,strategy:"absolute",transform:!1,middleware:[mD({mainAxis:g==="selection"?0:f,crossAxis:h}),rz({padding:p}),g!=="selection"&&sz({padding:p}),g==="selection"&&m?d4e({...m,padding:p,overflowRef:i,offset:s,minItemsVisible:o3,referenceOverflowThreshold:p,onFallbackChange(M){var R,O;if(!M)return;let T=v.elements.floating;if(!T)return;let I=parseFloat(getComputedStyle(T).scrollPaddingBottom)||0,F=Math.min(o3,T.childElementCount),z=0,B=0;for(let $ of(O=(R=v.elements.floating)==null?void 0:R.childNodes)!=null?O:[])if($ instanceof HTMLElement){let P=$.offsetTop,V=P+$.clientHeight+I,L=T.scrollTop,A=L+T.clientHeight;if(P>=L&&V<=A)F--;else{B=Math.max(0,Math.min(V,A)-Math.max(P,L)),z=$.clientHeight;break}}F>=1&&o($=>{let P=z*F-B+I;return $>=P?$:P})}}):null,oz({padding:p,apply({availableWidth:M,availableHeight:R,elements:O}){Object.assign(O.floating.style,{overflow:"auto",maxWidth:`${M}px`,maxHeight:`min(var(--anchor-max-height, 100vh), ${R}px)`})}})].filter(Boolean),whileElementsMounted:ez}),[w=g,S=b]=v.placement.split("-");g==="selection"&&(w="selection");let C=N.useMemo(()=>({anchor:[w,S].filter(Boolean).join(" ")}),[w,S]),j=f4e(v,{overflowRef:i,onChange:o}),{getReferenceProps:D,getFloatingProps:k}=u4e([j]),_=yt(M=>{l(M),x.setFloating(M)});return E.createElement(xR.Provider,{value:r},E.createElement(bx.Provider,{value:{setFloating:_,setReference:x.setReference,styles:y,getReferenceProps:D,getFloatingProps:k,slot:C}},e))}function x4e(e){Kn(()=>{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 y4e(e,t){var n,r,s;let o=w2((n=e==null?void 0:e.gap)!=null?n:"var(--anchor-gap, 0)",t),i=w2((r=e==null?void 0:e.offset)!=null?r:"var(--anchor-offset, 0)",t),a=w2((s=e==null?void 0:e.padding)!=null?s:"var(--anchor-padding, 0)",t);return{...e,gap:o,offset:i,padding:a}}function w2(e,t,n=void 0){let r=gx(),s=yt((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=i3(l,u);return[d,f=>{let h=XK(l);{let p=h.map(m=>window.getComputedStyle(u).getPropertyValue(m));r.requestAnimationFrame(function m(){r.nextFrame(m);let g=!1;for(let[x,y]of h.entries()){let v=window.getComputedStyle(u).getPropertyValue(y);if(p[x]!==v){p[x]=v,g=!0;break}}if(!g)return;let b=i3(l,u);d!==b&&(f(b),d=b)})}return r.dispose}]}return[n,null]}),o=N.useMemo(()=>s(e,t)[0],[e,t]),[i=o,a]=N.useState();return Kn(()=>{let[l,u]=s(e,t);if(a(l),!!u)return u(a)},[e,t]),i}function XK(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,...XK(s)]:[r]}return[]}function i3(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 v4e({children:e,freeze:t}){let n=AE(t,e);return N.createElement(N.Fragment,null,n)}function AE(e,t){let[n,r]=N.useState(t);return!e&&n!==t&&r(t),e?n:t}let yR=N.createContext(null);yR.displayName="OpenClosedContext";var nb=(e=>(e[e.Open=1]="Open",e[e.Closed=2]="Closed",e[e.Closing=4]="Closing",e[e.Opening=8]="Opening",e))(nb||{});function w4e(){return N.useContext(yR)}function S4e({value:e,children:t}){return N.createElement(yR.Provider,{value:e},t)}function C4e(e){function t(){document.readyState!=="loading"&&(e(),document.removeEventListener("DOMContentLoaded",t))}typeof window<"u"&&typeof document<"u"&&(document.addEventListener("DOMContentLoaded",t),t())}let Eu=[];C4e(()=>{function e(t){if(!(t.target instanceof HTMLElement)||t.target===document.body||Eu[0]===t.target)return;let n=t.target;n=n.closest(RE),Eu.unshift(n??t.target),Eu=Eu.filter(r=>r!=null&&r.isConnected),Eu.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 N4e(e){throw new Error("Unexpected object: "+e)}var gr=(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))(gr||{});function a3(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:N4e(e)}}var vR=(e=>(e[e.Left=0]="Left",e[e.Right=2]="Right",e))(vR||{});function j4e(e){let t=yt(e),n=N.useRef(!1);N.useEffect(()=>(n.current=!1,()=>{n.current=!0,IK(()=>{n.current&&t()})}),[t])}function k4e(){let e=typeof document>"u";return"useSyncExternalStore"in E?(t=>t.useSyncExternalStore)(E)(()=>()=>{},()=>!1,()=>!e):!1}function E4e(){let e=k4e(),[t,n]=E.useState(od.isHandoffComplete);return t&&od.isHandoffComplete===!1&&n(!1),E.useEffect(()=>{t!==!0&&n(!0)},[t]),E.useEffect(()=>od.handoff(),[]),e?!1:t}let _4e=N.createContext(!1);function D4e(){return N.useContext(_4e)}function M4e(e){let t=D4e(),n=N.useContext(JK),r=vS(e),[s,o]=N.useState(()=>{var i;if(!t&&n!==null)return(i=n.current)!=null?i:null;if(od.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 N.useEffect(()=>{s!==null&&(r!=null&&r.body.contains(s)||r==null||r.body.appendChild(s))},[s,r]),N.useEffect(()=>{t||n!==null&&o(n.current)},[n,o,t]),s}let QK=N.Fragment,T4e=Fi(function(e,t){let n=e,r=N.useRef(null),s=Cl(s5e(f=>{r.current=f}),t),o=vS(r),i=M4e(r),[a]=N.useState(()=>{var f;return od.isServer?null:(f=o==null?void 0:o.createElement("div"))!=null?f:null}),l=N.useContext(P4e),u=E4e();Kn(()=>{!i||!a||i.contains(a)||(a.setAttribute("data-headlessui-portal",""),i.appendChild(a))},[i,a]),Kn(()=>{if(a&&l)return l.register(a)},[l,a]),j4e(()=>{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=Oi();return u?!i||!a?null:In.createPortal(d({ourProps:{ref:s},theirProps:n,slot:{},defaultTag:QK,name:"Portal"}),a):null});function R4e(e,t){let n=Cl(t),{enabled:r=!0,...s}=e,o=Oi();return r?N.createElement(T4e,{...s,ref:n}):o({ourProps:{ref:n},theirProps:s,slot:{},defaultTag:QK,name:"Portal"})}let I4e=N.Fragment,JK=N.createContext(null);function A4e(e,t){let{target:n,...r}=e,s={ref:Cl(t)},o=Oi();return N.createElement(JK.Provider,{value:n},o({ourProps:s,theirProps:r,defaultTag:I4e,name:"Popover.Group"}))}let P4e=N.createContext(null),O4e=Fi(R4e),F4e=Fi(A4e),$4e=Object.assign(O4e,{Group:F4e});var L4e=(e=>(e[e.Open=0]="Open",e[e.Closed=1]="Closed",e))(L4e||{}),z4e=(e=>(e[e.Single=0]="Single",e[e.Multi=1]="Multi",e))(z4e||{}),B4e=(e=>(e[e.Pointer=0]="Pointer",e[e.Focus=1]="Focus",e[e.Other=2]="Other",e))(B4e||{}),V4e=(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))(V4e||{});function S2(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):k5e(r,i=>i.dataRef.current.domRef.current),o=n?s.indexOf(n):null;return o===-1&&(o=null),{options:s,activeOptionIndex:o}}let H4e={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===gr.Specific?t.idx:a3(t,{resolveItems:()=>u,resolveActiveIndex:()=>{var p,m;return(m=(p=e.activeOptionIndex)!=null?p:u.findIndex(g=>!d(g)))!=null?m: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=S2(e);if(i.activeOptionIndex===null){let u=i.options.findIndex(d=>!d.dataRef.current.disabled);u!==-1&&(i.activeOptionIndex=u)}let a=t.focus===gr.Specific?t.idx:a3(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=S2(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=S2(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}},wR=N.createContext(null);wR.displayName="ComboboxActionsContext";function xx(e){let t=N.useContext(wR);if(t===null){let n=new Error(`<${e} /> is missing a parent <Combobox /> component.`);throw Error.captureStackTrace&&Error.captureStackTrace(n,xx),n}return t}let eZ=N.createContext(null);function U4e(e){let t=Hp("VirtualProvider"),{options:n}=t.virtual,[r,s]=N.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=VT({enabled:n.length!==0,scrollPaddingStart:r,scrollPaddingEnd:s,count:n.length,estimateSize(){return 40},getScrollElement(){return t.optionsElement},overscan:12}),[i,a]=N.useState(0);Kn(()=>{a(u=>u+1)},[n]);let l=o.getVirtualItems();return l.length===0?null:N.createElement(eZ.Provider,{value:o},N.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 N.createElement(N.Fragment,{key:u.key},N.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 rb=N.createContext(null);rb.displayName="ComboboxDataContext";function Hp(e){let t=N.useContext(rb);if(t===null){let n=new Error(`<${e} /> is missing a parent <Combobox /> component.`);throw Error.captureStackTrace&&Error.captureStackTrace(n,Hp),n}return t}function W4e(e,t){return cl(t.type,H4e,e,t)}let q4e=N.Fragment;function Y4e(e,t){var n,r;let s=hR(),{value:o,defaultValue:i,onChange:a,form:l,name:u,by:d,disabled:f=s||!1,onClose:h,__demoMode:p=!1,multiple:m=!1,immediate:g=!1,virtual:b=null,nullable:x,...y}=e,v=GFe(i),[w=m?[]:void 0,S]=YFe(o,a,v),[C,j]=N.useReducer(W4e,{dataRef:N.createRef(),comboboxState:p?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:p}),D=N.useRef(!1),k=N.useRef({static:!1,hold:!1}),_=m5e(d),M=yt(ne=>b?d===null?b.options.indexOf(ne):b.options.findIndex(ae=>_(ae,ne)):C.options.findIndex(ae=>_(ae.dataRef.current.value,ne))),R=N.useCallback(ne=>cl(T.mode,{1:()=>w.some(ae=>_(ae,ne)),0:()=>_(w,ne)}),[w]),O=yt(ne=>C.activeOptionIndex===M(ne)),T=N.useMemo(()=>({...C,immediate:g,optionsPropsRef:k,value:w,defaultValue:v,disabled:f,mode:m?1:0,virtual:b?C.virtual:null,get activeOptionIndex(){if(D.current&&C.activeOptionIndex===null&&(b?b.options.length>0:C.options.length>0)){if(b){let ae=b.options.findIndex(ie=>{var fe,xe;return!((xe=(fe=b.disabled)==null?void 0:fe.call(b,ie))!=null&&xe)});if(ae!==-1)return ae}let ne=C.options.findIndex(ae=>!ae.dataRef.current.disabled);if(ne!==-1)return ne}return C.activeOptionIndex},calculateIndex:M,compare:_,isSelected:R,isActive:O}),[w,v,f,m,p,C,b]);Kn(()=>{var ne;b&&j({type:7,options:b.options,disabled:(ne=b.disabled)!=null?ne:null})},[b,b==null?void 0:b.options,b==null?void 0:b.disabled]),Kn(()=>{C.dataRef.current=T},[T]);let I=T.comboboxState===0;D5e(I,[T.buttonElement,T.inputElement,T.optionsElement],()=>H.closeCombobox());let F=N.useMemo(()=>{var ne,ae,ie;return{open:T.comboboxState===0,disabled:f,activeIndex:T.activeOptionIndex,activeOption:T.activeOptionIndex===null?null:T.virtual?T.virtual.options[(ne=T.activeOptionIndex)!=null?ne:0]:(ie=(ae=T.options[T.activeOptionIndex])==null?void 0:ae.dataRef.current.value)!=null?ie:null,value:w}},[T,f,w]),z=yt(()=>{if(T.activeOptionIndex!==null){if(H.setIsTyping(!1),T.virtual)A(T.virtual.options[T.activeOptionIndex]);else{let{dataRef:ne}=T.options[T.activeOptionIndex];A(ne.current.value)}H.goToOption(gr.Specific,T.activeOptionIndex)}}),B=yt(()=>{j({type:0}),D.current=!0}),$=yt(()=>{j({type:1}),D.current=!1,h==null||h()}),P=yt(ne=>{j({type:3,isTyping:ne})}),V=yt((ne,ae,ie)=>(D.current=!1,ne===gr.Specific?j({type:2,focus:gr.Specific,idx:ae,trigger:ie}):j({type:2,focus:ne,trigger:ie}))),L=yt((ne,ae)=>(j({type:4,payload:{id:ne,dataRef:ae}}),()=>{T.isActive(ae.current.value)&&(D.current=!0),j({type:5,id:ne})})),A=yt(ne=>cl(T.mode,{0(){return S==null?void 0:S(ne)},1(){let ae=T.value.slice(),ie=ae.findIndex(fe=>_(fe,ne));return ie===-1?ae.push(ne):ae.splice(ie,1),S==null?void 0:S(ae)}})),W=yt(ne=>{j({type:6,trigger:ne})}),U=yt(ne=>{j({type:8,element:ne})}),Y=yt(ne=>{j({type:9,element:ne})}),K=yt(ne=>{j({type:10,element:ne})}),H=N.useMemo(()=>({onChange:A,registerOption:L,goToOption:V,setIsTyping:P,closeCombobox:$,openCombobox:B,setActivationTrigger:W,selectActiveOption:z,setInputElement:U,setButtonElement:Y,setOptionsElement:K}),[]),[q,X]=c5e(),Z=t===null?{}:{ref:t},G=N.useCallback(()=>{if(v!==void 0)return S==null?void 0:S(v)},[S,v]),Q=Oi();return N.createElement(X,{value:q,props:{htmlFor:(r=T.inputElement)==null?void 0:r.id},slot:{open:T.comboboxState===0,disabled:f}},N.createElement(b4e,null,N.createElement(wR.Provider,{value:H},N.createElement(rb.Provider,{value:T},N.createElement(S4e,{value:cl(T.comboboxState,{0:nb.Open,1:nb.Closed})},u!=null&&N.createElement(JFe,{disabled:f,data:w!=null?{[u]:w}:{},form:l,onReset:G}),Q({ourProps:Z,theirProps:y,slot:F,defaultTag:q4e,name:"Combobox"}))))))}let G4e="input";function K4e(e,t){var n,r,s,o,i;let a=Hp("Combobox.Input"),l=xx("Combobox.Input"),u=N.useId(),d=LK(),{id:f=d||`headlessui-combobox-input-${u}`,onChange:h,displayValue:p,disabled:m=a.disabled||!1,autoFocus:g=!1,type:b="text",...x}=e,y=N.useRef(null),v=Cl(y,t,p4e(),l.setInputElement),w=vS(a.inputElement),S=gx(),C=yt(()=>{l.onChange(null),a.optionsElement&&(a.optionsElement.scrollTop=0),l.goToOption(gr.Nothing)}),j=N.useMemo(()=>{var A;return typeof p=="function"&&a.value!==void 0?(A=p(a.value))!=null?A:"":typeof a.value=="string"?a.value:""},[a.value,p]);J4(([A,W],[U,Y])=>{if(a.isTyping)return;let K=y.current;K&&((Y===0&&W===1||A!==U)&&(K.value=A),requestAnimationFrame(()=>{if(a.isTyping||!K||(w==null?void 0:w.activeElement)!==K)return;let{selectionStart:H,selectionEnd:q}=K;Math.abs((q??0)-(H??0))===0&&H===0&&K.setSelectionRange(K.value.length,K.value.length)}))},[j,a.comboboxState,w,a.isTyping]),J4(([A],[W])=>{if(A===0&&W===1){if(a.isTyping)return;let U=y.current;if(!U)return;let Y=U.value,{selectionStart:K,selectionEnd:H,selectionDirection:q}=U;U.value="",U.value=Y,q!==null?U.setSelectionRange(K,H,q):U.setSelectionRange(K,H)}},[a.comboboxState]);let D=N.useRef(!1),k=yt(()=>{D.current=!0}),_=yt(()=>{S.nextFrame(()=>{D.current=!1})}),M=yt(A=>{switch(l.setIsTyping(!0),A.key){case ys.Enter:if(a.comboboxState!==0||D.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(),cl(a.comboboxState,{0:()=>l.goToOption(gr.Next),1:()=>l.openCombobox()});case ys.ArrowUp:return A.preventDefault(),A.stopPropagation(),cl(a.comboboxState,{0:()=>l.goToOption(gr.Previous),1:()=>{In.flushSync(()=>l.openCombobox()),a.value||l.goToOption(gr.Last)}});case ys.Home:if(A.shiftKey)break;return A.preventDefault(),A.stopPropagation(),l.goToOption(gr.First);case ys.PageUp:return A.preventDefault(),A.stopPropagation(),l.goToOption(gr.First);case ys.End:if(A.shiftKey)break;return A.preventDefault(),A.stopPropagation(),l.goToOption(gr.Last);case ys.PageDown:return A.preventDefault(),A.stopPropagation(),l.goToOption(gr.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&&C(),l.closeCombobox());case ys.Tab:if(a.comboboxState!==0)return;a.mode===0&&a.activationTrigger!==1&&l.selectActiveOption(),l.closeCombobox();break}}),R=yt(A=>{h==null||h(A),a.mode===0&&A.target.value===""&&C(),l.openCombobox()}),O=yt(A=>{var W,U,Y;let K=(W=A.relatedTarget)!=null?W:Eu.find(H=>H!==A.currentTarget);if(!((U=a.optionsElement)!=null&&U.contains(K))&&!((Y=a.buttonElement)!=null&&Y.contains(K))&&a.comboboxState===0)return A.preventDefault(),a.mode===0&&a.value===null&&C(),l.closeCombobox()}),T=yt(A=>{var W,U,Y;let K=(W=A.relatedTarget)!=null?W:Eu.find(H=>H!==A.currentTarget);(U=a.buttonElement)!=null&&U.contains(K)||(Y=a.optionsElement)!=null&&Y.contains(K)||a.disabled||a.immediate&&a.comboboxState!==0&&S.microTask(()=>{In.flushSync(()=>l.openCombobox()),l.setActivationTrigger(1)})}),I=yS(),F=o5e(),{isFocused:z,focusProps:B}=RK({autoFocus:g}),{isHovered:$,hoverProps:P}=TK({isDisabled:m}),V=N.useMemo(()=>({open:a.comboboxState===0,disabled:m,hover:$,focus:z,autofocus:g}),[a,$,z,g,m]),L=pR({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":F,"aria-autocomplete":"list",defaultValue:(i=(o=e.defaultValue)!=null?o:a.defaultValue!==void 0?p==null?void 0:p(a.defaultValue):null)!=null?i:a.defaultValue,disabled:m||void 0,autoFocus:g,onCompositionStart:k,onCompositionEnd:_,onKeyDown:M,onChange:R,onFocus:T,onBlur:O},B,P);return Oi()({ourProps:L,theirProps:x,slot:V,defaultTag:G4e,name:"Combobox.Input"})}let Z4e="button";function X4e(e,t){var n;let r=Hp("Combobox.Button"),s=xx("Combobox.Button"),o=Cl(t,s.setButtonElement),i=N.useId(),{id:a=`headlessui-combobox-button-${i}`,disabled:l=r.disabled||!1,autoFocus:u=!1,...d}=e,f=GK(r.inputElement),h=yt(j=>{switch(j.key){case ys.Space:case ys.Enter:j.preventDefault(),j.stopPropagation(),r.comboboxState===1&&In.flushSync(()=>s.openCombobox()),f();return;case ys.ArrowDown:j.preventDefault(),j.stopPropagation(),r.comboboxState===1&&(In.flushSync(()=>s.openCombobox()),r.value||s.goToOption(gr.First)),f();return;case ys.ArrowUp:j.preventDefault(),j.stopPropagation(),r.comboboxState===1&&(In.flushSync(()=>s.openCombobox()),r.value||s.goToOption(gr.Last)),f();return;case ys.Escape:if(r.comboboxState!==0)return;j.preventDefault(),r.optionsElement&&!r.optionsPropsRef.current.static&&j.stopPropagation(),In.flushSync(()=>s.closeCombobox()),f();return;default:return}}),p=yt(j=>{j.preventDefault(),!n5e(j.currentTarget)&&(j.button===vR.Left&&(r.comboboxState===0?s.closeCombobox():s.openCombobox()),f())}),m=yS([a]),{isFocusVisible:g,focusProps:b}=RK({autoFocus:u}),{isHovered:x,hoverProps:y}=TK({isDisabled:l}),{pressed:v,pressProps:w}=zFe({disabled:l}),S=N.useMemo(()=>({open:r.comboboxState===0,active:v||r.comboboxState===0,disabled:l,value:r.value,hover:x,focus:g}),[r,x,g,v,l]),C=pR({ref:o,id:a,type:T5e(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":m,disabled:l||void 0,autoFocus:u,onMouseDown:p,onKeyDown:h},b,y,w);return Oi()({ourProps:C,theirProps:d,slot:S,defaultTag:Z4e,name:"Combobox.Button"})}let Q4e="div",J4e=ME.RenderStrategy|ME.Static;function e3e(e,t){var n,r,s;let o=N.useId(),{id:i=`headlessui-combobox-options-${o}`,hold:a=!1,anchor:l,portal:u=!1,modal:d=!0,transition:f=!1,...h}=e,p=Hp("Combobox.Options"),m=xx("Combobox.Options"),g=h4e(l);g&&(u=!0);let[b,x]=g4e(g),[y,v]=N.useState(null),w=m4e(),S=Cl(t,g?b:null,m.setOptionsElement,v),C=vS(p.optionsElement),j=w4e(),[D,k]=V5e(f,y,j!==null?(j&nb.Open)===nb.Open:p.comboboxState===0);v5e(D,p.inputElement,m.closeCombobox);let _=p.__demoMode?!1:d&&p.comboboxState===0;F5e(_,C);let M=p.__demoMode?!1:d&&p.comboboxState===0;y5e(M,{allowed:N.useCallback(()=>[p.inputElement,p.buttonElement,p.optionsElement],[p.inputElement,p.buttonElement,p.optionsElement])}),Kn(()=>{var L;p.optionsPropsRef.current.static=(L=e.static)!=null?L:!1},[p.optionsPropsRef,e.static]),Kn(()=>{p.optionsPropsRef.current.hold=a},[p.optionsPropsRef,a]),q5e(p.comboboxState===0,{container:p.optionsElement,accept(L){return L.getAttribute("role")==="option"?NodeFilter.FILTER_REJECT:L.hasAttribute("role")?NodeFilter.FILTER_SKIP:NodeFilter.FILTER_ACCEPT},walk(L){L.setAttribute("role","none")}});let R=yS([(n=p.buttonElement)==null?void 0:n.id]),O=N.useMemo(()=>({open:p.comboboxState===0,option:void 0}),[p.comboboxState]),T=yt(()=>{m.setActivationTrigger(0)}),I=yt(L=>{L.preventDefault(),m.setActivationTrigger(0)}),F=pR(g?w():{},{"aria-labelledby":R,role:"listbox","aria-multiselectable":p.mode===1?!0:void 0,id:i,ref:S,style:{...h.style,...x,"--input-width":q4(p.inputElement,!0).width,"--button-width":q4(p.buttonElement,!0).width},onWheel:p.activationTrigger===0?void 0:T,onMouseDown:I,...B5e(k)}),z=D&&p.comboboxState===1,B=AE(z,(r=p.virtual)==null?void 0:r.options),$=AE(z,p.value),P=yt(L=>p.compare($,L));if(p.virtual){if(B===void 0)throw new Error("Missing `options` in virtual mode");Object.assign(h,{children:N.createElement(rb.Provider,{value:B!==p.virtual.options?{...p,virtual:{...p.virtual,options:B}}:p},N.createElement(U4e,{slot:O},h.children))})}let V=Oi();return N.createElement($4e,{enabled:u?e.static||D:!1},N.createElement(rb.Provider,{value:p.mode===1?p:{...p,isSelected:P}},V({ourProps:F,theirProps:{...h,children:N.createElement(v4e,{freeze:z},typeof h.children=="function"?(s=h.children)==null?void 0:s.call(h,O):h.children)},slot:O,defaultTag:Q4e,features:J4e,visible:D,name:"Combobox.Options"})))}let t3e="div";function n3e(e,t){var n,r,s,o;let i=Hp("Combobox.Option"),a=xx("Combobox.Option"),l=N.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,...p}=e,m=GK(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=N.useRef(null),y=ef({disabled:f,value:d,domRef:x,order:h}),v=N.useContext(eZ),w=Cl(t,x,v?v.measureElement:null),S=yt(()=>{a.setIsTyping(!1),a.onChange(d)});Kn(()=>a.registerOption(u,y),[y,u]);let C=N.useRef(!(i.virtual||i.__demoMode));Kn(()=>{if(!i.virtual&&!i.__demoMode)return ba().requestAnimationFrame(()=>{C.current=!0})},[i.virtual,i.__demoMode]),Kn(()=>{if(C.current&&i.comboboxState===0&&g&&i.activationTrigger!==0)return ba().requestAnimationFrame(()=>{var I,F;(F=(I=x.current)==null?void 0:I.scrollIntoView)==null||F.call(I,{block:"nearest"})})},[x,g,i.comboboxState,i.activationTrigger,i.activeOptionIndex]);let j=yt(I=>{I.preventDefault(),I.button===vR.Left&&(f||(S(),YK()||requestAnimationFrame(()=>m()),i.mode===0&&a.closeCombobox()))}),D=yt(()=>{if(f)return a.goToOption(gr.Nothing);let I=i.calculateIndex(d);a.goToOption(gr.Specific,I)}),k=$5e(),_=yt(I=>k.update(I)),M=yt(I=>{if(!k.wasMoved(I)||f||g)return;let F=i.calculateIndex(d);a.goToOption(gr.Specific,F,0)}),R=yt(I=>{k.wasMoved(I)&&(f||g&&(i.optionsPropsRef.current.hold||a.goToOption(gr.Nothing)))}),O=N.useMemo(()=>({active:g,focus:g,selected:b,disabled:f}),[g,b,f]),T={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:j,onFocus:D,onPointerEnter:_,onMouseEnter:_,onPointerMove:M,onMouseMove:M,onPointerLeave:R,onMouseLeave:R};return Oi()({ourProps:T,theirProps:p,slot:O,defaultTag:t3e,name:"Combobox.Option"})}let r3e=Fi(Y4e),tZ=Fi(X4e),nZ=Fi(K4e),s3e=h5e,rZ=Fi(e3e),sZ=Fi(n3e),o3e=Object.assign(r3e,{Input:nZ,Button:tZ,Label:s3e,Options:rZ,Option:sZ});function i3e({elementId:e}){const t=N.useRef(!1);return N.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 a3e=N.memo(({option:e,currentStyle:t})=>c.jsxs(sZ,{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(Rr,{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 l3e({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:p,onQueryChange:m,filterDataType:g,onEnterKey:b,activeFilterValue:x}){const[y,v]=N.useState(""),w=p!==void 0?p:y,S=m||v,C=ee(T=>T.themeStyle),j=s||e;function D(T,I){if(I)return"";const F=[">","<",">=","<=","="];return(g?Vo(g):!1)&&x&&F.includes(x.operation)?`${x.operation}${x.values[0]}`:T!=null&&T.length?T==null?void 0:T.map(B=>B.value).join(", "):""}function k(T){Array.isArray(T)||(T=[T]),t(T)}function _(){return d||j&&j.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 R(){return w||!(e!=null&&e.length)?null:c.jsxs("div",{className:"border-b border-b-muted px-4 py-2 text-xs text-muted-foreground",children:["Showing top ",e.length," values. Type to search more..."]})}function O(){return!r||!(j!=null&&j.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(dn,{className:"border-muted-foreground/50",checked:o,onCheckedChange:i})]})]})}return c.jsx(o3e,{multiple:r,value:n,onChange:k,onClose:()=>{S("")},by:(T,I)=>Array.isArray(T)||Array.isArray(I)?!1:!T||!I?T===I:T.id===I.id,children:({open:T})=>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(nZ,{className:J("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:C==null?void 0:C.controlInputRadius},displayValue:I=>D(I,T),onChange:I=>S(I.target.value),onKeyDown:I=>{if(I.key==="Enter"&&b){const F=/^(>=|<=|>|<|=)/.test(w.trim()),z=g?Vo(g):!1;F&&z&&(I.preventDefault(),b()&&I.target.blur())}}}),c.jsx(tZ,{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(Ys,{className:"size-4 text-muted-foreground transition-colors group-hover:text-foreground"})})]}),c.jsxs(rZ,{anchor:"bottom",transition:!0,style:{borderRadius:C==null?void 0:C.controlInputRadius},className:ld("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:[T&&c.jsx(i3e,{elementId:"headlessui-portal-root"}),M(),R(),_(),O(),j==null?void 0:j.map(I=>c.jsx(a3e,{option:I,currentStyle:C},I.id))]})]})})}const l3=[{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:"⇎"}],c3e=new Set(["=",">","<",">=","<=","between","not between"]);function u3e(e){return c3e.has(e)?e:">="}function d3e({filter:e}){var S;const[t,n]=N.useState(">="),[r,s]=N.useState(""),[o,i]=N.useState(""),[a,l]=N.useState(""),[u,d]=N.useState(!0),f=N.useRef(null),h=N.useRef(!1),[,p]=N.useTransition(),m=ig(r,300),g=ig(o,300),b=ig(a,300),x=ee(C=>C.filterValues),y=ee(C=>C.themeStyle),{addOrUpdateFilterValue:v,removeFilterValues:w}=Yt();return N.useEffect(()=>()=>{f.current=null,h.current=!1},[]),N.useEffect(()=>{const C=x==null?void 0:x.find(j=>j.filterId===e.id);if(C&&C.operation!=="in"){const j=u3e(C.operation);if(f.current!==j&&(n(j),f.current=j,h.current=!1),j==="between"||j==="not between"){const k=C.values[0],_=C.values[1];i(k!=null?String(k):""),l(_!=null?String(_):""),s("")}else{const k=C.values[0];s(k!=null?String(k):""),i(""),l("")}}else f.current!==null&&(s(""),i(""),l(""),!h.current&&f.current!==t&&(n(">="),h.current=!1),f.current=null),d(!1)},[x,e.id]),N.useEffect(()=>{u&&(t==="between"||t==="not between"?g===o&&b===a&&d(!1):m===r&&d(!1))},[u,t,r,m,o,a,g,b]),N.useEffect(()=>{if(!u)if(t==="between"||t==="not between"){const C=g&&g.trim()!=="",j=b&&b.trim()!=="";if(!C||!j){!C&&!j&&(p(()=>{w(e.id)}),f.current=t);return}const D=Number(g),k=Number(b);if(isNaN(D)||isNaN(k))return;const _={filterId:e.id,connectionType:e.database==="NA"?"api":"database",name:e.column,valueType:hi(e),operation:t,values:[D,k]};p(()=>{v(_)}),f.current=t}else{if(!m||m.trim()===""){p(()=>{w(e.id)}),f.current=null;return}const C=Number(m);if(isNaN(C))return;const j={filterId:e.id,connectionType:e.database==="NA"?"api":"database",name:e.column,valueType:hi(e),operation:t,values:[C]};p(()=>{v(j)}),f.current=t}},[t,m,g,b,e.id,e.column,e.database,u,v,w,e]),c.jsxs("div",{className:"flex gap-2",children:[c.jsxs(rt,{value:t,onValueChange:C=>{h.current=!0,n(C)},children:[c.jsx(Je,{className:"h-8 w-16",style:{borderRadius:y==null?void 0:y.controlInputRadius},children:c.jsx("span",{className:"font-mono text-base",children:(S=l3.find(C=>C.value===t))==null?void 0:S.symbol})}),c.jsx(et,{children:l3.map(C=>c.jsx(pe,{value:C.value,children:c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-mono",children:C.symbol}),c.jsx("span",{children:C.label})]})},C.value))})]}),t==="between"||t==="not between"?c.jsxs(c.Fragment,{children:[c.jsx(Bn,{type:"number",placeholder:"Min",value:o,onChange:C=>i(C.target.value),className:"h-8 flex-1",style:{borderRadius:y==null?void 0:y.controlInputRadius}}),c.jsx(Bn,{type:"number",placeholder:"Max",value:a,onChange:C=>l(C.target.value),className:"h-8 flex-1",style:{borderRadius:y==null?void 0:y.controlInputRadius}})]}):c.jsx(Bn,{type:"number",placeholder:"Value",value:r,onChange:C=>s(C.target.value),className:"h-8 flex-1",style:{borderRadius:y==null?void 0:y.controlInputRadius}})]})}function f3e({filter:e}){const t=e.searchMode==="numeric",n=ee(v=>v.themeStyle),{filteredRecords:r,isSingleSelect:s,allSelected:o,handleChange:i,handleSelectAll:a,handleApplyOperatorExpression:l,query:u,setQuery:d,isLoading:f,isFetching:h,isError:p,selectedRecords:m,isSearching:g,searchError:b,resultSource:x,activeFilterValue:y}=bS(e,{enableServerSearch:!0,searchDebounceMs:300,minSearchLength:2,searchThreshold:5});return f||h?c.jsx(Ho,{style:{borderRadius:n==null?void 0:n.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"}):t?c.jsx(d3e,{filter:e}):c.jsx(l3e,{showNegativeIndicator:e.operation==="not in",renderFilterModeButton:()=>c.jsx(h3e,{filter:e}),inputClassName:"h-8",options:r,selectedOptions:m,onChange:i,multiple:!s,selectAllChecked:o,onSelectAllCheckedChange:a,isSearching:g,resultSource:x,searchError:b,query:u,onQueryChange:d,filterDataType:e.dataType,activeFilterValue:y,onEnterKey:l})}function h3e({filter:e}){const t=e.operation==="in"?"include":"exclude",{setFilterMode:n,setFilterDefaultValues:r}=Yt(),s=ee(d=>d.isDashboardEditing),o=ee(d=>{var f;return(f=d.filterValues)==null?void 0:f.find(h=>h.filterId===e.id)});function i(){t==="include"?n(e.id,"exclude"):n(e.id,"include")}function a(){o!=null&&o.values&&r(e.id,o.values)}const l=(o==null?void 0:o.values)&&o.values.length>0,u=e.defaultValues&&e.defaultValues.length>0;return c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:i,variant:"secondary",size:"sm",className:J("h-6 text-xs hover:underline",{}),children:Gw(t)}),s&&c.jsx(oe,{onClick:a,variant:u?"default":"ghost",size:"sm",className:J("h-6 text-xs",{"opacity-50":!l}),disabled:!l,title:u?"Update default values":l?"Set current selection as default":"Select values to set as default",children:"Default"})]})}function p3e({filter:e}){var o;const{filteredRecords:t,handleChange:n,selectedRecords:r}=bS(e);function s(i){n([{value:i,id:i}])}return c.jsx(ga,{onValueChange:s,value:((o=r==null?void 0:r[0])==null?void 0:o.value)||"",className:"mt-2 flex gap-3 overflow-x-auto",children:t==null?void 0:t.map(i=>c.jsxs("div",{className:"flex gap-2",children:[c.jsx(Nr,{value:i.value,id:"r1"}),c.jsx(ce,{className:"text-muted-foreground",htmlFor:"r1",children:i.value})]},i.value))})}function m3e({filter:e}){var d;const t=ee(f=>f.themeStyle),{filteredRecords:n,handleChange:r,selectedRecords:s,isLoading:o,isFetching:i,isError:a}=bS(e),l=n&&n.length>10;function u(f){r([{value:f,id:f}])}return o||i?c.jsx(Ho,{style:{borderRadius:t==null?void 0:t.controlInputRadius},className:"h-8 w-full bg-foreground/10"}):a?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:[l&&c.jsx("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:c.jsx(Yn,{children:c.jsxs(bn,{delayDuration:0,children:[c.jsx(xn,{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(xr,{className:"h-3 w-3 text-amber-600"}),c.jsxs("span",{className:"text-amber-600",children:["Many options (",n.length,")"]})]})}),c.jsx(Cn,{side:"bottom",className:"max-w-xs",children:c.jsxs("p",{className:"text-xs",children:["This filter has ",n.length," options. Consider using a dropdown for better usability with many options."]})})]})})}),c.jsx(cs,{value:((d=s==null?void 0:s[0])==null?void 0:d.value)||"",onValueChange:u,className:"w-full",children:c.jsx(Wr,{className:"h-9 flex-wrap justify-start overflow-x-auto",children:n==null?void 0:n.map(f=>c.jsx(Ht,{className:"h-7",value:f.value,children:f.value},f.value))})})]})}function wS({filter:e}){return Lc(e.dataType)?c.jsx(gFe,{filter:e}):e.uiType==="radio"&&e.type==="single"?c.jsx(p3e,{filter:e}):e.uiType==="tabs"&&e.type==="single"?c.jsx(m3e,{filter:e}):c.jsx(f3e,{filter:e})}function g3e({frame:e}){const[t,n]=N.useState(!1),r=e==null?void 0:e.cards[0],{data:s,isPending:o,isError:i}=ha(r),a=e==null?void 0:e.cards[1],{data:l,isLoading:u,isFetching:d}=ha(a);return(a==null?void 0:a.type)!=="text"?c.jsx(eb,{card:r,data:(s==null?void 0:s.records)||[],isPending:o,isError:i}):c.jsxs(Ds,{className:J("group relative overflow-y-auto",t?"m-4":"mx-0"),children:[t?c.jsx("div",{className:"overflow-y-auto break-words p-1",children:c.jsx(Hh,{card:a,data:(l==null?void 0:l.records)||[],isLoading:!1})}):c.jsx(eb,{card:r,data:(s==null?void 0:s.records)||[],isPending:o,isError:i}),c.jsx("div",{className:J("fixed z-10",{"invisible bottom-4 right-4 group-hover:visible":t,"right-6 top-6":!t}),children:c.jsx(fx,{disabled:u||d,className:J("h-7 p-1"),pressed:t,onPressedChange:n,"aria-label":"Toggle bold",children:t?c.jsx(mae,{className:"size-4 text-muted-foreground/70"}):c.jsx(gae,{className:"size-4 text-muted-foreground/70"})})})]})}function hw(e){return{clickFilter:ac,drillToDetail:rD,drillThrough:lv,drillToURL:n1,drillDown:yae,drillUp:vae,dynamicDrill:xa,inlineDrill:r1}[e]||ac}function tf(e){return{clickFilter:"Filter Dashboard",drillToDetail:"Show Details",drillThrough:"Navigate to Dashboard",drillToURL:"Open External Link",drillDown:"Drill Down",drillUp:"Drill Up",dynamicDrill:"Explore Field",inlineDrill:"Drill"}[e]||"Interaction"}function b3e(e,t,n,r,s){const o=hw(e.mode),i=e.label||tf(e.mode),a=x3e(e,t,n,r,s);return{label:i,icon:o,targetInfo:a,interaction:e}}function x3e(e,t,n=0,r,s){var o,i,a,l,u,d;switch(e.mode){case"clickFilter":{if((o=e.applyToCardIds)!=null&&o.length){const f=e.applyToCardIds.length;return`Apply to ${f} ${f===1?"card":"cards"}`}return(i=e.excludeCardIds)!=null&&i.length?"Apply to all cards":"Apply to other cards"}case"drillToDetail":{if(e.targetInsightId)return"Drill into Insight";const f=((a=e.detailFields)==null?void 0:a.length)||0;return f>0?`Show ${f} detail ${f===1?"field":"fields"}`:"Show detail table"}case"drillThrough":return e.targetDashboardId,"Navigate to dashboard";case"drillToURL":{if(e.urlTemplate)try{return`Open ${new URL(e.urlTemplate).hostname}`}catch{return"Open external link"}return"Open external link"}case"drillDown":{if(e.hierarchyId&&t){const f=t.find(h=>h.id===e.hierarchyId);if(f&&f.steps.length>0){let h;if((f.type==="date"||f.baseField)&&r&&f.baseField){const p=C_(f,r,s),m=S_(f,p);h=m==null?void 0:m.field}else h=(l=f.steps[n])==null?void 0:l.field;return h?h.label:n>=f.steps.length?"End of path":f.label||"Drill by hierarchy"}}return"Drill to next level"}case"drillUp":{if(n>0&&e.hierarchyId&&t){const f=t.find(h=>h.id===e.hierarchyId);if(f&&f.steps.length>0){const h=(u=f.steps[n-2])==null?void 0:u.field;return h?`Back to ${h.label}`:`Back to All: ${f.label||"Data"}`}}return"Go back one level"}case"dynamicDrill":{if(e.drillField)return`Drill into ${e.drillField.label} data`;if((d=e.availableFields)!=null&&d.length){const f=e.availableFields.length;return`Choose from ${f} ${f===1?"dimension":"dimensions"}`}return"Explore dimension"}case"inlineDrill":{const f=e.inlineLimit||100,h=e.displayMode||"table";return`Show ${f} records as ${h}`}default:return""}}function y3e(e,t,n,r,s){return e.map(o=>b3e(o,t,n,r,s))}function v3e({open:e,onOpenChange:t,position:n,interactions:r,selectedConditions:s,onSelectInteraction:o,drillHierarchies:i,cardId:a,card:l}){const{currentDepth:u,breadcrumbs:d}=Lt(w=>{var S,C,j;return{currentDepth:a?((C=(S=w.interactionStates[a])==null?void 0:S.breadcrumbs)==null?void 0:C.length)??0:0,breadcrumbs:a?((j=w.interactionStates[a])==null?void 0:j.breadcrumbs)??[]:[]}}),f=E.useMemo(()=>y3e(r,i,u,l,d),[r,i,u,l,d]),h=E.useMemo(()=>{if(s.length===0)return"";const w=s[0];if(w.label){const S=w.label.split(/[=><]/);if(S.length>1)return S[1].trim()}return String(w.value)},[s]);if(E.useEffect(()=>{if(!e)return;const w=S=>{S.key==="Escape"&&t(!1)};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[e,t]),!e||!n)return null;const p=280,m=80+f.length*60,g=window.innerWidth,b=window.innerHeight;let x=n.x,y=n.y+8;x+p>g&&(x=Math.max(8,g-p-8)),y+m>b&&(y=Math.max(8,n.y-m-8));const v=c.jsxs("div",{className:"semaphor-scope",style:{position:"fixed",inset:0,pointerEvents:"none",background:"transparent"},children:[c.jsx("div",{className:"fixed inset-0",style:{zIndex:50,pointerEvents:"auto",background:"transparent"},onClick:()=>t(!1),"aria-hidden":"true"}),c.jsxs("div",{className:J("fixed rounded-lg border bg-popover shadow-lg","animate-in fade-in-0 zoom-in-95"),style:{left:`${x}px`,top:`${y}px`,zIndex:51,width:`${p}px`,maxHeight:"400px",pointerEvents:"auto"},role:"menu","aria-label":"Select interaction",children:[h&&c.jsxs("div",{className:"border-b px-4 py-3",children:[c.jsx("p",{className:"text-xs text-muted-foreground",children:"Selected"}),c.jsx("p",{className:"text-sm font-medium",children:h})]}),c.jsx("div",{className:"max-h-80 overflow-y-auto py-1",children:f.map((w,S)=>{var D;const C=w.icon,j=w.interaction.mode==="dynamicDrill"&&(S===0||((D=f[S-1])==null?void 0:D.interaction.mode)!=="dynamicDrill");return c.jsxs(E.Fragment,{children:[j&&c.jsx("div",{className:"border-t px-4 py-2",children:c.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"⚡ Explore Other Fields"})}),c.jsxs("button",{className:J("flex w-full items-start gap-3 px-4 py-3","hover:bg-accent hover:text-accent-foreground","cursor-pointer transition-colors","border-b text-left last:border-b-0"),onClick:()=>{o(w.interaction),t(!1)},role:"menuitem",children:[c.jsx("div",{className:"mt-0.5 flex-shrink-0",children:c.jsx(C,{className:"h-4 w-4 text-muted-foreground"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("p",{className:"mb-1 text-sm font-medium leading-none",children:w.label}),w.targetInfo&&c.jsx("p",{className:"text-xs text-muted-foreground",children:w.targetInfo})]})]})]},S)})})]})]});return In.createPortal(v,document.body)}function w3e(e){const t=N.useRef([]),n=N.useRef(null),r=N.useRef(null),o=di(e.interactionConfig).some(h=>h.mode==="clickFilter"&&h.trigger!==void 0),i=qm(h=>h.registerClearBlurCallback),a=qm(h=>h.unregisterCard);N.useEffect(()=>{const h=()=>{r.current&&f(r.current)};return i(e.id,h),()=>{a(e.id)}},[e.id,i,a]);function l({chart:h,selectedSegments:p,storedOriginalColorsRef:m}){if(!h||!h.canvas||!h.canvas.ownerDocument){console.warn("Chart or canvas is null when trying to toggle blur segments");return}const g=h.data.datasets;m.current||(m.current=g.map((x,y)=>h.getDatasetMeta(y).data.map(w=>w.options.backgroundColor)));const b=m.current;g.forEach((x,y)=>{const v=b[y];if(p.length===0){x.backgroundColor=[...v];return}x.backgroundColor=v.map((w,S)=>p.some(j=>j.datasetIndex===y&&j.dataIndex===S)?w:u(w,.2))});try{h.update()}catch(x){console.warn("Failed to update chart during blur toggle:",x)}}function u(h,p=.2){if(h.startsWith("rgba"))return h.replace(/[\d.]+\)$/g,`${p})`);if(h.startsWith("#")){const m=parseInt(h.slice(1,3),16),g=parseInt(h.slice(3,5),16),b=parseInt(h.slice(5,7),16);return`rgba(${m}, ${g}, ${b}, ${p})`}return h}function d(h,p){var v;if(!o||!p)return;r.current=p;const m=p.getElementsAtEventForMode(h,"nearest",{intersect:!0},!0);if(!m.length)return;const{datasetIndex:g,index:b}=m[0],x={datasetIndex:g,dataIndex:b};if(((v=h.native)==null?void 0:v.shiftKey)||h.shiftKey){const w=t.current.findIndex(S=>S.datasetIndex===g&&S.dataIndex===b);w>=0?t.current.splice(w,1):t.current.push(x)}else{const w=t.current.length===1&&t.current[0].datasetIndex===g&&t.current[0].dataIndex===b;t.current=w?[]:[x]}l({chart:p,selectedSegments:t.current,storedOriginalColorsRef:n})}function f(h){h&&(t.current=[],n.current&&l({chart:h,selectedSegments:[],storedOriginalColorsRef:n}))}return{handleChartClick:d,clearBlur:f}}function S3e({resolvedCardConfig:e,card:t,records:n,chart:r,clickEvent:s}){var u,d,f,h,p,m,g,b,x,y;const o=r==null?void 0:r.getElementsAtEventForMode(s,"nearest",{intersect:!0},!0);if(!o.length)return;const i=o[0].datasetIndex,a=o[0].index,l=(d=(u=o[0].element)==null?void 0:u.$context)==null?void 0:d.raw;console.log("datasetIndex",i),console.log("clickIndex",a),console.log("value",l);try{if(!(n!=null&&n.length))return;const{keys:v}=rr(n),{groupByColumns:w=[],pivotByColumns:S=[],metricColumns:C=[]}=e||t.config,j=D=>w.find(k=>k.label===D)||S.find(k=>k.label===D)||C.find(k=>k.label===D);if(t.type==="map"){const D=v[0],k=((h=(f=l==null?void 0:l.feature)==null?void 0:f.properties)==null?void 0:h.name)||((m=(p=l==null?void 0:l.feature)==null?void 0:p.properties)==null?void 0:m.NAME),_=j(D);return!_||k==null?void 0:{conditions:[{field:_,operator:"=",value:k}]}}if(["pie","funnel","doughnut"].includes(t.type)){const D=v[0],k=v==null?void 0:v[1+i],_=j(D),M=j(k),R=(g=n==null?void 0:n[a])==null?void 0:g[D];if(!_||R==null){console.log("no dim field or value",D,R);return}return{conditions:[{field:_,operator:"=",value:R}],metrics:M?[{field:M,value:l}]:void 0}}if(["stackedBar","bar","line"].includes(t.type)){const D=v[0],k=j(D),_=(b=n==null?void 0:n[a])==null?void 0:b[D];if(!k||_==null){console.log("no dim field or value for stacked bar",D,_);return}const M=C[i]||C[0];if(!M){console.log("no metric field found");return}const R=S[0],T=Object.keys(n[0]).filter(B=>B!==D)[i],F=(T?(x=n==null?void 0:n[a])==null?void 0:x[T]:(y=n==null?void 0:n[a])==null?void 0:y[M.label])??l,z=[{field:k,operator:"=",value:_}];return R&&T&&z.push({field:R,operator:"=",value:T}),{conditions:z,metrics:[{field:M,value:F}]}}}catch(v){console.error("getClickContextFromChart error",v)}}function C3e(e){return e&&typeof e=="object"&&"field"in e&&"operator"in e}function N3e(e){return e&&typeof e=="object"&&"filterId"in e&&"operation"in e&&"values"in e}function oZ({filters:e,filterDefinitions:t,contextMode:n,className:r,showLabel:s=!0,labelText:o="Applied Filters:",icon:i}){if(!e||e.length===0)return n==="none"?c.jsx("div",{className:"px-6 pb-4",children:c.jsx("span",{className:"text-xs text-muted-foreground",children:"No filters applied"})}):null;const l=e.map(u=>{var d,f;if(C3e(u))return{fieldName:((d=u.field)==null?void 0:d.label)||((f=u.field)==null?void 0:f.name)||"Unknown",operator:u.operator,value:k3e(u)};if(N3e(u)){const h=t==null?void 0:t.find(p=>p.id===u.filterId);return{fieldName:(h==null?void 0:h.title)||u.name,operator:u.operation,value:j3e(u)}}else return{fieldName:"Unknown",operator:"=",value:String(u)}}).reduce((u,d)=>(u[d.fieldName]||(u[d.fieldName]=[]),u[d.fieldName].push(d),u),{});return c.jsxs("div",{className:r||"border-b px-6 pb-4",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s&&i&&c.jsxs("div",{className:"flex items-center gap-2 text-foreground/80",children:[i,c.jsx("span",{className:"whitespace-nowrap text-sm font-medium",children:o})]}),s&&!i&&c.jsx("span",{className:"whitespace-nowrap text-sm text-muted-foreground",children:o}),c.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(l).map(([u,d])=>c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsxs("span",{className:"text-sm font-medium",children:[u,":"]}),d.map((f,h)=>c.jsx(Fe,{variant:"outline",className:"cursor-pointer select-none border-primary/20 bg-gradient-to-r from-primary/5 to-primary/10 text-primary shadow-sm transition-all hover:from-primary/10 hover:to-primary/15 hover:shadow-md dark:border-primary/30 dark:from-primary/10 dark:to-primary/20 dark:text-primary dark:hover:from-primary/15 dark:hover:to-primary/25",children:f.value},`${u}-${h}`))]},u))})]}),n&&c.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:[n==="interactionFilters"&&c.jsx("span",{children:"Showing data filtered by interaction only"}),n==="full"&&c.jsx("span",{children:"Showing data with all dashboard filters + interaction filters"}),n==="none"&&c.jsx("span",{children:"Showing all data (no filters applied)"})]})]})}function j3e(e){const{values:t,operation:n}=e;return!t||t.length===0?"":n==="="||n==="!="||n===">"||n==="<"||n===">="||n==="<="?String(t[0]):n==="in"||n==="not in"?t.map(r=>String(r)).join(", "):(n==="between"||n==="not between")&&t.length===2?`${t[0]} - ${t[1]}`:String(t[0])}function k3e(e){const{operator:t,value:n}=e;if(e.label){const r=e.label.split(/[=><]/);if(r.length>1)return r[1].trim()}switch(t){case"=":return String(n);case"!=":return`≠ ${n}`;case">":return`> ${n}`;case"<":return`< ${n}`;case">=":return`≥ ${n}`;case"<=":return`≤ ${n}`;case"in":return Array.isArray(n)?n.join(", "):String(n);case"not in":return`not ${Array.isArray(n)?n.join(", "):n}`;case"contains":return`contains ${n}`;case"startsWith":return`starts with ${n}`;case"endsWith":return`ends with ${n}`;case"between":return Array.isArray(n)?`between ${n[0]} and ${n[1]}`:String(n);case"not between":return Array.isArray(n)?`not between ${n[0]} and ${n[1]}`:String(n);case"isNull":return"is null";case"isNotNull":return"is not null";default:return String(n)}}function E3e({cardId:e,className:t}){const n=Lt(d=>d.interactionStates[e]),r=Lt(d=>d.popInteractionStep),s=Lt(d=>d.resetInteractionState),o=(n==null?void 0:n.breadcrumbs)??[];if(n==null||n.hierarchyId,o.length===0)return null;const i=d=>{const f=o.length-d-1;for(let h=0;h<f;h++)r(e)},a=()=>{s(e)},l=d=>(d.sourceFilterGroups[0],d.toField?d.toField.label||d.toField.name:"Drill Step"),u=d=>{const f=d.sourceFilterGroups.flatMap(h=>h.filters);return c.jsxs("div",{className:"max-w-xs space-y-2 text-sm",children:[f.length>0&&c.jsx(oZ,{filters:f,className:"pb-2",labelText:"Drill Down Filters:",icon:c.jsx(Cae,{className:"h-4 w-4 text-foreground/80"})}),d.granularity&&c.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[c.jsx(os,{className:"h-4 w-4 text-foreground/80"}),c.jsxs("span",{className:"text-sm font-medium text-foreground/80",children:["Granularity: ",d.granularity]})]}),d.metric&&c.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[c.jsx(lae,{className:"h-4 w-4 text-foreground/80"}),c.jsxs("span",{className:"text-sm font-medium text-foreground/80",children:["Value:"," ",d.metric.formattedValue||d.metric.value]})]})]})};return c.jsx(Yn,{children:c.jsxs("div",{className:J("flex items-center gap-1 text-sm",t),children:[c.jsx(bn,{children:c.jsx(xn,{asChild:!0,children:c.jsx("button",{className:"flex items-center p-0 text-muted-foreground hover:text-foreground",onClick:a,"aria-label":"Reset drill path",children:c.jsx(K_,{className:"h-3.5 w-3.5"})})})}),c.jsx(Ci,{className:"ml-0.5 h-3 w-3 text-muted-foreground"}),c.jsx("div",{className:"flex items-center",children:o.map((d,f)=>c.jsxs("div",{className:"flex items-center",children:[f>0&&c.jsx(Ci,{className:"mx-1 h-3 w-3 text-muted-foreground"}),c.jsxs(bn,{delayDuration:0,children:[c.jsx(xn,{asChild:!0,children:c.jsx(oe,{variant:"link",size:"sm",className:"h-6 px-1 text-muted-foreground no-underline hover:text-foreground hover:no-underline",onClick:()=>i(f),"aria-label":`Go back to: ${l(d)}`,children:l(d)})}),c.jsx(lR,{className:"ml-4",side:"bottom",children:u(d)})]})]},f))})]})})}function _3e(e){switch(e){case"content-only":return{showHeader:!1,showTitle:!1,showDescription:!1,showTabs:!1,showFooter:!1,showFilters:!1,showBreadcrumbs:!1,showRefreshIndicator:!1,showFilterInfo:!1};case"print":return{showHeader:!0,showTitle:!0,showDescription:!0,showTabs:!1,showFilters:!1,showBreadcrumbs:!1,showRefreshIndicator:!1,showFilterInfo:!1,showTableToolbar:!1,showColumnSettings:!1};case"embed":return{showHeader:!1,showTitle:!0,showDescription:!1,showTabs:!0,showFooter:!1,showFilters:!1,showBreadcrumbs:!1,showRefreshIndicator:!1,showFilterInfo:!1};case"table-print":return{showHeader:!1,showTitle:!0,showDescription:!1,showTabs:!1,showFooter:!1,showFilters:!1,showBreadcrumbs:!1,showRefreshIndicator:!1,showFilterInfo:!1,showPagination:!1,showTableToolbar:!1,showColumnSettings:!1};case"full":default:return{showHeader:!0,showTitle:!0,showDescription:!0,showTabs:!0,showFooter:!0,showFilters:!0,showBreadcrumbs:!0,showRefreshIndicator:!0,showFilterInfo:!0}}}function SR({children:e,displayPreferences:t={mode:"full"},currentUser:n}){const r=N.useMemo(()=>{const s=t.mode||"full",o=_3e(s),i=vq(n||null),a={mode:s,overrides:{...o,...i,...t.overrides}};return{displayPreferences:a,shouldShowElement:u=>{var d;return((d=a.overrides)==null?void 0:d[u])??!0}}},[t,n]);return c.jsx(zB.Provider,{value:r,children:e})}function c3({card:e,frame:t}){var ie,fe,xe,Ce,je,de,Re,Oe,mt;const{customCards:n,placeholders:r,tokenProps:s}=qe(),{shouldShowElement:o}=Bc(),i=Lt(be=>be.interactionStates[e.id]),a=((ie=i==null?void 0:i.breadcrumbs)==null?void 0:ie.length)>0,l=ee(be=>be.themeStyle),u=ee(be=>be.selectedSheetId),d=ee(be=>be.isDashboardEditing);ee(be=>be.selectedLensId);const f=ee(be=>be.dashboard.filters),h=f==null?void 0:f.find(be=>be.id===t.filterId&&!be.hide),{setCardTitle:p,setCardDescription:m,setSelectedFrameId:g,updateFilter:b}=Yt(),{updateFrame:x}=Yt(),{handleChartClick:y}=w3e(e),v=o("showHeader")&&(((fe=e.customCardPreferences)==null?void 0:fe.showCardHeader)??!0),{isError:w,isLoading:S,isFetching:C,cfg:j,isPending:D,data:k,handleDatapointClick:_,pagination:M,comparisonMetadata:R}=Kb(e),O=N.useMemo(()=>(k==null?void 0:k.records)||[],[k==null?void 0:k.records]),[T,I]=N.useState({open:!1,position:null,interactions:[],context:null}),{breadcrumbs:F,hierarchyId:z}=Lt(be=>{var se,ue;return{breadcrumbs:((se=be.interactionStates[e.id])==null?void 0:se.breadcrumbs)??[],hierarchyId:(ue=be.interactionStates[e.id])==null?void 0:ue.hierarchyId}}),B=(be,se,ue)=>{var Nt;const we=F.length>0?[{mode:"drillUp",trigger:(Nt=be[0])==null?void 0:Nt.trigger,label:"Drill Up",hierarchyId:z}]:[],Se=[];for(const Ke of be)if(Ke.mode==="dynamicDrill"&&Ke.availableFields){const $t=Ke.availableFields.filter(Ne=>!F.some(Dt=>{var hn;return((hn=Dt.toField)==null?void 0:hn.id)===Ne.id}));for(const Ne of $t)Se.push({mode:"dynamicDrill",trigger:Ke.trigger,drillField:Ne,label:Ne.label,availableFields:Ke.availableFields})}const Pe=be.filter(Ke=>Ke.mode!=="dynamicDrill"),Qe=[...we,...Pe,...Se];I({open:!0,position:ue||{x:0,y:0},interactions:Qe,context:se})},{handlePointerInteraction:$,applySelectedInteraction:P}=t6(e,t.id,u||"",B),V=N_(e),L=N.useMemo(()=>{var be;return e.type!=="pivotTable"||!((be=k==null?void 0:k.records)!=null&&be.length)?null:{records:k.records,columnSubtotalMeta:k.columnSubtotalMeta,subtotalColumns:k.subtotalColumns||[],pivotSchema:k.pivotSchema||[],groupByColumns:k.groupByColumns}},[e.type,k==null?void 0:k.records,k==null?void 0:k.columnSubtotalMeta,k==null?void 0:k.subtotalColumns,k==null?void 0:k.pivotSchema,k==null?void 0:k.groupByColumns]),A=Pp(e,L),W=(be,se)=>{const ue={...e,paginationConfig:{page:be+1,pageSize:se}},we={...t,cards:t.cards.map(Se=>Se.id===e.id?ue:Se)};u&&x(u,we)},U=be=>{var Se,Pe;const se=gY(be,(Se=e.config)==null?void 0:Se.metricColumns,(Pe=e.config)==null?void 0:Pe.groupByColumns),ue={...e,config:{...e.config||{},sortByColumns:se}},we={...t,cards:t.cards.map(Qe=>Qe.id===e.id?ue:Qe)};u&&x(u,we)};function Y(be,se){be.stopPropagation();const ue=S3e({resolvedCardConfig:V,card:e,records:(k==null?void 0:k.records)||[],chart:se,clickEvent:be.nativeEvent});if(!ue)return;const we=di(e.interactionConfig),Se=Uw(we,ue),Pe=Se.length===1&&Se[0].mode==="clickFilter",Qe=Se.some($t=>$t.mode==="dynamicDrill"),Nt=Se.length>1||Qe;be.button===0&&Pe&&!Nt&&y(be.nativeEvent,se);const Ke={shift:be.shiftKey,ctrl:be.ctrlKey,meta:be.metaKey};be.button===0?$({context:ue,gesture:"leftClick",modifierKeys:Ke,position:{x:be.clientX,y:be.clientY}}):be.button===2&&$({context:ue,gesture:"rightClick",modifierKeys:Ke,position:{x:be.clientX,y:be.clientY}})}function K(){var be,se,ue;if(n&&n.length>0){const we=n.find(Se=>Se.cardId===e.id);if(we&&we.replaceDefault){const Se=we.content;if(Se)return c.jsx(Se,{card:e})}}if(e.type==="kpi"){if(((be=t==null?void 0:t.cards)==null?void 0:be.length)===1)return c.jsx(eb,{card:e,data:w?[]:(k==null?void 0:k.records)||[],isPending:D,isError:w});if(((se=t==null?void 0:t.cards)==null?void 0:se.length)>1)return c.jsx(g3e,{frame:t})}return e.type==="text"&&((ue=t==null?void 0:t.cards)==null?void 0:ue.length)===1?c.jsx(Ds,{className:"my-4 overflow-y-auto break-words px-4",children:c.jsx(Hh,{isLoading:S||C,card:e,data:(k==null?void 0:k.records)||[]})}):ne}function H(){if(w)return c.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[c.jsx(eD,{className:"size-8 text-destructive"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Error fetching data. Check your card settings."})]});if((S||C)&&(!(k!=null&&k.records)||k.records.length===0))return e.type==="table"?c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(yK,{})}):c.jsx("div",{className:"flex h-full w-full items-center justify-center",children:c.jsx(_c,{size:"md",color:"muted","aria-label":"Loading data"})});if(k!=null&&k.records&&(k==null?void 0:k.records.length)===0)return r!=null&&r.NoRecords?c.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:r.NoRecords}):c.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[c.jsx(sD,{className:"size-8 text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(e.type==="table")return c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(rx,{card:e,data:O,paginationMetadata:M,onPaginationChange:W,onSortChange:U,isLoading:S||C,frameId:t.id,sheetId:u||"",onMultipleInteractions:B})});if(e.type==="pivotTable"&&A)return c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(ax,{card:e,data:A.data,options:A.options,onAggregationChange:be=>{const se=jE(be,e.config),ue={...e,config:se},we={...t,cards:t.cards.map(Se=>Se.id===e.id?ue:Se)};u&&x(u,we)},onAggregationLabelChange:be=>{const se=wK(be,e.config),ue={...e,config:se},we={...t,cards:t.cards.map(Se=>Se.id===e.id?ue:Se)};u&&x(u,we)}})});if(e.type==="aggregateTable")return c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(aS,{card:e,data:(k==null?void 0:k.records)||[],groupByColumns:k==null?void 0:k.groupByColumns,pivotSchema:k==null?void 0:k.pivotSchema,paginationMetadata:M,onPaginationChange:W,onAggregationChange:be=>{const se=jE(be,e.config),ue={...e,config:se},we={...t,cards:t.cards.map(Se=>Se.id===e.id?ue:Se)};u&&x(u,we)},isLoading:S||C})});if(e.type==="text")return c.jsx(Ds,{className:"overflow-y-auto break-words pr-2",children:c.jsx(Hh,{isLoading:S||C,card:e,data:(k==null?void 0:k.records)||[]})});if(e.type==="custom")return c.jsx(wl,{FallbackComponent:uS,children:c.jsx(eR,{frame:t,card:e})});if(n&&n.length>0){const be=n.find(se=>se.cardId===e.id);if(be&&be.content){const se=be.content;return c.jsx(se,{card:e})}}if(j)return c.jsx(ix,{cfg:j,onChartClick:Y,onDatapointClick:_})}function q(){if(n&&n.length>0){const be=n.find(se=>se.cardId===e.id);if(be&&be.footer){const se=be.footer;if(se)return c.jsx(se,{card:e})}}return null}function X(){var ue;const be=t.cards.filter(we=>{var Se;return!((Se=we.tabTitle)!=null&&Se.endsWith("__Header"))&&(we.displayTab===!0||we.displayTab===void 0)}),se=l==null?void 0:l.controlInputRadius;return c.jsx(cs,{value:t.activeCardId,className:"flex items-center justify-end gap-3",onValueChange:we=>{const Se={...t,activeCardId:we};x(u,Se)},children:c.jsx(Wr,{style:{borderRadius:l==null?void 0:l.controlInputRadius},className:"flex-end flex h-9 flex-wrap items-center border border-border bg-background p-0",children:(ue=t.cards.filter(we=>{var Se;return!((Se=we.tabTitle)!=null&&Se.endsWith("__Header"))&&(we.displayTab===!0||we.displayTab===void 0)}))==null?void 0:ue.map((we,Se)=>c.jsx(Ht,{className:J("h-full items-center rounded-none data-[state=active]:bg-muted data-[state=active]:shadow-none",{"border-r":Se!==be.length-1}),style:{borderTopLeftRadius:Se===0?se:0,borderTopRightRadius:Se===be.length-1?se:0,borderBottomLeftRadius:Se===0?se:0,borderBottomRightRadius:Se===be.length-1?se:0},value:we.id,children:we.tabTitle||we.title},we.id))})})}function Z(){var se,ue,we,Se;let be=t.cards.find(Pe=>Pe.type==="kpi"&&Pe.tabTitle===`${e.tabTitle}__Header`);return be||(be=t.cards.find(Pe=>Pe.type==="kpi"&&Pe.tabTitle==="All__Header")),be?c.jsx("div",{className:"flex items-end gap-2",children:c.jsx(aFe,{renderFilterInfo:()=>{var Pe,Qe,Nt,Ke;return o("showFilterInfo")&&((Qe=(Pe=e.preferences)==null?void 0:Pe.displayOptions)==null?void 0:Qe.showFilterInfo)!==!1?c.jsx(NE,{cardId:e.id,cardFilters:(Nt=e.config)==null?void 0:Nt.filters,cardFilterCount:uw(((Ke=e.config)==null?void 0:Ke.filters)||null)}):null},card:be})}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{role:"card-title-container",className:"flex h-7 items-center gap-2",children:[o("showTitle")&&c.jsx(wi,{className:J("text-base",{}),children:c.jsx(qo,{value:e.title,onSave:Pe=>p(u,e.id,Pe),isEditable:d,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),o("showTitle")&&(d||e.info)&&c.jsx(xK,{card:e}),o("showRefreshIndicator")&&e.refreshInterval&&c.jsxs(bn,{children:[c.jsx(xn,{className:"pr-1",children:c.jsx("div",{className:J("h-2 w-2 rounded-full bg-green-500 transition-opacity",{"opacity-10":S||C})})}),c.jsx(Cn,{side:"right",align:"center",children:c.jsx("p",{className:"text-xs",children:`Realtime (${e==null?void 0:e.refreshInterval})`})})]}),o("showFilterInfo")&&((ue=(se=e.preferences)==null?void 0:se.displayOptions)==null?void 0:ue.showFilterInfo)!==!1&&c.jsx(NE,{cardId:e.id,cardFilters:(we=e.config)==null?void 0:we.filters,cardFilterCount:uw(((Se=e.config)==null?void 0:Se.filters)||null)}),R&&c.jsx(vK,{metadata:R,variant:"compact"})]}),c.jsxs("div",{"data-content":"card-description-and-breadcrumb",className:"flex h-6 items-center overflow-y-auto",children:[!a&&o("showDescription")&&c.jsx("div",{className:J("text-sm text-muted-foreground",{}),children:c.jsx(qo,{value:(e==null?void 0:e.description)||"",onSave:Pe=>m(u,e.id,Pe),isEditable:d,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})}),a&&o("showBreadcrumbs")&&c.jsx(E3e,{cardId:e.id})]})]})}if(!e.id)return null;const G=((Ce=(xe=e.preferences)==null?void 0:xe.displayOptions)==null?void 0:Ce.showChrome)??!0,Q=((de=(je=e.preferences)==null?void 0:je.displayOptions)==null?void 0:de.allowScroll)??!0,ne=G?c.jsxs(c.Fragment,{children:[v?c.jsx(vi,{children:c.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 basis-0 scroll-pb-2 overflow-x-auto",role:"header-container",children:Z()}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsx("div",{children:h&&o("showFilters")&&c.jsxs("div",{style:{borderRadius:(Oe=(Re=l==null?void 0:l.chart)==null?void 0:Re.options)==null?void 0:Oe.borderRadius},"data-content":"frame-filter-container",className:"flex shrink-0 items-center",children:[!Lc(h.dataType)&&c.jsx(ce,{className:"my-1 shrink-0 px-3",children:c.jsx(qo,{value:h.title||h.column,onSave:be=>b({...h,title:be}),isEditable:d,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),c.jsx(wS,{filter:h})]})}),t.cards.length>1&&o("showTabs")&&X()]})]})}):c.jsx("div",{className:"h-8"}),c.jsx(Si,{"data-role":"card-content",className:"relative flex min-h-0 grow flex-col",children:H()}),o("showFooter")&&c.jsx(r8,{children:q()})]}):H(),ae=()=>G&&Q?"flex h-full flex-col":G&&!Q?"flex h-full flex-col overflow-hidden":!G&&!Q?"h-full":"h-full overflow-auto";return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"relative h-full",children:[c.jsx("div",{className:J(ae(),{"animate-pulse":S||C}),children:K()}),(S||C)&&(k==null?void 0:k.records)&&k.records.length>0&&c.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-background/50",children:c.jsx(_c,{size:"md",color:"muted","aria-label":"Loading data"})})]}),T.context&&c.jsx(v3e,{open:T.open,onOpenChange:be=>{I(se=>({...se,open:be}))},position:T.position,interactions:T.interactions,selectedConditions:T.context.conditions,drillHierarchies:(mt=e.interactionConfig)==null?void 0:mt.drillHierarchies,cardId:e.id,card:e,onSelectInteraction:be=>{T.context&&P(be,T.context),I({open:!1,position:null,interactions:[],context:null})}})]})}function iZ({card:e,frame:t}){return e.displayPreferences?c.jsx(SR,{displayPreferences:e.displayPreferences,children:c.jsx(c3,{card:e,frame:t})}):c.jsx(c3,{card:e,frame:t})}function D3e({card:e,frame:t,showTitle:n=!0}){const{isError:r,isLoading:s,isFetching:o,cfg:i,data:a,pagination:l}=Kb(e),u=N.useMemo(()=>{var p;return e.type!=="pivotTable"||!((p=a==null?void 0:a.records)!=null&&p.length)?null:{records:a.records,columnSubtotalMeta:a.columnSubtotalMeta,subtotalColumns:a.subtotalColumns||[],pivotSchema:a.pivotSchema||[],groupByColumns:a.groupByColumns}},[e.type,a==null?void 0:a.records,a==null?void 0:a.columnSubtotalMeta,a==null?void 0:a.subtotalColumns,a==null?void 0:a.pivotSchema,a==null?void 0:a.groupByColumns]),d=Pp(e,u),f=N.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]);if(s||o)return c.jsxs("div",{className:"flex h-full grow flex-col items-center justify-center gap-4 p-12",children:[c.jsx(On,{className:"h-8 w-8 animate-spin text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading visual..."})]});if(r)return c.jsx("div",{className:"flex flex-col items-center justify-center gap-2 p-12",children:c.jsx("p",{className:"text-sm font-medium text-destructive",children:"Failed to load visual"})});function h(){return e.type==="kpi"?c.jsx(eb,{card:e,data:(a==null?void 0:a.records)||[],isPending:s||o}):e.type==="table"?c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(rx,{card:e,data:f,isLoading:s||o,paginationMetadata:l})}):e.type==="pivotTable"&&d?c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(ax,{card:e,data:(a==null?void 0:a.records)||[],onAggregationChange:()=>{},onAggregationLabelChange:()=>{}})}):e.type==="aggregateTable"?c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(aS,{card:e,data:(a==null?void 0:a.records)||[],groupByColumns:a==null?void 0:a.groupByColumns,pivotSchema:a==null?void 0:a.pivotSchema,paginationMetadata:l,onAggregationChange:()=>{},isLoading:s||o})}):e.type==="text"?c.jsx(Ds,{className:"overflow-y-auto break-words pr-2",children:c.jsx(Hh,{isLoading:s||o,card:e,data:(a==null?void 0:a.records)||[]})}):e.type==="custom"?c.jsx(wl,{FallbackComponent:uS,children:c.jsx(eR,{frame:t,card:e})}):i?c.jsx(ix,{cfg:i,onChartClick:()=>{},onDatapointClick:()=>{}}):null}return c.jsxs("div",{className:"flex h-full w-full flex-col",children:[n&&e.title&&c.jsxs("div",{className:"border-b px-4 py-2",children:[c.jsx("h3",{className:"text-lg font-medium",children:e.title}),e.description&&c.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:e.description})]}),c.jsx("div",{className:"min-h-0 flex-1 p-4",children:h()})]})}function aZ({insightId:e,filters:t,contextMode:n}){const{data:r,isLoading:s,isError:o,error:i}=ID(e,{enabled:!!e}),a=Lt(f=>f.setInteractionState),l=Lt(f=>f.resetInteractionState),u=N.useMemo(()=>{var h;if(!r)return null;const f=(r==null?void 0:r.frameObject)??((h=r==null?void 0:r.visual)==null?void 0:h.frameObject);if(!f)return null;if(typeof f=="string")try{return JSON.parse(f)}catch{return null}return f},[r]),d=N.useMemo(()=>{var f;return(f=u==null?void 0:u.cards)!=null&&f.length?u.activeCardId&&u.cards.find(h=>h.id===u.activeCardId)||u.cards[0]:null},[u]);return N.useEffect(()=>{if(!d)return;if(n==="none"||!(t!=null&&t.length)){const m={...Ao(),contextMode:n};a(d.id,m);return}const h={sourceCardId:"drill-to-insight",interactionMode:"clickFilter",filterGroups:[{filters:t}],applyToCardIds:[d.id]},p={...Ao(),appliedClickFilters:[h],contextMode:n};return a(d.id,p),()=>{l(d.id)}},[d,t,n,a,l]),s?c.jsxs("div",{className:"flex h-full grow flex-col items-center justify-center gap-4 p-12",children:[c.jsx(On,{className:"h-8 w-8 animate-spin text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading visual..."})]}):o?c.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 p-12",children:[c.jsx("p",{className:"text-sm font-medium text-destructive",children:"Failed to load insight"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:i instanceof Error?i.message:"Unknown error"})]}):!u||!d?c.jsx("div",{className:"flex items-center justify-center p-12",children:c.jsx("p",{className:"text-sm text-muted-foreground",children:"This insight has no visual data to display"})}):c.jsx("div",{className:"h-full w-full",children:c.jsx(D3e,{card:d,frame:u,showTitle:!1})})}function M3e({filters:e,contextMode:t}){if(!e||e.length===0)return t==="none"?c.jsxs(Fe,{variant:"outline",className:"gap-1 whitespace-nowrap",children:[c.jsx(ac,{className:"h-3 w-3"}),"No filters"]}):null;const n=e.reduce((s,o)=>{var a,l;const i=((a=o.field)==null?void 0:a.label)||((l=o.field)==null?void 0:l.name)||"Unknown";return s[i]||(s[i]=[]),s[i].push(o),s},{});e.length;const r=Object.keys(n).length;return c.jsx(Yn,{children:c.jsxs(bn,{delayDuration:200,children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"cursor-help gap-1 whitespace-nowrap border border-blue-500/20 bg-blue-500/10 text-blue-700 dark:text-blue-300",children:[c.jsx(ac,{className:"h-3 w-3"}),r," ",r===1?"filter":"filters"]})}),c.jsx(Cn,{side:"bottom",align:"start",className:"max-w-md",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Applied Filters"}),c.jsx("div",{className:"space-y-1.5",children:Object.entries(n).map(([s,o])=>c.jsxs("div",{className:"text-xs",children:[c.jsxs("span",{className:"font-medium",children:[s,":"]})," ",o.map((i,a)=>c.jsxs("span",{children:[T3e(i),a<o.length-1?", ":""]},a))]},s))}),t&&c.jsx("div",{className:"border-t pt-2 text-xs text-muted-foreground",children:R3e(t)})]})})]})})}function T3e(e){const{operator:t,value:n}=e;if(e.label){const r=e.label.split(/[=><]/);if(r.length>1)return r[1].trim()}switch(t){case"=":return String(n);case"!=":return`≠ ${n}`;case">":return`> ${n}`;case"<":return`< ${n}`;case">=":return`≥ ${n}`;case"<=":return`≤ ${n}`;case"in":return Array.isArray(n)?n.join(", "):String(n);case"not in":return`not ${Array.isArray(n)?n.join(", "):n}`;case"contains":return`contains ${n}`;case"startsWith":return`starts with ${n}`;case"endsWith":return`ends with ${n}`;case"between":return Array.isArray(n)?`${n[0]}-${n[1]}`:String(n);case"not between":return Array.isArray(n)?`not ${n[0]}-${n[1]}`:String(n);case"isNull":return"is null";case"isNotNull":return"is not null";default:return String(n)}}function R3e(e){switch(e){case"filters":case"interactionFilters":return"Showing data filtered by interaction only";case"full":return"Showing data with all dashboard filters + interaction filters";case"none":return"Showing all data (no filters applied)"}}function lZ(e,t={}){const{enabled:n=!0}=t,{data:r}=ID(e,{enabled:n&&!!e});return N.useMemo(()=>{var l,u;if(!r)return{title:"",description:void 0};const o=(r==null?void 0:r.frameObject)??((l=r==null?void 0:r.visual)==null?void 0:l.frameObject);if(!o)return{title:"",description:void 0};let i=null;if(typeof o=="string")try{i=JSON.parse(o)}catch{return{title:"",description:void 0}}else i=o;if(!((u=i==null?void 0:i.cards)!=null&&u.length))return{title:"",description:void 0};const a=i.activeCardId&&i.cards.find(d=>d.id===i.activeCardId)||i.cards[0];return{title:a.title,description:a.description}},[r])}function I3e({cardId:e,children:t}){const n=Lt(o=>o.replacedCards[e]),r=Lt(o=>o.restoreCard),s=lZ((n==null?void 0:n.insightId)||"",{enabled:!!(n!=null&&n.insightId)});return n?c.jsxs("div",{className:"flex h-full w-full flex-col",children:[c.jsxs("div",{className:"border-b bg-muted/30",children:[c.jsx("div",{className:"flex items-baseline gap-2 px-5 pb-2 pt-4",children:s.title&&c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"truncate text-sm font-semibold",children:s.title}),s.description&&c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-muted-foreground",children:"-"}),c.jsx("span",{className:"truncate text-xs text-muted-foreground",children:s.description})]})]})}),c.jsxs("div",{className:"flex items-center gap-3 px-4 pb-2",children:[c.jsxs(oe,{variant:"ghost",size:"sm",onClick:()=>r(e),className:"flex-shrink-0 gap-1",children:[c.jsx(o8,{className:"h-4 w-4"}),"Back"]}),c.jsx(M3e,{filters:n.filters,contextMode:n.contextMode})]})]}),c.jsx("div",{className:"min-h-0 flex-1",children:c.jsx(aZ,{insightId:n.insightId,filters:n.filters,contextMode:n.contextMode})})]}):c.jsx(c.Fragment,{children:t})}function A3e({frame:e,footer:t,className:n,...r}){var w,S;const s=N.useRef(null),[o,i]=N.useState(!1),a=ee(C=>C.themeStyle),l=ee(C=>C.isVisualEditing),u=ee(C=>C.selectedFrameId),d=ee(C=>C.isDashboardEditing),{setSelectedFrameId:f}=Yt(),{clearSelectedVisual:h}=Rb(),{setSelectedConnectionId:p,setSelectedDatabaseName:m,setSelectedSchemaName:g,setSelectedTableName:b,setCard:x}=ur();N.useEffect(()=>{if(u===e.id&&d&&!l){const C=s==null?void 0:s.current;C==null||C.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})}},[u,e.id,d,l,s]);const y=e.cards.find(C=>C.id===e.activeCardId);function v(C){C.stopPropagation(),f(e.id),h(),y&&x(y),y!=null&&y.connectionId&&p(y==null?void 0:y.connectionId),y!=null&&y.lastSelectedDatabase&&m(y==null?void 0:y.lastSelectedDatabase),y!=null&&y.lastSelectedSchema&&g(y==null?void 0:y.lastSelectedSchema),y!=null&&y.lastSelectedTable&&b(y==null?void 0:y.lastSelectedTable)}return c.jsx(wl,{FallbackComponent:dS,children:c.jsxs("div",{tabIndex:-1,ref:s,role:"card-frame","data-frame-id":e.id,"data-active-card-id":y==null?void 0:y.id,onClick:v,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{borderRadius:a==null?void 0:a.cardBorderRadius},className:J("relative flex h-full flex-col rounded-sm border bg-background shadow-sm",{"border-dashed border-foreground/50":u===e.id&&d},a==null?void 0:a.dashboardCard,n,"semaphor-card-frame"),...r,children:[(d||((S=(w=y==null?void 0:y.preferences)==null?void 0:w.displayOptions)==null?void 0:S.showCardToolbar)!==!1)&&c.jsx(iK,{frame:e,isHovered:o}),y&&c.jsx(I3e,{cardId:y.id,children:c.jsx(iZ,{card:y,frame:e},y.id)})]})})}function CR(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}var P3e=["color"],O3e=N.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=CR(e,P3e);return N.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),N.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),F3e=["color"],cZ=N.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=CR(e,F3e);return N.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),N.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),$3e=["color"],uZ=N.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=CR(e,$3e);return N.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),N.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Gh({text:e,className:t}){const[n,r]=N.useState(!1);return c.jsx(oe,{className:J("h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",t),variant:"ghost",size:"icon",onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>{r(!1)},1e3)},children:n?c.jsx(cZ,{className:"size-3.5"}):c.jsx(_g,{className:"size-3.5"})})}function L3e({filter:e,onUpdate:t}){const[n,r]=N.useState(""),s=ee(y=>y.dashboard.sheets)||[],o=ee(y=>y.selectedSheetId),i=N.useMemo(()=>{const y=[];return s==null||s.forEach(v=>{var w;(w=v.frames)==null||w.forEach(S=>{var C;(C=S.cards)==null||C.forEach(j=>{y.push({...j,sheetId:v.id,sheetTitle:v.title||v.id})})})}),y},[s]),a=()=>e.applyToSheetIds!==void 0?"specific-sheets":e.excludeSheetIds!==void 0?"all-except-specific":"all-sheets",l=()=>e.applyToCardIds!==void 0?"specific-cards":e.excludeCardIds!==void 0?"all-except-specific":"all-cards",u=y=>{const v={};switch(y){case"all-sheets":v.applyToSheetIds=void 0,v.excludeSheetIds=void 0;break;case"specific-sheets":v.applyToSheetIds=[],v.excludeSheetIds=void 0;break;case"all-except-specific":v.applyToSheetIds=void 0,v.excludeSheetIds=[];break}t(v)},d=y=>{const v={};switch(y){case"all-cards":v.applyToCardIds=void 0,v.excludeCardIds=void 0;break;case"specific-cards":v.applyToCardIds=[],v.excludeCardIds=void 0;break;case"all-except-specific":v.applyToCardIds=void 0,v.excludeCardIds=[];break}t(v)},f=(y,v)=>{if(v==="specific-sheets"){const w=e.applyToSheetIds||[],S=w.includes(y)?w.filter(C=>C!==y):[...w,y];t({applyToSheetIds:S})}else if(v==="all-except-specific"){const w=e.excludeSheetIds||[],S=w.includes(y)?w.filter(C=>C!==y):[...w,y];t({excludeSheetIds:S})}},h=(y,v)=>{if(v==="specific-cards"){const w=e.applyToCardIds||[],S=w.includes(y)?w.filter(C=>C!==y):[...w,y];t({applyToCardIds:S})}else if(v==="all-except-specific"){const w=e.excludeCardIds||[],S=w.includes(y)?w.filter(C=>C!==y):[...w,y];t({excludeCardIds:S})}},p=()=>{const y=a();return y==="specific-sheets"?e.applyToSheetIds||[]:y==="all-except-specific"?(s==null?void 0:s.filter(v=>{var w;return!((w=e.excludeSheetIds)!=null&&w.includes(v.id))}).map(v=>v.id))||[]:(s==null?void 0:s.map(v=>v.id))||[]},m=N.useMemo(()=>{const y=p();return i.filter(v=>y.includes(v.sheetId))},[i,e.applyToSheetIds,e.excludeSheetIds]),g=N.useMemo(()=>{if(!n.trim())return m;const y=n.toLowerCase();return m.filter(v=>{var w;return(w=v==null?void 0:v.title)==null?void 0:w.toLowerCase().includes(y)})},[n,m]),b=a(),x=l();return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Sheet Scope"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Which sheets should display this filter?"})]}),c.jsxs(ga,{value:b,onValueChange:y=>u(y),className:"space-y-3",children:[c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"all-sheets",id:"all-sheets",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"all-sheets",className:"cursor-pointer text-sm font-medium",children:"All sheets"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:["Display filter on all sheets (",(s==null?void 0:s.length)||0," sheets)"]})]})]}),c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"specific-sheets",id:"specific-sheets",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"specific-sheets",className:"cursor-pointer text-sm font-medium",children:"Only specific sheets"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Display filter on selected sheets only"})]})]}),b==="specific-sheets"&&c.jsx("div",{className:"ml-7 space-y-2",children:c.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:s==null?void 0:s.map(y=>{const v=(e.applyToSheetIds||[]).includes(y.id);return c.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[c.jsx(dn,{id:`sheet-${y.id}`,checked:v,onCheckedChange:()=>f(y.id,"specific-sheets")}),c.jsxs(ce,{htmlFor:`sheet-${y.id}`,className:"cursor-pointer text-sm font-medium",children:[y.title||y.id,y.id===o&&c.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:"(this sheet)"})]})]},y.id)})})}),c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"all-except-specific",id:"all-sheets-except",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"all-sheets-except",className:"cursor-pointer text-sm font-medium",children:"All sheets except specific ones"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Display filter on all sheets except selected ones"})]})]}),b==="all-except-specific"&&c.jsx("div",{className:"ml-7 space-y-2",children:c.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:s==null?void 0:s.map(y=>{const v=(e.excludeSheetIds||[]).includes(y.id);return c.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[c.jsx(dn,{id:`sheet-exclude-${y.id}`,checked:v,onCheckedChange:()=>f(y.id,"all-except-specific")}),c.jsxs(ce,{htmlFor:`sheet-exclude-${y.id}`,className:"cursor-pointer text-sm font-medium",children:[y.title||y.id,y.id===o&&c.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:"(this sheet)"})]})]},y.id)})})})]})]}),c.jsxs("div",{className:"space-y-3 border-t pt-4",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Card Scope"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Which cards should receive this filter?"})]}),c.jsxs(ga,{value:x,onValueChange:y=>d(y),className:"space-y-3",children:[c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"all-cards",id:"all-cards",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"all-cards",className:"cursor-pointer text-sm font-medium",children:"All cards"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:["Apply filter to all cards in applicable sheets (",m.length," cards)"]})]})]}),c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"specific-cards",id:"specific-cards",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"specific-cards",className:"cursor-pointer text-sm font-medium",children:"Only specific cards"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to selected cards only"})]})]}),x==="specific-cards"&&c.jsxs("div",{className:"ml-7 space-y-2",children:[c.jsx(Nn,{placeholder:"Search cards...",value:n,onChange:y=>r(y.target.value),className:"mb-2"}),c.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:g.length>0?g.map(y=>{const v=(e.applyToCardIds||[]).includes(y.id);return c.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[c.jsx(dn,{id:`card-${y.id}`,checked:v,onCheckedChange:()=>h(y.id,"specific-cards")}),c.jsxs("div",{className:"flex-1",children:[c.jsx(ce,{htmlFor:`card-${y.id}`,className:"cursor-pointer text-sm font-medium",children:y.title}),c.jsx("p",{className:"text-xs text-muted-foreground",children:y.sheetTitle})]})]},y.id)}):c.jsxs("p",{className:"py-4 text-center text-sm text-muted-foreground",children:['No cards found matching "',n,'"']})})]}),c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"all-except-specific",id:"all-cards-except",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"all-cards-except",className:"cursor-pointer text-sm font-medium",children:"All cards except specific ones"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to all cards except selected ones"})]})]}),x==="all-except-specific"&&c.jsxs("div",{className:"ml-7 space-y-2",children:[c.jsx(Nn,{placeholder:"Search cards...",value:n,onChange:y=>r(y.target.value),className:"mb-2"}),c.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:g.length>0?g.map(y=>{const v=(e.excludeCardIds||[]).includes(y.id);return c.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[c.jsx(dn,{id:`card-exclude-${y.id}`,checked:v,onCheckedChange:()=>h(y.id,"all-except-specific")}),c.jsxs("div",{className:"flex-1",children:[c.jsx(ce,{htmlFor:`card-exclude-${y.id}`,className:"cursor-pointer text-sm font-medium",children:y.title}),c.jsx("p",{className:"text-xs text-muted-foreground",children:y.sheetTitle})]})]},y.id)}):c.jsxs("p",{className:"py-4 text-center text-sm text-muted-foreground",children:['No cards found matching "',n,'"']})})]})]})]}),c.jsx("div",{className:"rounded-md bg-blue-50 p-3 text-xs text-blue-900 dark:bg-blue-950 dark:text-blue-100",children:"ℹ️ Cards are filtered based on sheet scope selection. Only cards from applicable sheets are shown in card scope."})]})}function z3e(e){for(const[n,r]of Object.entries(e8))if(JSON.stringify(r)===JSON.stringify(e))return n;const t={day:"day",week:"week",month:"month",quarter:"quarter",year:"year"};switch(e.mode){case"last":{const n=e.complete?" (complete)":"",r=e.n>1?"s":"";return`Last ${e.n} ${t[e.unit]}${r}${n}`}case"this":{const n=e.toDate?" to date":"";return`This ${t[e.unit]}${n}`}case"previous":return`Previous ${t[e.unit]}`;case"between":return`Between ${e.from} and ${e.to} ${t[e.unit]}s`}}function B3e({filter:e}){var M,R;const[t,n]=N.useState(e.sql),[r,s]=N.useState(!1),[o,i]=N.useState({}),[a,l]=N.useState(e.title||""),[u,d]=N.useState(e.column),[f,h]=N.useState(e.searchMode||"auto"),[p,m]=N.useState(((M=e.defaultValues)==null?void 0:M.map(O=>String(O)))||[]),[g,b]=N.useState(e.defaultDateFilter);ee(O=>O.selectedSheetId);const{updateFilter:x}=Yt(),{tokenProps:y}=qe(),v=N.useMemo(()=>Ks(e.dataType)==="date",[e.dataType]),w=((R=y==null?void 0:y.params)==null?void 0:R.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone,S=N.useMemo(()=>{if(!g)return;const[O,T]=J6(g,w);return{from:O,to:T}},[g,w]),{data:C}=dR(e);function j(){const O=a.trim(),T=u.trim(),I={sql:t,...o},F=T||e.column;T&&T!==e.column&&(I.column=F),I.title=O||F,Vo(e.dataType)&&(I.searchMode=f),I.defaultValues=p.length>0?p.map(B=>{const $=Number(B);return!isNaN($)&&Vo(e.dataType)?$:B}):void 0,v&&(I.defaultDateFilter=g);const z={...e,...I};x(z),i({}),s(!1)}N.useEffect(()=>{var O;r&&(i({}),n(e.sql),l(e.title===e.column?"":e.title||""),d(e.column),h(e.searchMode||"auto"),m(((O=e.defaultValues)==null?void 0:O.map(T=>String(T)))||[]),b(e.defaultDateFilter))},[r,e.sql,e.title,e.column,e.searchMode,e.defaultValues,e.defaultDateFilter]);function D(O){const T={...e,type:O};x(T)}function k(O){const T={...e,uiType:O};x(T)}function _(O){const T={...e,dateSelectionMode:O};x(T)}return c.jsxs(Ns,{open:r,onOpenChange:s,children:[c.jsx(js,{children:c.jsx(Ku,{className:"invisible h-3 w-3 cursor-pointer text-muted-foreground hover:text-foreground group-hover:visible"})}),c.jsx(ks,{onMouseDown:O=>O.stopPropagation(),onDoubleClick:O=>O.stopPropagation(),className:"z-50 m-2 h-[600px] w-[500px]",children:c.jsxs("div",{className:"flex h-full flex-col",children:[c.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[c.jsx("h4",{className:"font-medium leading-none",title:e.column,children:e.column.split(".").pop()}),c.jsx(Fe,{variant:"secondary",className:"flex-shrink-0 text-xs font-normal",children:e.dataType})]}),c.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:"Customize filter settings and scope"}),c.jsxs(cs,{defaultValue:"scope",className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:[c.jsxs(Wr,{className:"grid w-full flex-shrink-0 grid-cols-2",children:[c.jsx(Ht,{value:"scope",children:"Scope"}),c.jsx(Ht,{value:"advanced",children:"Configuration"})]}),c.jsx(Gn,{value:"scope",className:"mt-4 flex-1 overflow-y-auto",children:c.jsx(L3e,{filter:{...e,...o},onUpdate:O=>{i(T=>({...T,...O}))}})}),c.jsxs(Gn,{value:"advanced",className:"mt-4 flex-1 space-y-5 overflow-y-auto",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Custom Title (optional)"}),c.jsx(Yn,{children:c.jsxs(bn,{delayDuration:0,children:[c.jsx(xn,{asChild:!0,children:c.jsx(xr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),c.jsx(Cn,{side:"right",className:"max-w-xs",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("p",{className:"text-xs",children:"Leave empty to use the column name. Provide a custom title to override it."}),c.jsxs("div",{className:"space-y-1 border-t pt-2",children:[c.jsx("p",{className:"text-xs font-medium",children:"Filter ID"}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("p",{className:"break-all font-mono text-xs text-muted-foreground",children:e.id}),c.jsx(Gh,{text:e.id})]})]})]})})]})})]}),c.jsx(Bn,{value:a,onChange:O=>l(O.target.value),placeholder:e.column,className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-1",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Column Name"}),c.jsx(Bn,{value:u,onChange:O=>d(O.target.value),placeholder:"Enter column name",className:"h-8 font-mono text-xs"})]}),v?c.jsxs("div",{className:"space-y-1",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Date Picker Type"}),c.jsxs(rt,{value:e.dateSelectionMode||"range",onValueChange:O=>_(O),children:[c.jsx(Je,{className:"h-8",children:c.jsx(lt,{})}),c.jsxs(et,{children:[c.jsx(pe,{value:"range",children:"Date Range Picker"}),c.jsx(pe,{value:"months",children:"Month Picker"})]})]})]}):c.jsxs("div",{className:"space-y-1",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Selection Type"}),c.jsxs(rt,{value:e.type||"multiple",onValueChange:D,children:[c.jsx(Je,{className:"h-8",children:c.jsx(lt,{})}),c.jsxs(et,{children:[c.jsx(pe,{value:"multiple",children:"Multiple"}),c.jsx(pe,{value:"single",children:"Single"})]})]})]}),!v&&e.type==="single"&&c.jsxs("div",{className:"space-y-1",children:[c.jsx(ce,{className:"text-sm font-medium",children:"UI Component"}),c.jsxs(rt,{value:e.uiType||"dropdown",onValueChange:k,children:[c.jsx(Je,{className:"h-8",children:c.jsx(lt,{})}),c.jsxs(et,{children:[c.jsx(pe,{value:"dropdown",children:"Dropdown"}),c.jsx(pe,{value:"radio",children:"Radio"}),c.jsx(pe,{value:"tabs",children:"Tabs"})]})]})]}),Vo(e.dataType)&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Search Mode"}),c.jsx(Yn,{children:c.jsxs(bn,{delayDuration:0,children:[c.jsx(xn,{asChild:!0,children:c.jsx(xr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),c.jsx(Cn,{side:"right",className:"max-w-xs",children:c.jsxs("div",{className:"space-y-2 text-xs",children:[c.jsxs("p",{children:[c.jsx("strong",{children:"Text Search:"}),' Treats numbers as text (e.g., ZIP codes, IDs). Search for "90210".']}),c.jsxs("p",{children:[c.jsx("strong",{children:"Numeric Operators:"})," Supports comparison operators (e.g., >100, <=50, =100) for quantities, prices."]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Auto-detect:"})," Tries numeric first, falls back to text search."]})]})})]})})]}),c.jsxs(rt,{value:f,onValueChange:O=>h(O),children:[c.jsx(Je,{className:"h-8",children:c.jsx(lt,{})}),c.jsxs(et,{children:[c.jsx(pe,{value:"text",children:"Text Search"}),c.jsx(pe,{value:"numeric",children:"Numeric Operators"}),c.jsx(pe,{value:"auto",children:"Auto-detect"})]})]})]}),v?c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Default Date Filter (optional)"}),c.jsx(Yn,{children:c.jsxs(bn,{delayDuration:0,children:[c.jsx(xn,{asChild:!0,children:c.jsx(xr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),c.jsx(Cn,{side:"right",className:"max-w-xs",children:c.jsx("p",{className:"text-xs",children:"Set a relative date filter that will be automatically applied when the dashboard first loads. The dates will recalculate on each dashboard load and scheduled report execution."})})]})})]}),e.dateSelectionMode==="months"?c.jsxs(rt,{value:g?JSON.stringify(g):"__none__",onValueChange:O=>{if(O==="__none__"){b(void 0);return}try{const T=JSON.parse(O);b(T)}catch(T){console.error("Failed to parse relative date filter",T)}},children:[c.jsx(Je,{className:"h-8",children:c.jsx(lt,{placeholder:"Select default month range..."})}),c.jsxs(et,{children:[c.jsx(pe,{value:"__none__",children:"None"}),c.jsx(pe,{value:JSON.stringify({mode:"this",unit:"month"}),children:"This month"}),c.jsx(pe,{value:JSON.stringify({mode:"previous",unit:"month"}),children:"Last month"})]})]}):c.jsx(uR,{value:S,onRelativeSelect:(O,T)=>{b(T)},showRelativeTab:!0,hideCalendar:!0,timezone:w,placeholder:"Select default date range...",buttonClassName:"h-8"}),g&&c.jsx("div",{className:"flex items-center gap-2",children:c.jsxs(Fe,{variant:"secondary",className:"gap-1.5 text-xs",children:[z3e(g),c.jsx(vt,{className:"h-3 w-3 cursor-pointer hover:text-destructive",onClick:()=>b(void 0)})]})})]}):c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Default Values (optional)"}),c.jsx(Yn,{children:c.jsxs(bn,{delayDuration:0,children:[c.jsx(xn,{asChild:!0,children:c.jsx(xr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),c.jsx(Cn,{side:"right",className:"max-w-xs",children:c.jsx("p",{className:"text-xs",children:"Select values that will be automatically applied when the dashboard first loads. Works like a filter selection."})})]})})]}),C!=null&&C.records&&C.records.length>0?c.jsxs(rt,{value:"",onValueChange:O=>{O&&!p.includes(O)&&m([...p,O])},children:[c.jsx(Je,{className:"h-8",children:c.jsx(lt,{placeholder:"Select values to add..."})}),c.jsxs(et,{children:[C.records.filter(O=>{var F;const T=(F=e.column.split(".").pop())==null?void 0:F.replace(/"/g,""),I=T?O[T]:O.value;return I!=null&&!p.includes(String(I))}).map(O=>{var F;const T=(F=e.column.split(".").pop())==null?void 0:F.replace(/"/g,""),I=T?O[T]:O.value;return c.jsx(pe,{value:String(I),children:String(I)},String(I))}),C.records.every(O=>{var F;const T=(F=e.column.split(".").pop())==null?void 0:F.replace(/"/g,""),I=T?O[T]:O.value;return I==null||p.includes(String(I))})&&c.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"All values selected"})]})]}):c.jsx("div",{className:"flex h-8 items-center rounded-md border bg-muted px-2 text-xs text-muted-foreground",children:"Loading filter options..."}),p.length>0&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsxs("div",{className:"text-xs font-medium text-muted-foreground",children:["Selected (",p.length,"):"]}),c.jsx("div",{className:"flex flex-wrap gap-1.5",children:p.map(O=>c.jsxs(Fe,{variant:"secondary",className:"gap-1.5 text-xs",children:[String(O),c.jsx(vt,{className:"h-3 w-3 cursor-pointer hover:text-destructive",onClick:()=>{m(T=>T.filter(I=>I!==O))}})]},O))})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"SQL"}),c.jsx(Yn,{children:c.jsxs(bn,{delayDuration:0,children:[c.jsx(xn,{asChild:!0,children:c.jsx(xr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),c.jsx(Cn,{side:"right",className:"max-w-xs",children:c.jsx("p",{className:"text-xs",children:"This SQL will be used to fetch the filter values"})})]})})]}),c.jsx(qd,{onKeyDown:O=>{O.stopPropagation()},value:t,onChange:O=>n(O.target.value),className:`h-32 w-full resize-none break-all font-mono text-xs ${Wf}`,placeholder:"SELECT column FROM table..."})]}),c.jsx("div",{className:"border-t pt-2"})]})]}),c.jsx("div",{className:"mt-3 flex justify-end gap-2 border-t pt-3",children:c.jsxs(oe,{onClick:j,size:"sm",variant:"outline",children:[c.jsx(Rr,{className:"mr-2 size-4"}),"Accept"]})})]})})]})}function NR({filter:e}){var u;const t=ee(d=>d.isDashboardEditing),{preferences:n}=dp(),r=((u=n==null?void 0:n.cardDisplay)==null?void 0:u.mode)==="print",s=ee(d=>d.filterValues),o=s==null?void 0:s.some(d=>d.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:l}=Yt();return c.jsxs("div",{className:"group mb-1 flex h-5 items-center justify-between",children:[c.jsxs("div",{className:"flex grow items-center gap-2",children:[c.jsx(ce,{className:"my-1 inline-block text-sm",children:c.jsx(qo,{value:e.title||e.column,onSave:d=>l({...e,title:d}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),o&&!r&&c.jsx("button",{onClick:()=>i(e.id),className:"text-muted-foreground",children:c.jsx(pae,{className:"size-3.5"})}),t&&c.jsx("button",{className:"invisible group-hover:visible",onClick:()=>{l({...e,hide:!e.hide})},children:e.hide?c.jsx(bc,{className:"size-3.5 text-muted-foreground hover:text-foreground"}):c.jsx(t1,{className:"size-3.5 text-muted-foreground hover:text-foreground"})}),t&&c.jsx(B3e,{filter:e})]}),c.jsx("div",{className:"flex items-center gap-2",children:t&&c.jsx(vt,{onClick:()=>{i(e.id),a(e.id)},className:"size-3 cursor-pointer text-muted-foreground hover:cursor-pointer hover:text-foreground"})})]})}function dZ(){var g;const e=ee(b=>b.isDashboardEditing),t=ee(b=>b.selectedSheetId),n=ee(b=>b.dashboard),r=n==null?void 0:n.sheets,s=r==null?void 0:r.find(b=>b.id===t),o=_e(b=>b.card),i=_e(b=>b.selectedConnectionId),{addFrame:a,setSelectedFrameId:l,setIsVisualEditing:u}=Yt(),{setFrame:d,setCard:f,setActiveTabCardId:h}=ur();function p(){var v,w;const b=o==null?void 0:o.dataSource;if(b)return b;const x=(w=(v=n==null?void 0:n.aiContext)==null?void 0:v.selectedEntities)==null?void 0:w[0],y=x==null?void 0:x.type;if(x)return{connectionId:x.connectionId,connectionType:x.connectionType,type:y,selectedEntities:[x]}}function m(b){const x=(b==null?void 0:b.sheetId)||t,y=r==null?void 0:r.find(j=>j.id===x);if(!y){console.warn("Cannot add frame: No sheet found");return}if(!(!y.frames||y.frames.length===0)&&!e){console.warn("Cannot add frame: Dashboard not in editing mode");return}const w=p(),S={id:Mr(),title:"Title",type:"bar",connectionId:i||"",dataSource:w,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},sql:"",data:[]},C={id:Mr(),cards:[S],activeCardId:S.id};return x&&(a(x,C),l(C.id)),b!=null&&b.openVisualEditor&&(d(C),f(S),h(S.id),u(!0)),C}return{handleAddNewFrame:m,canAddFrame:e||!((g=s==null?void 0:s.frames)!=null&&g.length)}}function V3e({sheetId:e}){const{handleAddNewFrame:t}=dZ(),n=ee(s=>s.themeStyle),r=()=>{t({openVisualEditor:!0,sheetId:e})};return c.jsx("div",{className:"flex h-full min-h-[400px] items-start justify-start p-4",children:c.jsxs("button",{onClick:r,style:{borderRadius:n==null?void 0:n.cardBorderRadius},className:"group flex h-96 w-[600px] flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed border-muted-foreground/25 bg-background transition-all hover:border-muted-foreground/50 hover:bg-muted/50",children:[c.jsx("div",{className:"rounded-full bg-primary/10 p-3 transition-colors group-hover:bg-primary/20",children:c.jsx(jr,{className:"h-6 w-6 text-primary"})}),c.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Add new Visual"})]})})}function sb(e){const t=(e||"").toLowerCase(),n=Ks(t);return n==="string"?c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-blue-200/70 bg-gradient-to-r from-blue-100/60 to-blue-200/40 text-blue-900 shadow-sm dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100",children:c.jsx(Vj,{className:"h-3 w-3"})}):n==="number"?c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-green-200/70 bg-gradient-to-r from-green-100/60 to-green-200/40 text-green-900 shadow-sm dark:border-green-800/50 dark:from-green-950/40 dark:to-green-900/30 dark:text-green-100",children:c.jsx(E8,{className:"h-3 w-3"})}):n==="date"?c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-purple-200/70 bg-gradient-to-r from-purple-100/60 to-purple-200/40 text-purple-900 shadow-sm dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100",children:c.jsx(os,{className:"h-3 w-3"})}):n==="boolean"?c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-orange-200/70 bg-gradient-to-r from-orange-100/60 to-orange-200/40 text-orange-900 shadow-sm dark:border-orange-800/50 dark:from-orange-950/40 dark:to-orange-900/30 dark:text-orange-100",children:c.jsx(_ae,{className:"h-3 w-3"})}):n==="json"?c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-gray-200/70 bg-gradient-to-r from-gray-100/60 to-gray-200/40 text-gray-900 shadow-sm dark:border-gray-800/50 dark:from-gray-950/40 dark:to-gray-900/30 dark:text-gray-100",children:c.jsx(v8,{className:"h-3 w-3"})}):n==="geo"?c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-amber-200/70 bg-gradient-to-r from-amber-100/60 to-amber-200/40 text-amber-900 shadow-sm dark:border-amber-800/50 dark:from-amber-950/40 dark:to-amber-900/30 dark:text-amber-100",children:c.jsx(bae,{className:"h-3 w-3"})}):n==="calculated"?c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-indigo-200/70 bg-gradient-to-r from-indigo-100/60 to-indigo-200/40 text-indigo-900 shadow-sm dark:border-indigo-800/50 dark:from-indigo-950/40 dark:to-indigo-900/30 dark:text-indigo-100",children:c.jsx(q_,{className:"h-3 w-3"})}):c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-gray-200/70 bg-gradient-to-r from-gray-100/60 to-gray-200/40 text-gray-900 shadow-sm dark:border-gray-800/50 dark:from-gray-950/40 dark:to-gray-900/30 dark:text-gray-100",children:c.jsx(Vj,{className:"h-3 w-3"})})}function H3e({value:e,onChange:t,metrics:n,attributes:r}){const s=(o,i)=>(e==null?void 0:e.field.id)===o.id&&(e==null?void 0:e.type)===i;return c.jsx(Yn,{children:c.jsxs("div",{className:"space-y-4",children:[n.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Value of Metric"}),c.jsxs(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsx(xr,{className:"h-3.5 w-3.5 text-muted-foreground"})}),c.jsxs(Cn,{className:"max-w-xs",children:[c.jsx("p",{className:"text-xs font-medium mb-1",children:"Captures intersection of all dimensions"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:`Example: Clicking a bar segment in "Sales by Country, stacked by State" captures both Country='USA' AND State='California'`})]})]})]}),c.jsx("div",{className:"space-y-1",children:n.map(o=>{const i=s(o,"metric");return c.jsxs(oe,{variant:i?"default":"outline",size:"sm",className:J("w-full justify-start font-normal",i&&"bg-primary text-primary-foreground"),onClick:()=>t({type:"metric",field:o}),children:[i&&c.jsx(Rr,{className:"mr-2 h-4 w-4"}),sb(o.dataType),c.jsx("span",{className:"ml-2",children:o.label})]},o.id)})})]}),r.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Value of Attribute"}),c.jsxs(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsx(xr,{className:"h-3.5 w-3.5 text-muted-foreground"})}),c.jsxs(Cn,{className:"max-w-xs",children:[c.jsx("p",{className:"text-xs font-medium mb-1",children:"Captures only this dimension"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:`Example: If configured on "State", clicking a bar in "Sales by Country, stacked by State" captures only State='California' (Country is not included)`})]})]})]}),c.jsx("div",{className:"space-y-1",children:r.map(o=>{const i=s(o,"attribute");return c.jsxs(oe,{variant:i?"default":"outline",size:"sm",className:J("w-full justify-start font-normal",i&&"bg-primary text-primary-foreground"),onClick:()=>t({type:"attribute",field:o}),children:[i&&c.jsx(Rr,{className:"mr-2 h-4 w-4"}),sb(o.dataType),c.jsx("span",{className:"ml-2",children:o.label})]},o.id)})})]}),n.length===0&&r.length===0&&c.jsx("div",{className:"text-sm text-muted-foreground text-center py-8",children:"No metrics or attributes available in this chart"})]})})}const u3=[{value:"clickFilter",label:"Cross filter",description:"Filter other cards on the dashboard"},{value:"drillDown",label:"Drill down",description:"Navigate through a hierarchy of dimensions"},{value:"dynamicDrill",label:"Explore dimensions",description:"Let users explore any dimension dynamically"},{value:"drillThrough",label:"Drill into dashboard",description:"Navigate to another dashboard"},{value:"drillToDetail",label:"Drill into insight",description:"Navigate to a saved insight"},{value:"drillToURL",label:"Drill into URL",description:"Navigate to a custom URL"}];function U3e({value:e,onChange:t}){const n=u3.find(r=>r.value===e);return c.jsx("div",{className:"space-y-2",children:c.jsxs(rt,{value:e,onValueChange:t,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:"Choose action...",children:n&&c.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const r=hw(n.value);return c.jsx(r,{className:"h-4 w-4"})})(),c.jsx("span",{children:n.label})]})})}),c.jsx(et,{children:u3.map(r=>{const s=hw(r.value);return c.jsx(pe,{value:r.value,children:c.jsxs("div",{className:"flex items-start gap-2 py-1",children:[c.jsx(s,{className:"mt-0.5 h-4 w-4 shrink-0"}),c.jsxs("div",{className:"flex flex-col",children:[c.jsx("span",{className:"font-medium",children:r.label}),c.jsx("span",{className:"text-xs text-muted-foreground",children:r.description})]})]})},r.value)})})]})})}function W3e({interaction:e,onUpdate:t}){const[n,r]=N.useState(""),s=h6(),o=()=>e.applyToCardIds!==void 0?"specific-cards":e.excludeCardIds!==void 0?"all-except-specific":"all-cards",i=d=>{const f={};switch(d){case"all-cards":f.applyToCardIds=void 0,f.excludeCardIds=void 0;break;case"specific-cards":f.applyToCardIds=[],f.excludeCardIds=void 0;break;case"all-except-specific":f.applyToCardIds=void 0,f.excludeCardIds=[];break}t({...e,...f})},a=(d,f)=>{if(f==="specific-cards"){const h=e.applyToCardIds||[],p=h.includes(d)?h.filter(m=>m!==d):[...h,d];t({...e,applyToCardIds:p})}else if(f==="all-except-specific"){const h=e.excludeCardIds||[],p=h.includes(d)?h.filter(m=>m!==d):[...h,d];t({...e,excludeCardIds:p})}},l=N.useMemo(()=>{if(!n.trim())return s;const d=n.toLowerCase();return s==null?void 0:s.filter(f=>{var h;return(h=f==null?void 0:f.title)==null?void 0:h.toLowerCase().includes(d)})},[n,s]),u=o();return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Filter scope"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose which cards should receive the filter"})]}),c.jsxs(ga,{value:u,onValueChange:d=>i(d),className:"space-y-2",children:[c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"all-cards",id:"all-cards",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"all-cards",className:"cursor-pointer text-sm font-medium",children:"All cards"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to all cards in the dashboard"})]})]}),c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"specific-cards",id:"specific-cards",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"specific-cards",className:"cursor-pointer text-sm font-medium",children:"Only specific cards"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to selected cards only"})]})]}),u==="specific-cards"&&c.jsxs("div",{className:"ml-7 space-y-2",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Cards to filter"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Select which cards should receive the filter"})]}),c.jsx(Nn,{placeholder:"Search cards...",value:n,onChange:d=>r(d.target.value),className:"mb-2"}),c.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:l&&l.length>0?l.map(d=>{const f=(e.applyToCardIds||[]).includes(d.id);return c.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[c.jsx(dn,{id:`card-${d.id}`,checked:f,onCheckedChange:()=>a(d.id,"specific-cards")}),c.jsxs("div",{className:"flex-1",children:[c.jsx(ce,{htmlFor:`card-${d.id}`,className:"cursor-pointer text-sm font-medium",children:d.title}),d.description&&c.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:d.description})]})]},d.id)}):c.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:n?`No cards found matching "${n}"`:"No cards available"})})]}),c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"all-except-specific",id:"all-except-specific",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"all-except-specific",className:"cursor-pointer text-sm font-medium",children:"All cards except specific ones"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to all cards, excluding selected ones"})]})]}),u==="all-except-specific"&&c.jsxs("div",{className:"ml-7 space-y-2",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Cards to exclude"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Select which cards should be excluded from filtering"})]}),c.jsx(Nn,{placeholder:"Search cards...",value:n,onChange:d=>r(d.target.value),className:"mb-2"}),c.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:l&&l.length>0?l.map(d=>{const f=(e.excludeCardIds||[]).includes(d.id);return c.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[c.jsx(dn,{id:`card-exclude-${d.id}`,checked:f,onCheckedChange:()=>a(d.id,"all-except-specific")}),c.jsxs("div",{className:"flex-1",children:[c.jsx(ce,{htmlFor:`card-exclude-${d.id}`,className:"cursor-pointer text-sm font-medium",children:d.title}),d.description&&c.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:d.description})]})]},d.id)}):c.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:n?`No cards found matching "${n}"`:"No cards available"})})]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Menu label"}),c.jsx(Nn,{value:e.label||"",onChange:d=>t({...e,label:d.target.value}),placeholder:tf(e.mode)}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}var jR="Collapsible",[q3e,fZ]=Er(jR),[Y3e,kR]=q3e(jR),hZ=E.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:s,disabled:o,onOpenChange:i,...a}=e,[l=!1,u]=$r({prop:r,defaultProp:s,onChange:i});return c.jsx(Y3e,{scope:n,disabled:o,contentId:nr(),open:l,onOpenToggle:E.useCallback(()=>u(d=>!d),[u]),children:c.jsx(Be.div,{"data-state":MR(l),"data-disabled":o?"":void 0,...a,ref:t})})});hZ.displayName=jR;var pZ="CollapsibleTrigger",ER=E.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,s=kR(pZ,n);return c.jsx(Be.button,{type:"button","aria-controls":s.contentId,"aria-expanded":s.open||!1,"data-state":MR(s.open),"data-disabled":s.disabled?"":void 0,disabled:s.disabled,...r,ref:t,onClick:Ee(e.onClick,s.onOpenToggle)})});ER.displayName=pZ;var _R="CollapsibleContent",DR=E.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=kR(_R,e.__scopeCollapsible);return c.jsx(sr,{present:n||s.open,children:({present:o})=>c.jsx(G3e,{...r,ref:t,present:o})})});DR.displayName=_R;var G3e=E.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:s,...o}=e,i=kR(_R,n),[a,l]=E.useState(r),u=E.useRef(null),d=ft(t,u),f=E.useRef(0),h=f.current,p=E.useRef(0),m=p.current,g=i.open||a,b=E.useRef(g),x=E.useRef(void 0);return E.useEffect(()=>{const y=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(y)},[]),Lr(()=>{const y=u.current;if(y){x.current=x.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const v=y.getBoundingClientRect();f.current=v.height,p.current=v.width,b.current||(y.style.transitionDuration=x.current.transitionDuration,y.style.animationName=x.current.animationName),l(r)}},[i.open,r]),c.jsx(Be.div,{"data-state":MR(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!g,...o,ref:d,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":m?`${m}px`:void 0,...e.style},children:g&&s})});function MR(e){return e?"open":"closed"}var mZ=hZ,K3e=ER,Z3e=DR;const Dc=mZ,Mc=ER,Tc=DR;function X3e(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return N.useMemo(()=>r=>{t.forEach(s=>s(r))},t)}const SS=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Up(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function TR(e){return"nodeType"in e}function Is(e){var t,n;return e?Up(e)?e:TR(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function RR(e){const{Document:t}=Is(e);return e instanceof t}function yx(e){return Up(e)?!1:e instanceof Is(e).HTMLElement}function gZ(e){return e instanceof Is(e).SVGElement}function Wp(e){return e?Up(e)?e.document:TR(e)?RR(e)?e:yx(e)||gZ(e)?e.ownerDocument:document:document:document}const Ei=SS?N.useLayoutEffect:N.useEffect;function CS(e){const t=N.useRef(e);return Ei(()=>{t.current=e}),N.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)},[])}function Q3e(){const e=N.useRef(null),t=N.useCallback((r,s)=>{e.current=setInterval(r,s)},[]),n=N.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function ob(e,t){t===void 0&&(t=[e]);const n=N.useRef(e);return Ei(()=>{n.current!==e&&(n.current=e)},t),n}function vx(e,t){const n=N.useRef();return N.useMemo(()=>{const r=e(n.current);return n.current=r,r},[...t])}function pw(e){const t=CS(e),n=N.useRef(null),r=N.useCallback(s=>{s!==n.current&&(t==null||t(s,n.current)),n.current=s},[]);return[n,r]}function mw(e){const t=N.useRef();return N.useEffect(()=>{t.current=e},[e]),t.current}let C2={};function wx(e,t){return N.useMemo(()=>{if(t)return t;const n=C2[e]==null?0:C2[e]+1;return C2[e]=n,e+"-"+n},[e,t])}function bZ(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];return r.reduce((o,i)=>{const a=Object.entries(i);for(const[l,u]of a){const d=o[l];d!=null&&(o[l]=d+e*u)}return o},{...t})}}const th=bZ(1),ib=bZ(-1);function J3e(e){return"clientX"in e&&"clientY"in e}function NS(e){if(!e)return!1;const{KeyboardEvent:t}=Is(e.target);return t&&e instanceof t}function e$e(e){if(!e)return!1;const{TouchEvent:t}=Is(e.target);return t&&e instanceof t}function gw(e){if(e$e(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return J3e(e)?{x:e.clientX,y:e.clientY}:null}const _i=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[_i.Translate.toString(e),_i.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+" "+n+"ms "+r}}}),d3="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function t$e(e){return e.matches(d3)?e:e.querySelector(d3)}const n$e={display:"none"};function r$e(e){let{id:t,value:n}=e;return N.createElement("div",{id:t,style:n$e},n)}function s$e(e){let{id:t,announcement:n,ariaLiveType:r="assertive"}=e;const s={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return N.createElement("div",{id:t,style:s,role:"status","aria-live":r,"aria-atomic":!0},n)}function o$e(){const[e,t]=N.useState("");return{announce:N.useCallback(r=>{r!=null&&t(r)},[]),announcement:e}}const xZ=N.createContext(null);function i$e(e){const t=N.useContext(xZ);N.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function a$e(){const[e]=N.useState(()=>new Set),t=N.useCallback(r=>(e.add(r),()=>e.delete(r)),[e]);return[N.useCallback(r=>{let{type:s,event:o}=r;e.forEach(i=>{var a;return(a=i[s])==null?void 0:a.call(i,o)})},[e]),t]}const l$e={draggable:`
976
+ `)),[]});var z5e=(e=>(e[e.None=0]="None",e[e.Closed=1]="Closed",e[e.Enter=2]="Enter",e[e.Leave=4]="Leave",e))(z5e||{});function B5e(e){let t={};for(let n in e)e[n]===!0&&(t[`data-${n}`]="");return t}function V5e(e,t,n,r){let[s,o]=N.useState(n),{hasFlag:i,addFlag:a,removeFlag:l}=L5e(e&&s?3:0),u=N.useRef(!1),d=N.useRef(!1),f=gx();return Kn(()=>{var h;if(e){if(n&&o(!0),!t){n&&a(3);return}return(h=void 0)==null||h.call(r,n),H5e(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 p;d.current&&typeof t.getAnimations=="function"&&t.getAnimations().length>0||(u.current=!1,l(7),n||o(!1),(p=void 0)==null||p.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 H5e(e,{prepare:t,run:n,done:r,inFlight:s}){let o=ba();return W5e(e,{prepare:t,inFlight:s}),o.nextFrame(()=>{n(),o.requestAnimationFrame(()=>{o.add(U5e(e,r))})}),o.dispose}function U5e(e,t){var n,r;let s=ba();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 W5e(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 q5e(e,{container:t,accept:n,walk:r}){let s=N.useRef(n),o=N.useRef(r);N.useEffect(()=>{s.current=n,o.current=r},[n,r]),Kn(()=>{if(!t||!e)return;let i=mx(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 J4(e,t){let n=N.useRef([]),r=yt(e);N.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 Y5e(){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 KK={...E},G5e=KK.useInsertionEffect,K5e=G5e||(e=>e());function ZK(e){const t=E.useRef(()=>{if(process.env.NODE_ENV!=="production")throw new Error("Cannot call an event handler while rendering.")});return K5e(()=>{t.current=e}),E.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 IE=typeof document<"u"?N.useLayoutEffect:N.useEffect;let e3=!1,Z5e=0;const t3=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+Z5e++;function X5e(){const[e,t]=E.useState(()=>e3?t3():void 0);return IE(()=>{e==null&&t(t3())},[]),E.useEffect(()=>{e3=!0},[]),e}const Q5e=KK.useId,J5e=Q5e||X5e;let tb;process.env.NODE_ENV!=="production"&&(tb=new Set);function e4e(){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=tb)!=null&&e.has(s))){var o;(o=tb)==null||o.add(s),console.warn(s)}}function t4e(){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=tb)!=null&&e.has(s))){var o;(o=tb)==null||o.add(s),console.error(s)}}function n4e(){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 r4e=E.createContext(null),s4e=E.createContext(null),o4e=()=>{var e;return((e=E.useContext(r4e))==null?void 0:e.id)||null},i4e=()=>E.useContext(s4e),a4e="data-floating-ui-focusable";function l4e(e){const{open:t=!1,onOpenChange:n,elements:r}=e,s=J5e(),o=E.useRef({}),[i]=E.useState(()=>n4e()),a=o4e()!=null;if(process.env.NODE_ENV!=="production"){const p=r.reference;p&&!es(p)&&t4e("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]=E.useState(r.reference),d=ZK((p,m,g)=>{o.current.openEvent=p?m:void 0,i.emit("openchange",{open:p,event:m,reason:g,nested:a}),n==null||n(p,m,g)}),f=E.useMemo(()=>({setPositionReference:u}),[]),h=E.useMemo(()=>({reference:l||r.reference||null,floating:r.floating||null,domReference:r.reference}),[l,r.reference,r.floating]);return E.useMemo(()=>({dataRef:o,open:t,onOpenChange:d,elements:h,events:i,floatingId:s,refs:f}),[t,d,h,i,s,f])}function c4e(e){e===void 0&&(e={});const{nodeId:t}=e,n=l4e({...e,elements:{reference:null,floating:null,...e.elements}}),r=e.rootContext||n,s=r.elements,[o,i]=E.useState(null),[a,l]=E.useState(null),d=(s==null?void 0:s.domReference)||o,f=E.useRef(null),h=i4e();IE(()=>{d&&(f.current=d)},[d]);const p=nz({...e,elements:{...s,...a&&{reference:a}}}),m=E.useCallback(v=>{const w=es(v)?{getBoundingClientRect:()=>v.getBoundingClientRect(),contextElement:v}:v;l(w),p.refs.setReference(w)},[p.refs]),g=E.useCallback(v=>{(es(v)||v===null)&&(f.current=v,i(v)),(es(p.refs.reference.current)||p.refs.reference.current===null||v!==null&&!es(v))&&p.refs.setReference(v)},[p.refs]),b=E.useMemo(()=>({...p.refs,setReference:g,setPositionReference:m,domReference:f}),[p.refs,g,m]),x=E.useMemo(()=>({...p.elements,domReference:d}),[p.elements,d]),y=E.useMemo(()=>({...p,...r,refs:b,elements:x,nodeId:t}),[p,b,x,t,r]);return IE(()=>{r.dataRef.current.floatingContext=y;const v=h==null?void 0:h.nodesRef.current.find(w=>w.id===t);v&&(v.context=y)}),E.useMemo(()=>({...p,context:y,refs:b,elements:x}),[p,b,x,y])}const n3="active",r3="selected";function v2(e,t,n){const r=new Map,s=n==="item";let o=e;if(s&&e){const{[n3]:i,[r3]:a,...l}=e;o=l}return{...n==="floating"&&{tabIndex:-1,[a4e]:""},...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&&[n3,r3].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,p=arguments.length,m=new Array(p),g=0;g<p;g++)m[g]=arguments[g];return(h=r.get(u))==null?void 0:h.map(b=>b(...m)).find(b=>b!==void 0)}}}else i[u]=d}),i),{})}}function u4e(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=E.useCallback(a=>v2(a,e,"reference"),t),o=E.useCallback(a=>v2(a,e,"floating"),n),i=E.useCallback(a=>v2(a,e,"item"),r);return E.useMemo(()=>({getReferenceProps:s,getFloatingProps:o,getItemProps:i}),[s,o,i])}function s3(e,t){return{...e,rects:{...e.rects,floating:{...e.rects.floating,height:t}}}}const d4e=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}=da(e,t),{rects:f,elements:{floating:h}}=t,p=n.current[i],m=(u==null?void 0:u.current)||h,g=h.clientTop||m.clientTop,b=h.clientTop!==0,x=m.clientTop!==0,y=h===m;if(process.env.NODE_ENV!=="production"&&(t.placement.startsWith("bottom")||e4e('`placement` side must be "bottom" when using the `inner`',"middleware.")),!p)return{};const v={...t,...await mD(-p.offsetTop-h.clientTop-f.reference.height/2-p.offsetHeight/2-o).fn(t)},w=await FC(s3(v,m.scrollHeight+g+h.clientTop),d),S=await FC(v,{...d,elementContext:"reference"}),C=Jr(0,w.top),j=v.y+C,_=(m.scrollHeight>m.clientHeight?M=>M:Mg)(Jr(0,m.scrollHeight+(b&&y||x?g*2:0)-C-Jr(0,w.bottom)));if(m.style.maxHeight=_+"px",m.scrollTop=C,s){const M=m.offsetHeight<p.offsetHeight*fl(a,n.current.length)-1||S.top>=-l||S.bottom>=-l;gc.flushSync(()=>s(M))}return r&&(r.current=await FC(s3({...v,y:j},m.offsetHeight+g+h.clientTop),d)),{y:j}}});function f4e(e,t){const{open:n,elements:r}=e,{enabled:s=!0,overflowRef:o,scrollRef:i,onChange:a}=t,l=ZK(a),u=E.useRef(!1),d=E.useRef(null),f=E.useRef(null);E.useEffect(()=>{if(!s)return;function p(g){if(g.ctrlKey||!m||o.current==null)return;const b=g.deltaY,x=o.current.top>=-.5,y=o.current.bottom>=-.5,v=m.scrollHeight-m.clientHeight,w=b<0?-1:1,S=b<0?"max":"min";m.scrollHeight<=m.clientHeight||(!x&&b>0||!y&&b<0?(g.preventDefault(),gc.flushSync(()=>{l(C=>C+Math[S](b,v*w))})):/firefox/i.test(Y5e())&&(m.scrollTop+=b))}const m=(i==null?void 0:i.current)||r.floating;if(n&&m)return m.addEventListener("wheel",p),requestAnimationFrame(()=>{d.current=m.scrollTop,o.current!=null&&(f.current={...o.current})}),()=>{d.current=null,f.current=null,m.removeEventListener("wheel",p)}},[s,n,r.floating,o,i,l]);const h=E.useMemo(()=>({onKeyDown(){u.current=!0},onWheel(){u.current=!1},onPointerMove(){u.current=!1},onScroll(){const p=(i==null?void 0:i.current)||r.floating;if(!(!o.current||!p||!u.current)){if(d.current!==null){const m=p.scrollTop-d.current;(o.current.bottom<-.5&&m<-1||o.current.top<-.5&&m>1)&&gc.flushSync(()=>l(g=>g+m))}requestAnimationFrame(()=>{d.current=p.scrollTop})}}}),[r.floating,l,o,i]);return E.useMemo(()=>s?{floating:h}:{},[s,h])}let bx=N.createContext({styles:void 0,setReference:()=>{},setFloating:()=>{},getReferenceProps:()=>({}),getFloatingProps:()=>({}),slot:{}});bx.displayName="FloatingContext";let xR=N.createContext(null);xR.displayName="PlacementContext";function h4e(e){return N.useMemo(()=>e?typeof e=="string"?{to:e}:e:null,[e])}function p4e(){return N.useContext(bx).setReference}function m4e(){let{getFloatingProps:e,slot:t}=N.useContext(bx);return N.useCallback((...n)=>Object.assign({},e(...n),{"data-anchor":t.anchor}),[e,t])}function g4e(e=null){e===!1&&(e=null),typeof e=="string"&&(e={to:e});let t=N.useContext(xR),n=N.useMemo(()=>e,[JSON.stringify(e,(s,o)=>{var i;return(i=o==null?void 0:o.outerHTML)!=null?i:o})]);Kn(()=>{t==null||t(n??null)},[t,n]);let r=N.useContext(bx);return N.useMemo(()=>[r.setFloating,e?r.styles:{}],[r.setFloating,e,r.styles])}let o3=4;function b4e({children:e,enabled:t=!0}){let[n,r]=N.useState(null),[s,o]=N.useState(0),i=N.useRef(null),[a,l]=N.useState(null);x4e(a);let u=t&&n!==null&&a!==null,{to:d="bottom",gap:f=0,offset:h=0,padding:p=0,inner:m}=y4e(n,a),[g,b="center"]=d.split(" ");Kn(()=>{u&&o(0)},[u]);let{refs:x,floatingStyles:y,context:v}=c4e({open:u,placement:g==="selection"?b==="center"?"bottom":`bottom-${b}`:b==="center"?`${g}`:`${g}-${b}`,strategy:"absolute",transform:!1,middleware:[mD({mainAxis:g==="selection"?0:f,crossAxis:h}),rz({padding:p}),g!=="selection"&&sz({padding:p}),g==="selection"&&m?d4e({...m,padding:p,overflowRef:i,offset:s,minItemsVisible:o3,referenceOverflowThreshold:p,onFallbackChange(M){var R,O;if(!M)return;let T=v.elements.floating;if(!T)return;let I=parseFloat(getComputedStyle(T).scrollPaddingBottom)||0,F=Math.min(o3,T.childElementCount),z=0,B=0;for(let $ of(O=(R=v.elements.floating)==null?void 0:R.childNodes)!=null?O:[])if($ instanceof HTMLElement){let P=$.offsetTop,V=P+$.clientHeight+I,L=T.scrollTop,A=L+T.clientHeight;if(P>=L&&V<=A)F--;else{B=Math.max(0,Math.min(V,A)-Math.max(P,L)),z=$.clientHeight;break}}F>=1&&o($=>{let P=z*F-B+I;return $>=P?$:P})}}):null,oz({padding:p,apply({availableWidth:M,availableHeight:R,elements:O}){Object.assign(O.floating.style,{overflow:"auto",maxWidth:`${M}px`,maxHeight:`min(var(--anchor-max-height, 100vh), ${R}px)`})}})].filter(Boolean),whileElementsMounted:ez}),[w=g,S=b]=v.placement.split("-");g==="selection"&&(w="selection");let C=N.useMemo(()=>({anchor:[w,S].filter(Boolean).join(" ")}),[w,S]),j=f4e(v,{overflowRef:i,onChange:o}),{getReferenceProps:D,getFloatingProps:k}=u4e([j]),_=yt(M=>{l(M),x.setFloating(M)});return E.createElement(xR.Provider,{value:r},E.createElement(bx.Provider,{value:{setFloating:_,setReference:x.setReference,styles:y,getReferenceProps:D,getFloatingProps:k,slot:C}},e))}function x4e(e){Kn(()=>{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 y4e(e,t){var n,r,s;let o=w2((n=e==null?void 0:e.gap)!=null?n:"var(--anchor-gap, 0)",t),i=w2((r=e==null?void 0:e.offset)!=null?r:"var(--anchor-offset, 0)",t),a=w2((s=e==null?void 0:e.padding)!=null?s:"var(--anchor-padding, 0)",t);return{...e,gap:o,offset:i,padding:a}}function w2(e,t,n=void 0){let r=gx(),s=yt((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=i3(l,u);return[d,f=>{let h=XK(l);{let p=h.map(m=>window.getComputedStyle(u).getPropertyValue(m));r.requestAnimationFrame(function m(){r.nextFrame(m);let g=!1;for(let[x,y]of h.entries()){let v=window.getComputedStyle(u).getPropertyValue(y);if(p[x]!==v){p[x]=v,g=!0;break}}if(!g)return;let b=i3(l,u);d!==b&&(f(b),d=b)})}return r.dispose}]}return[n,null]}),o=N.useMemo(()=>s(e,t)[0],[e,t]),[i=o,a]=N.useState();return Kn(()=>{let[l,u]=s(e,t);if(a(l),!!u)return u(a)},[e,t]),i}function XK(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,...XK(s)]:[r]}return[]}function i3(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 v4e({children:e,freeze:t}){let n=AE(t,e);return N.createElement(N.Fragment,null,n)}function AE(e,t){let[n,r]=N.useState(t);return!e&&n!==t&&r(t),e?n:t}let yR=N.createContext(null);yR.displayName="OpenClosedContext";var nb=(e=>(e[e.Open=1]="Open",e[e.Closed=2]="Closed",e[e.Closing=4]="Closing",e[e.Opening=8]="Opening",e))(nb||{});function w4e(){return N.useContext(yR)}function S4e({value:e,children:t}){return N.createElement(yR.Provider,{value:e},t)}function C4e(e){function t(){document.readyState!=="loading"&&(e(),document.removeEventListener("DOMContentLoaded",t))}typeof window<"u"&&typeof document<"u"&&(document.addEventListener("DOMContentLoaded",t),t())}let Eu=[];C4e(()=>{function e(t){if(!(t.target instanceof HTMLElement)||t.target===document.body||Eu[0]===t.target)return;let n=t.target;n=n.closest(RE),Eu.unshift(n??t.target),Eu=Eu.filter(r=>r!=null&&r.isConnected),Eu.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 N4e(e){throw new Error("Unexpected object: "+e)}var gr=(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))(gr||{});function a3(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:N4e(e)}}var vR=(e=>(e[e.Left=0]="Left",e[e.Right=2]="Right",e))(vR||{});function j4e(e){let t=yt(e),n=N.useRef(!1);N.useEffect(()=>(n.current=!1,()=>{n.current=!0,IK(()=>{n.current&&t()})}),[t])}function k4e(){let e=typeof document>"u";return"useSyncExternalStore"in E?(t=>t.useSyncExternalStore)(E)(()=>()=>{},()=>!1,()=>!e):!1}function E4e(){let e=k4e(),[t,n]=E.useState(od.isHandoffComplete);return t&&od.isHandoffComplete===!1&&n(!1),E.useEffect(()=>{t!==!0&&n(!0)},[t]),E.useEffect(()=>od.handoff(),[]),e?!1:t}let _4e=N.createContext(!1);function D4e(){return N.useContext(_4e)}function M4e(e){let t=D4e(),n=N.useContext(JK),r=vS(e),[s,o]=N.useState(()=>{var i;if(!t&&n!==null)return(i=n.current)!=null?i:null;if(od.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 N.useEffect(()=>{s!==null&&(r!=null&&r.body.contains(s)||r==null||r.body.appendChild(s))},[s,r]),N.useEffect(()=>{t||n!==null&&o(n.current)},[n,o,t]),s}let QK=N.Fragment,T4e=Fi(function(e,t){let n=e,r=N.useRef(null),s=Cl(s5e(f=>{r.current=f}),t),o=vS(r),i=M4e(r),[a]=N.useState(()=>{var f;return od.isServer?null:(f=o==null?void 0:o.createElement("div"))!=null?f:null}),l=N.useContext(P4e),u=E4e();Kn(()=>{!i||!a||i.contains(a)||(a.setAttribute("data-headlessui-portal",""),i.appendChild(a))},[i,a]),Kn(()=>{if(a&&l)return l.register(a)},[l,a]),j4e(()=>{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=Oi();return u?!i||!a?null:In.createPortal(d({ourProps:{ref:s},theirProps:n,slot:{},defaultTag:QK,name:"Portal"}),a):null});function R4e(e,t){let n=Cl(t),{enabled:r=!0,...s}=e,o=Oi();return r?N.createElement(T4e,{...s,ref:n}):o({ourProps:{ref:n},theirProps:s,slot:{},defaultTag:QK,name:"Portal"})}let I4e=N.Fragment,JK=N.createContext(null);function A4e(e,t){let{target:n,...r}=e,s={ref:Cl(t)},o=Oi();return N.createElement(JK.Provider,{value:n},o({ourProps:s,theirProps:r,defaultTag:I4e,name:"Popover.Group"}))}let P4e=N.createContext(null),O4e=Fi(R4e),F4e=Fi(A4e),$4e=Object.assign(O4e,{Group:F4e});var L4e=(e=>(e[e.Open=0]="Open",e[e.Closed=1]="Closed",e))(L4e||{}),z4e=(e=>(e[e.Single=0]="Single",e[e.Multi=1]="Multi",e))(z4e||{}),B4e=(e=>(e[e.Pointer=0]="Pointer",e[e.Focus=1]="Focus",e[e.Other=2]="Other",e))(B4e||{}),V4e=(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))(V4e||{});function S2(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):k5e(r,i=>i.dataRef.current.domRef.current),o=n?s.indexOf(n):null;return o===-1&&(o=null),{options:s,activeOptionIndex:o}}let H4e={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===gr.Specific?t.idx:a3(t,{resolveItems:()=>u,resolveActiveIndex:()=>{var p,m;return(m=(p=e.activeOptionIndex)!=null?p:u.findIndex(g=>!d(g)))!=null?m: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=S2(e);if(i.activeOptionIndex===null){let u=i.options.findIndex(d=>!d.dataRef.current.disabled);u!==-1&&(i.activeOptionIndex=u)}let a=t.focus===gr.Specific?t.idx:a3(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=S2(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=S2(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}},wR=N.createContext(null);wR.displayName="ComboboxActionsContext";function xx(e){let t=N.useContext(wR);if(t===null){let n=new Error(`<${e} /> is missing a parent <Combobox /> component.`);throw Error.captureStackTrace&&Error.captureStackTrace(n,xx),n}return t}let eZ=N.createContext(null);function U4e(e){let t=Hp("VirtualProvider"),{options:n}=t.virtual,[r,s]=N.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=VT({enabled:n.length!==0,scrollPaddingStart:r,scrollPaddingEnd:s,count:n.length,estimateSize(){return 40},getScrollElement(){return t.optionsElement},overscan:12}),[i,a]=N.useState(0);Kn(()=>{a(u=>u+1)},[n]);let l=o.getVirtualItems();return l.length===0?null:N.createElement(eZ.Provider,{value:o},N.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 N.createElement(N.Fragment,{key:u.key},N.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 rb=N.createContext(null);rb.displayName="ComboboxDataContext";function Hp(e){let t=N.useContext(rb);if(t===null){let n=new Error(`<${e} /> is missing a parent <Combobox /> component.`);throw Error.captureStackTrace&&Error.captureStackTrace(n,Hp),n}return t}function W4e(e,t){return cl(t.type,H4e,e,t)}let q4e=N.Fragment;function Y4e(e,t){var n,r;let s=hR(),{value:o,defaultValue:i,onChange:a,form:l,name:u,by:d,disabled:f=s||!1,onClose:h,__demoMode:p=!1,multiple:m=!1,immediate:g=!1,virtual:b=null,nullable:x,...y}=e,v=GFe(i),[w=m?[]:void 0,S]=YFe(o,a,v),[C,j]=N.useReducer(W4e,{dataRef:N.createRef(),comboboxState:p?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:p}),D=N.useRef(!1),k=N.useRef({static:!1,hold:!1}),_=m5e(d),M=yt(ne=>b?d===null?b.options.indexOf(ne):b.options.findIndex(ae=>_(ae,ne)):C.options.findIndex(ae=>_(ae.dataRef.current.value,ne))),R=N.useCallback(ne=>cl(T.mode,{1:()=>w.some(ae=>_(ae,ne)),0:()=>_(w,ne)}),[w]),O=yt(ne=>C.activeOptionIndex===M(ne)),T=N.useMemo(()=>({...C,immediate:g,optionsPropsRef:k,value:w,defaultValue:v,disabled:f,mode:m?1:0,virtual:b?C.virtual:null,get activeOptionIndex(){if(D.current&&C.activeOptionIndex===null&&(b?b.options.length>0:C.options.length>0)){if(b){let ae=b.options.findIndex(ie=>{var fe,xe;return!((xe=(fe=b.disabled)==null?void 0:fe.call(b,ie))!=null&&xe)});if(ae!==-1)return ae}let ne=C.options.findIndex(ae=>!ae.dataRef.current.disabled);if(ne!==-1)return ne}return C.activeOptionIndex},calculateIndex:M,compare:_,isSelected:R,isActive:O}),[w,v,f,m,p,C,b]);Kn(()=>{var ne;b&&j({type:7,options:b.options,disabled:(ne=b.disabled)!=null?ne:null})},[b,b==null?void 0:b.options,b==null?void 0:b.disabled]),Kn(()=>{C.dataRef.current=T},[T]);let I=T.comboboxState===0;D5e(I,[T.buttonElement,T.inputElement,T.optionsElement],()=>H.closeCombobox());let F=N.useMemo(()=>{var ne,ae,ie;return{open:T.comboboxState===0,disabled:f,activeIndex:T.activeOptionIndex,activeOption:T.activeOptionIndex===null?null:T.virtual?T.virtual.options[(ne=T.activeOptionIndex)!=null?ne:0]:(ie=(ae=T.options[T.activeOptionIndex])==null?void 0:ae.dataRef.current.value)!=null?ie:null,value:w}},[T,f,w]),z=yt(()=>{if(T.activeOptionIndex!==null){if(H.setIsTyping(!1),T.virtual)A(T.virtual.options[T.activeOptionIndex]);else{let{dataRef:ne}=T.options[T.activeOptionIndex];A(ne.current.value)}H.goToOption(gr.Specific,T.activeOptionIndex)}}),B=yt(()=>{j({type:0}),D.current=!0}),$=yt(()=>{j({type:1}),D.current=!1,h==null||h()}),P=yt(ne=>{j({type:3,isTyping:ne})}),V=yt((ne,ae,ie)=>(D.current=!1,ne===gr.Specific?j({type:2,focus:gr.Specific,idx:ae,trigger:ie}):j({type:2,focus:ne,trigger:ie}))),L=yt((ne,ae)=>(j({type:4,payload:{id:ne,dataRef:ae}}),()=>{T.isActive(ae.current.value)&&(D.current=!0),j({type:5,id:ne})})),A=yt(ne=>cl(T.mode,{0(){return S==null?void 0:S(ne)},1(){let ae=T.value.slice(),ie=ae.findIndex(fe=>_(fe,ne));return ie===-1?ae.push(ne):ae.splice(ie,1),S==null?void 0:S(ae)}})),W=yt(ne=>{j({type:6,trigger:ne})}),U=yt(ne=>{j({type:8,element:ne})}),Y=yt(ne=>{j({type:9,element:ne})}),K=yt(ne=>{j({type:10,element:ne})}),H=N.useMemo(()=>({onChange:A,registerOption:L,goToOption:V,setIsTyping:P,closeCombobox:$,openCombobox:B,setActivationTrigger:W,selectActiveOption:z,setInputElement:U,setButtonElement:Y,setOptionsElement:K}),[]),[q,X]=c5e(),Z=t===null?{}:{ref:t},G=N.useCallback(()=>{if(v!==void 0)return S==null?void 0:S(v)},[S,v]),Q=Oi();return N.createElement(X,{value:q,props:{htmlFor:(r=T.inputElement)==null?void 0:r.id},slot:{open:T.comboboxState===0,disabled:f}},N.createElement(b4e,null,N.createElement(wR.Provider,{value:H},N.createElement(rb.Provider,{value:T},N.createElement(S4e,{value:cl(T.comboboxState,{0:nb.Open,1:nb.Closed})},u!=null&&N.createElement(JFe,{disabled:f,data:w!=null?{[u]:w}:{},form:l,onReset:G}),Q({ourProps:Z,theirProps:y,slot:F,defaultTag:q4e,name:"Combobox"}))))))}let G4e="input";function K4e(e,t){var n,r,s,o,i;let a=Hp("Combobox.Input"),l=xx("Combobox.Input"),u=N.useId(),d=LK(),{id:f=d||`headlessui-combobox-input-${u}`,onChange:h,displayValue:p,disabled:m=a.disabled||!1,autoFocus:g=!1,type:b="text",...x}=e,y=N.useRef(null),v=Cl(y,t,p4e(),l.setInputElement),w=vS(a.inputElement),S=gx(),C=yt(()=>{l.onChange(null),a.optionsElement&&(a.optionsElement.scrollTop=0),l.goToOption(gr.Nothing)}),j=N.useMemo(()=>{var A;return typeof p=="function"&&a.value!==void 0?(A=p(a.value))!=null?A:"":typeof a.value=="string"?a.value:""},[a.value,p]);J4(([A,W],[U,Y])=>{if(a.isTyping)return;let K=y.current;K&&((Y===0&&W===1||A!==U)&&(K.value=A),requestAnimationFrame(()=>{if(a.isTyping||!K||(w==null?void 0:w.activeElement)!==K)return;let{selectionStart:H,selectionEnd:q}=K;Math.abs((q??0)-(H??0))===0&&H===0&&K.setSelectionRange(K.value.length,K.value.length)}))},[j,a.comboboxState,w,a.isTyping]),J4(([A],[W])=>{if(A===0&&W===1){if(a.isTyping)return;let U=y.current;if(!U)return;let Y=U.value,{selectionStart:K,selectionEnd:H,selectionDirection:q}=U;U.value="",U.value=Y,q!==null?U.setSelectionRange(K,H,q):U.setSelectionRange(K,H)}},[a.comboboxState]);let D=N.useRef(!1),k=yt(()=>{D.current=!0}),_=yt(()=>{S.nextFrame(()=>{D.current=!1})}),M=yt(A=>{switch(l.setIsTyping(!0),A.key){case ys.Enter:if(a.comboboxState!==0||D.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(),cl(a.comboboxState,{0:()=>l.goToOption(gr.Next),1:()=>l.openCombobox()});case ys.ArrowUp:return A.preventDefault(),A.stopPropagation(),cl(a.comboboxState,{0:()=>l.goToOption(gr.Previous),1:()=>{In.flushSync(()=>l.openCombobox()),a.value||l.goToOption(gr.Last)}});case ys.Home:if(A.shiftKey)break;return A.preventDefault(),A.stopPropagation(),l.goToOption(gr.First);case ys.PageUp:return A.preventDefault(),A.stopPropagation(),l.goToOption(gr.First);case ys.End:if(A.shiftKey)break;return A.preventDefault(),A.stopPropagation(),l.goToOption(gr.Last);case ys.PageDown:return A.preventDefault(),A.stopPropagation(),l.goToOption(gr.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&&C(),l.closeCombobox());case ys.Tab:if(a.comboboxState!==0)return;a.mode===0&&a.activationTrigger!==1&&l.selectActiveOption(),l.closeCombobox();break}}),R=yt(A=>{h==null||h(A),a.mode===0&&A.target.value===""&&C(),l.openCombobox()}),O=yt(A=>{var W,U,Y;let K=(W=A.relatedTarget)!=null?W:Eu.find(H=>H!==A.currentTarget);if(!((U=a.optionsElement)!=null&&U.contains(K))&&!((Y=a.buttonElement)!=null&&Y.contains(K))&&a.comboboxState===0)return A.preventDefault(),a.mode===0&&a.value===null&&C(),l.closeCombobox()}),T=yt(A=>{var W,U,Y;let K=(W=A.relatedTarget)!=null?W:Eu.find(H=>H!==A.currentTarget);(U=a.buttonElement)!=null&&U.contains(K)||(Y=a.optionsElement)!=null&&Y.contains(K)||a.disabled||a.immediate&&a.comboboxState!==0&&S.microTask(()=>{In.flushSync(()=>l.openCombobox()),l.setActivationTrigger(1)})}),I=yS(),F=o5e(),{isFocused:z,focusProps:B}=RK({autoFocus:g}),{isHovered:$,hoverProps:P}=TK({isDisabled:m}),V=N.useMemo(()=>({open:a.comboboxState===0,disabled:m,hover:$,focus:z,autofocus:g}),[a,$,z,g,m]),L=pR({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":F,"aria-autocomplete":"list",defaultValue:(i=(o=e.defaultValue)!=null?o:a.defaultValue!==void 0?p==null?void 0:p(a.defaultValue):null)!=null?i:a.defaultValue,disabled:m||void 0,autoFocus:g,onCompositionStart:k,onCompositionEnd:_,onKeyDown:M,onChange:R,onFocus:T,onBlur:O},B,P);return Oi()({ourProps:L,theirProps:x,slot:V,defaultTag:G4e,name:"Combobox.Input"})}let Z4e="button";function X4e(e,t){var n;let r=Hp("Combobox.Button"),s=xx("Combobox.Button"),o=Cl(t,s.setButtonElement),i=N.useId(),{id:a=`headlessui-combobox-button-${i}`,disabled:l=r.disabled||!1,autoFocus:u=!1,...d}=e,f=GK(r.inputElement),h=yt(j=>{switch(j.key){case ys.Space:case ys.Enter:j.preventDefault(),j.stopPropagation(),r.comboboxState===1&&In.flushSync(()=>s.openCombobox()),f();return;case ys.ArrowDown:j.preventDefault(),j.stopPropagation(),r.comboboxState===1&&(In.flushSync(()=>s.openCombobox()),r.value||s.goToOption(gr.First)),f();return;case ys.ArrowUp:j.preventDefault(),j.stopPropagation(),r.comboboxState===1&&(In.flushSync(()=>s.openCombobox()),r.value||s.goToOption(gr.Last)),f();return;case ys.Escape:if(r.comboboxState!==0)return;j.preventDefault(),r.optionsElement&&!r.optionsPropsRef.current.static&&j.stopPropagation(),In.flushSync(()=>s.closeCombobox()),f();return;default:return}}),p=yt(j=>{j.preventDefault(),!n5e(j.currentTarget)&&(j.button===vR.Left&&(r.comboboxState===0?s.closeCombobox():s.openCombobox()),f())}),m=yS([a]),{isFocusVisible:g,focusProps:b}=RK({autoFocus:u}),{isHovered:x,hoverProps:y}=TK({isDisabled:l}),{pressed:v,pressProps:w}=zFe({disabled:l}),S=N.useMemo(()=>({open:r.comboboxState===0,active:v||r.comboboxState===0,disabled:l,value:r.value,hover:x,focus:g}),[r,x,g,v,l]),C=pR({ref:o,id:a,type:T5e(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":m,disabled:l||void 0,autoFocus:u,onMouseDown:p,onKeyDown:h},b,y,w);return Oi()({ourProps:C,theirProps:d,slot:S,defaultTag:Z4e,name:"Combobox.Button"})}let Q4e="div",J4e=ME.RenderStrategy|ME.Static;function e3e(e,t){var n,r,s;let o=N.useId(),{id:i=`headlessui-combobox-options-${o}`,hold:a=!1,anchor:l,portal:u=!1,modal:d=!0,transition:f=!1,...h}=e,p=Hp("Combobox.Options"),m=xx("Combobox.Options"),g=h4e(l);g&&(u=!0);let[b,x]=g4e(g),[y,v]=N.useState(null),w=m4e(),S=Cl(t,g?b:null,m.setOptionsElement,v),C=vS(p.optionsElement),j=w4e(),[D,k]=V5e(f,y,j!==null?(j&nb.Open)===nb.Open:p.comboboxState===0);v5e(D,p.inputElement,m.closeCombobox);let _=p.__demoMode?!1:d&&p.comboboxState===0;F5e(_,C);let M=p.__demoMode?!1:d&&p.comboboxState===0;y5e(M,{allowed:N.useCallback(()=>[p.inputElement,p.buttonElement,p.optionsElement],[p.inputElement,p.buttonElement,p.optionsElement])}),Kn(()=>{var L;p.optionsPropsRef.current.static=(L=e.static)!=null?L:!1},[p.optionsPropsRef,e.static]),Kn(()=>{p.optionsPropsRef.current.hold=a},[p.optionsPropsRef,a]),q5e(p.comboboxState===0,{container:p.optionsElement,accept(L){return L.getAttribute("role")==="option"?NodeFilter.FILTER_REJECT:L.hasAttribute("role")?NodeFilter.FILTER_SKIP:NodeFilter.FILTER_ACCEPT},walk(L){L.setAttribute("role","none")}});let R=yS([(n=p.buttonElement)==null?void 0:n.id]),O=N.useMemo(()=>({open:p.comboboxState===0,option:void 0}),[p.comboboxState]),T=yt(()=>{m.setActivationTrigger(0)}),I=yt(L=>{L.preventDefault(),m.setActivationTrigger(0)}),F=pR(g?w():{},{"aria-labelledby":R,role:"listbox","aria-multiselectable":p.mode===1?!0:void 0,id:i,ref:S,style:{...h.style,...x,"--input-width":q4(p.inputElement,!0).width,"--button-width":q4(p.buttonElement,!0).width},onWheel:p.activationTrigger===0?void 0:T,onMouseDown:I,...B5e(k)}),z=D&&p.comboboxState===1,B=AE(z,(r=p.virtual)==null?void 0:r.options),$=AE(z,p.value),P=yt(L=>p.compare($,L));if(p.virtual){if(B===void 0)throw new Error("Missing `options` in virtual mode");Object.assign(h,{children:N.createElement(rb.Provider,{value:B!==p.virtual.options?{...p,virtual:{...p.virtual,options:B}}:p},N.createElement(U4e,{slot:O},h.children))})}let V=Oi();return N.createElement($4e,{enabled:u?e.static||D:!1},N.createElement(rb.Provider,{value:p.mode===1?p:{...p,isSelected:P}},V({ourProps:F,theirProps:{...h,children:N.createElement(v4e,{freeze:z},typeof h.children=="function"?(s=h.children)==null?void 0:s.call(h,O):h.children)},slot:O,defaultTag:Q4e,features:J4e,visible:D,name:"Combobox.Options"})))}let t3e="div";function n3e(e,t){var n,r,s,o;let i=Hp("Combobox.Option"),a=xx("Combobox.Option"),l=N.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,...p}=e,m=GK(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=N.useRef(null),y=ef({disabled:f,value:d,domRef:x,order:h}),v=N.useContext(eZ),w=Cl(t,x,v?v.measureElement:null),S=yt(()=>{a.setIsTyping(!1),a.onChange(d)});Kn(()=>a.registerOption(u,y),[y,u]);let C=N.useRef(!(i.virtual||i.__demoMode));Kn(()=>{if(!i.virtual&&!i.__demoMode)return ba().requestAnimationFrame(()=>{C.current=!0})},[i.virtual,i.__demoMode]),Kn(()=>{if(C.current&&i.comboboxState===0&&g&&i.activationTrigger!==0)return ba().requestAnimationFrame(()=>{var I,F;(F=(I=x.current)==null?void 0:I.scrollIntoView)==null||F.call(I,{block:"nearest"})})},[x,g,i.comboboxState,i.activationTrigger,i.activeOptionIndex]);let j=yt(I=>{I.preventDefault(),I.button===vR.Left&&(f||(S(),YK()||requestAnimationFrame(()=>m()),i.mode===0&&a.closeCombobox()))}),D=yt(()=>{if(f)return a.goToOption(gr.Nothing);let I=i.calculateIndex(d);a.goToOption(gr.Specific,I)}),k=$5e(),_=yt(I=>k.update(I)),M=yt(I=>{if(!k.wasMoved(I)||f||g)return;let F=i.calculateIndex(d);a.goToOption(gr.Specific,F,0)}),R=yt(I=>{k.wasMoved(I)&&(f||g&&(i.optionsPropsRef.current.hold||a.goToOption(gr.Nothing)))}),O=N.useMemo(()=>({active:g,focus:g,selected:b,disabled:f}),[g,b,f]),T={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:j,onFocus:D,onPointerEnter:_,onMouseEnter:_,onPointerMove:M,onMouseMove:M,onPointerLeave:R,onMouseLeave:R};return Oi()({ourProps:T,theirProps:p,slot:O,defaultTag:t3e,name:"Combobox.Option"})}let r3e=Fi(Y4e),tZ=Fi(X4e),nZ=Fi(K4e),s3e=h5e,rZ=Fi(e3e),sZ=Fi(n3e),o3e=Object.assign(r3e,{Input:nZ,Button:tZ,Label:s3e,Options:rZ,Option:sZ});function i3e({elementId:e}){const t=N.useRef(!1);return N.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 a3e=N.memo(({option:e,currentStyle:t})=>c.jsxs(sZ,{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(Rr,{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 l3e({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:p,onQueryChange:m,filterDataType:g,onEnterKey:b,activeFilterValue:x}){const[y,v]=N.useState(""),w=p!==void 0?p:y,S=m||v,C=ee(T=>T.themeStyle),j=s||e;function D(T,I){if(I)return"";const F=[">","<",">=","<=","="];return(g?Vo(g):!1)&&x&&F.includes(x.operation)?`${x.operation}${x.values[0]}`:T!=null&&T.length?T==null?void 0:T.map(B=>B.value).join(", "):""}function k(T){Array.isArray(T)||(T=[T]),t(T)}function _(){return d||j&&j.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 R(){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||!(j!=null&&j.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(dn,{className:"border-muted-foreground/50",checked:o,onCheckedChange:i})]})]})}return c.jsx(o3e,{multiple:r,value:n,onChange:k,onClose:()=>{S("")},by:(T,I)=>Array.isArray(T)||Array.isArray(I)?!1:!T||!I?T===I:T.id===I.id,children:({open:T})=>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(nZ,{className:J("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:C==null?void 0:C.controlInputRadius},displayValue:I=>D(I,T),onChange:I=>S(I.target.value),onKeyDown:I=>{if(I.key==="Enter"&&b){const F=/^(>=|<=|>|<|=)/.test(w.trim()),z=g?Vo(g):!1;F&&z&&(I.preventDefault(),b()&&I.target.blur())}}}),c.jsx(tZ,{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(Ys,{className:"size-4 text-muted-foreground transition-colors group-hover:text-foreground"})})]}),c.jsxs(rZ,{anchor:"bottom",transition:!0,style:{borderRadius:C==null?void 0:C.controlInputRadius},className:ld("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:[T&&c.jsx(i3e,{elementId:"headlessui-portal-root"}),M(),R(),_(),O(),j==null?void 0:j.map(I=>c.jsx(a3e,{option:I,currentStyle:C},I.id))]})]})})}const l3=[{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:"⇎"}],c3e=new Set(["=",">","<",">=","<=","between","not between"]);function u3e(e){return c3e.has(e)?e:">="}function d3e({filter:e}){var S;const[t,n]=N.useState(">="),[r,s]=N.useState(""),[o,i]=N.useState(""),[a,l]=N.useState(""),[u,d]=N.useState(!0),f=N.useRef(null),h=N.useRef(!1),[,p]=N.useTransition(),m=ig(r,300),g=ig(o,300),b=ig(a,300),x=ee(C=>C.filterValues),y=ee(C=>C.themeStyle),{addOrUpdateFilterValue:v,removeFilterValues:w}=Yt();return N.useEffect(()=>()=>{f.current=null,h.current=!1},[]),N.useEffect(()=>{const C=x==null?void 0:x.find(j=>j.filterId===e.id);if(C&&C.operation!=="in"){const j=u3e(C.operation);if(f.current!==j&&(n(j),f.current=j,h.current=!1),j==="between"||j==="not between"){const k=C.values[0],_=C.values[1];i(k!=null?String(k):""),l(_!=null?String(_):""),s("")}else{const k=C.values[0];s(k!=null?String(k):""),i(""),l("")}}else f.current!==null&&(s(""),i(""),l(""),!h.current&&f.current!==t&&(n(">="),h.current=!1),f.current=null),d(!1)},[x,e.id]),N.useEffect(()=>{u&&(t==="between"||t==="not between"?g===o&&b===a&&d(!1):m===r&&d(!1))},[u,t,r,m,o,a,g,b]),N.useEffect(()=>{if(!u)if(t==="between"||t==="not between"){const C=g&&g.trim()!=="",j=b&&b.trim()!=="";if(!C||!j){!C&&!j&&(p(()=>{w(e.id)}),f.current=t);return}const D=Number(g),k=Number(b);if(isNaN(D)||isNaN(k))return;const _={filterId:e.id,connectionType:e.database==="NA"?"api":"database",name:e.column,valueType:hi(e),operation:t,values:[D,k]};p(()=>{v(_)}),f.current=t}else{if(!m||m.trim()===""){p(()=>{w(e.id)}),f.current=null;return}const C=Number(m);if(isNaN(C))return;const j={filterId:e.id,connectionType:e.database==="NA"?"api":"database",name:e.column,valueType:hi(e),operation:t,values:[C]};p(()=>{v(j)}),f.current=t}},[t,m,g,b,e.id,e.column,e.database,u,v,w,e]),c.jsxs("div",{className:"flex gap-2",children:[c.jsxs(rt,{value:t,onValueChange:C=>{h.current=!0,n(C)},children:[c.jsx(Je,{className:"h-8 w-16",style:{borderRadius:y==null?void 0:y.controlInputRadius},children:c.jsx("span",{className:"font-mono text-base",children:(S=l3.find(C=>C.value===t))==null?void 0:S.symbol})}),c.jsx(et,{children:l3.map(C=>c.jsx(pe,{value:C.value,children:c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-mono",children:C.symbol}),c.jsx("span",{children:C.label})]})},C.value))})]}),t==="between"||t==="not between"?c.jsxs(c.Fragment,{children:[c.jsx(Bn,{type:"number",placeholder:"Min",value:o,onChange:C=>i(C.target.value),className:"h-8 flex-1",style:{borderRadius:y==null?void 0:y.controlInputRadius}}),c.jsx(Bn,{type:"number",placeholder:"Max",value:a,onChange:C=>l(C.target.value),className:"h-8 flex-1",style:{borderRadius:y==null?void 0:y.controlInputRadius}})]}):c.jsx(Bn,{type:"number",placeholder:"Value",value:r,onChange:C=>s(C.target.value),className:"h-8 flex-1",style:{borderRadius:y==null?void 0:y.controlInputRadius}})]})}function f3e({filter:e}){const t=e.searchMode==="numeric",n=ee(v=>v.themeStyle),{filteredRecords:r,isSingleSelect:s,allSelected:o,handleChange:i,handleSelectAll:a,handleApplyOperatorExpression:l,query:u,setQuery:d,isLoading:f,isFetching:h,isError:p,selectedRecords:m,isSearching:g,searchError:b,resultSource:x,activeFilterValue:y}=bS(e,{enableServerSearch:!0,searchDebounceMs:300,minSearchLength:2,searchThreshold:5});return f||h?c.jsx(Ho,{style:{borderRadius:n==null?void 0:n.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"}):t?c.jsx(d3e,{filter:e}):c.jsx(l3e,{showNegativeIndicator:e.operation==="not in",renderFilterModeButton:()=>c.jsx(h3e,{filter:e}),inputClassName:"h-8",options:r,selectedOptions:m,onChange:i,multiple:!s,selectAllChecked:o,onSelectAllCheckedChange:a,isSearching:g,resultSource:x,searchError:b,query:u,onQueryChange:d,filterDataType:e.dataType,activeFilterValue:y,onEnterKey:l})}function h3e({filter:e}){const t=e.operation==="in"?"include":"exclude",{setFilterMode:n,setFilterDefaultValues:r}=Yt(),s=ee(d=>d.isDashboardEditing),o=ee(d=>{var f;return(f=d.filterValues)==null?void 0:f.find(h=>h.filterId===e.id)});function i(){t==="include"?n(e.id,"exclude"):n(e.id,"include")}function a(){o!=null&&o.values&&r(e.id,o.values)}const l=(o==null?void 0:o.values)&&o.values.length>0,u=e.defaultValues&&e.defaultValues.length>0;return c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:i,variant:"secondary",size:"sm",className:J("h-6 text-xs hover:underline",{}),children:Gw(t)}),s&&c.jsx(oe,{onClick:a,variant:u?"default":"ghost",size:"sm",className:J("h-6 text-xs",{"opacity-50":!l}),disabled:!l,title:u?"Update default values":l?"Set current selection as default":"Select values to set as default",children:"Default"})]})}function p3e({filter:e}){var o;const{filteredRecords:t,handleChange:n,selectedRecords:r}=bS(e);function s(i){n([{value:i,id:i}])}return c.jsx(ga,{onValueChange:s,value:((o=r==null?void 0:r[0])==null?void 0:o.value)||"",className:"mt-2 flex gap-3 overflow-x-auto",children:t==null?void 0:t.map(i=>c.jsxs("div",{className:"flex gap-2",children:[c.jsx(Nr,{value:i.value,id:"r1"}),c.jsx(ce,{className:"text-muted-foreground",htmlFor:"r1",children:i.value})]},i.value))})}function m3e({filter:e}){var d;const t=ee(f=>f.themeStyle),{filteredRecords:n,handleChange:r,selectedRecords:s,isLoading:o,isFetching:i,isError:a}=bS(e),l=n&&n.length>10;function u(f){r([{value:f,id:f}])}return o||i?c.jsx(Ho,{style:{borderRadius:t==null?void 0:t.controlInputRadius},className:"h-8 w-full bg-foreground/10"}):a?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:[l&&c.jsx("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:c.jsx(Yn,{children:c.jsxs(bn,{delayDuration:0,children:[c.jsx(xn,{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(xr,{className:"h-3 w-3 text-amber-600"}),c.jsxs("span",{className:"text-amber-600",children:["Many options (",n.length,")"]})]})}),c.jsx(Cn,{side:"bottom",className:"max-w-xs",children:c.jsxs("p",{className:"text-xs",children:["This filter has ",n.length," options. Consider using a dropdown for better usability with many options."]})})]})})}),c.jsx(cs,{value:((d=s==null?void 0:s[0])==null?void 0:d.value)||"",onValueChange:u,className:"w-full",children:c.jsx(Wr,{className:"h-9 flex-wrap justify-start overflow-x-auto",children:n==null?void 0:n.map(f=>c.jsx(Ht,{className:"h-7",value:f.value,children:f.value},f.value))})})]})}function wS({filter:e}){return Lc(e.dataType)?c.jsx(gFe,{filter:e}):e.uiType==="radio"&&e.type==="single"?c.jsx(p3e,{filter:e}):e.uiType==="tabs"&&e.type==="single"?c.jsx(m3e,{filter:e}):c.jsx(f3e,{filter:e})}function g3e({frame:e}){const[t,n]=N.useState(!1),r=e==null?void 0:e.cards[0],{data:s,isPending:o,isError:i}=ha(r),a=e==null?void 0:e.cards[1],{data:l,isLoading:u,isFetching:d}=ha(a);return(a==null?void 0:a.type)!=="text"?c.jsx(eb,{card:r,data:(s==null?void 0:s.records)||[],isPending:o,isError:i}):c.jsxs(Ds,{className:J("group relative overflow-y-auto",t?"m-4":"mx-0"),children:[t?c.jsx("div",{className:"overflow-y-auto break-words p-1",children:c.jsx(Hh,{card:a,data:(l==null?void 0:l.records)||[],isLoading:!1})}):c.jsx(eb,{card:r,data:(s==null?void 0:s.records)||[],isPending:o,isError:i}),c.jsx("div",{className:J("fixed z-10",{"invisible bottom-4 right-4 group-hover:visible":t,"right-6 top-6":!t}),children:c.jsx(fx,{disabled:u||d,className:J("h-7 p-1"),pressed:t,onPressedChange:n,"aria-label":"Toggle bold",children:t?c.jsx(mae,{className:"size-4 text-muted-foreground/70"}):c.jsx(gae,{className:"size-4 text-muted-foreground/70"})})})]})}function hw(e){return{clickFilter:ac,drillToDetail:rD,drillThrough:lv,drillToURL:n1,drillDown:yae,drillUp:vae,dynamicDrill:xa,inlineDrill:r1}[e]||ac}function tf(e){return{clickFilter:"Filter Dashboard",drillToDetail:"Show Details",drillThrough:"Navigate to Dashboard",drillToURL:"Open External Link",drillDown:"Drill Down",drillUp:"Drill Up",dynamicDrill:"Explore Field",inlineDrill:"Drill"}[e]||"Interaction"}function b3e(e,t,n,r,s){const o=hw(e.mode),i=e.label||tf(e.mode),a=x3e(e,t,n,r,s);return{label:i,icon:o,targetInfo:a,interaction:e}}function x3e(e,t,n=0,r,s){var o,i,a,l,u,d;switch(e.mode){case"clickFilter":{if((o=e.applyToCardIds)!=null&&o.length){const f=e.applyToCardIds.length;return`Apply to ${f} ${f===1?"card":"cards"}`}return(i=e.excludeCardIds)!=null&&i.length?"Apply to all cards":"Apply to other cards"}case"drillToDetail":{if(e.targetInsightId)return"Drill into Insight";const f=((a=e.detailFields)==null?void 0:a.length)||0;return f>0?`Show ${f} detail ${f===1?"field":"fields"}`:"Show detail table"}case"drillThrough":return e.targetDashboardId,"Navigate to dashboard";case"drillToURL":{if(e.urlTemplate)try{return`Open ${new URL(e.urlTemplate).hostname}`}catch{return"Open external link"}return"Open external link"}case"drillDown":{if(e.hierarchyId&&t){const f=t.find(h=>h.id===e.hierarchyId);if(f&&f.steps.length>0){let h;if((f.type==="date"||f.baseField)&&r&&f.baseField){const p=C_(f,r,s),m=S_(f,p);h=m==null?void 0:m.field}else h=(l=f.steps[n])==null?void 0:l.field;return h?h.label:n>=f.steps.length?"End of path":f.label||"Drill by hierarchy"}}return"Drill to next level"}case"drillUp":{if(n>0&&e.hierarchyId&&t){const f=t.find(h=>h.id===e.hierarchyId);if(f&&f.steps.length>0){const h=(u=f.steps[n-2])==null?void 0:u.field;return h?`Back to ${h.label}`:`Back to All: ${f.label||"Data"}`}}return"Go back one level"}case"dynamicDrill":{if(e.drillField)return`Drill into ${e.drillField.label} data`;if((d=e.availableFields)!=null&&d.length){const f=e.availableFields.length;return`Choose from ${f} ${f===1?"dimension":"dimensions"}`}return"Explore dimension"}case"inlineDrill":{const f=e.inlineLimit||100,h=e.displayMode||"table";return`Show ${f} records as ${h}`}default:return""}}function y3e(e,t,n,r,s){return e.map(o=>b3e(o,t,n,r,s))}function v3e({open:e,onOpenChange:t,position:n,interactions:r,selectedConditions:s,onSelectInteraction:o,drillHierarchies:i,cardId:a,card:l}){const{currentDepth:u,breadcrumbs:d}=Lt(w=>{var S,C,j;return{currentDepth:a?((C=(S=w.interactionStates[a])==null?void 0:S.breadcrumbs)==null?void 0:C.length)??0:0,breadcrumbs:a?((j=w.interactionStates[a])==null?void 0:j.breadcrumbs)??[]:[]}}),f=E.useMemo(()=>y3e(r,i,u,l,d),[r,i,u,l,d]),h=E.useMemo(()=>{if(s.length===0)return"";const w=s[0];if(w.label){const S=w.label.split(/[=><]/);if(S.length>1)return S[1].trim()}return String(w.value)},[s]);if(E.useEffect(()=>{if(!e)return;const w=S=>{S.key==="Escape"&&t(!1)};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[e,t]),!e||!n)return null;const p=280,m=80+f.length*60,g=window.innerWidth,b=window.innerHeight;let x=n.x,y=n.y+8;x+p>g&&(x=Math.max(8,g-p-8)),y+m>b&&(y=Math.max(8,n.y-m-8));const v=c.jsxs("div",{className:"semaphor-scope",style:{position:"fixed",inset:0,pointerEvents:"none",background:"transparent"},children:[c.jsx("div",{className:"fixed inset-0",style:{zIndex:50,pointerEvents:"auto",background:"transparent"},onClick:()=>t(!1),"aria-hidden":"true"}),c.jsxs("div",{className:J("fixed rounded-lg border bg-popover shadow-lg","animate-in fade-in-0 zoom-in-95"),style:{left:`${x}px`,top:`${y}px`,zIndex:51,width:`${p}px`,maxHeight:"400px",pointerEvents:"auto"},role:"menu","aria-label":"Select interaction",children:[h&&c.jsxs("div",{className:"border-b px-4 py-3",children:[c.jsx("p",{className:"text-xs text-muted-foreground",children:"Selected"}),c.jsx("p",{className:"text-sm font-medium",children:h})]}),c.jsx("div",{className:"max-h-80 overflow-y-auto py-1",children:f.map((w,S)=>{var D;const C=w.icon,j=w.interaction.mode==="dynamicDrill"&&(S===0||((D=f[S-1])==null?void 0:D.interaction.mode)!=="dynamicDrill");return c.jsxs(E.Fragment,{children:[j&&c.jsx("div",{className:"border-t px-4 py-2",children:c.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"⚡ Explore Other Fields"})}),c.jsxs("button",{className:J("flex w-full items-start gap-3 px-4 py-3","hover:bg-accent hover:text-accent-foreground","cursor-pointer transition-colors","border-b text-left last:border-b-0"),onClick:()=>{o(w.interaction),t(!1)},role:"menuitem",children:[c.jsx("div",{className:"mt-0.5 flex-shrink-0",children:c.jsx(C,{className:"h-4 w-4 text-muted-foreground"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("p",{className:"mb-1 text-sm font-medium leading-none",children:w.label}),w.targetInfo&&c.jsx("p",{className:"text-xs text-muted-foreground",children:w.targetInfo})]})]})]},S)})})]})]});return In.createPortal(v,document.body)}function w3e(e){const t=N.useRef([]),n=N.useRef(null),r=N.useRef(null),o=di(e.interactionConfig).some(h=>h.mode==="clickFilter"&&h.trigger!==void 0),i=qm(h=>h.registerClearBlurCallback),a=qm(h=>h.unregisterCard);N.useEffect(()=>{const h=()=>{r.current&&f(r.current)};return i(e.id,h),()=>{a(e.id)}},[e.id,i,a]);function l({chart:h,selectedSegments:p,storedOriginalColorsRef:m}){if(!h||!h.canvas||!h.canvas.ownerDocument){console.warn("Chart or canvas is null when trying to toggle blur segments");return}const g=h.data.datasets;m.current||(m.current=g.map((x,y)=>h.getDatasetMeta(y).data.map(w=>w.options.backgroundColor)));const b=m.current;g.forEach((x,y)=>{const v=b[y];if(p.length===0){x.backgroundColor=[...v];return}x.backgroundColor=v.map((w,S)=>p.some(j=>j.datasetIndex===y&&j.dataIndex===S)?w:u(w,.2))});try{h.update()}catch(x){console.warn("Failed to update chart during blur toggle:",x)}}function u(h,p=.2){if(h.startsWith("rgba"))return h.replace(/[\d.]+\)$/g,`${p})`);if(h.startsWith("#")){const m=parseInt(h.slice(1,3),16),g=parseInt(h.slice(3,5),16),b=parseInt(h.slice(5,7),16);return`rgba(${m}, ${g}, ${b}, ${p})`}return h}function d(h,p){var v;if(!o||!p)return;r.current=p;const m=p.getElementsAtEventForMode(h,"nearest",{intersect:!0},!0);if(!m.length)return;const{datasetIndex:g,index:b}=m[0],x={datasetIndex:g,dataIndex:b};if(((v=h.native)==null?void 0:v.shiftKey)||h.shiftKey){const w=t.current.findIndex(S=>S.datasetIndex===g&&S.dataIndex===b);w>=0?t.current.splice(w,1):t.current.push(x)}else{const w=t.current.length===1&&t.current[0].datasetIndex===g&&t.current[0].dataIndex===b;t.current=w?[]:[x]}l({chart:p,selectedSegments:t.current,storedOriginalColorsRef:n})}function f(h){h&&(t.current=[],n.current&&l({chart:h,selectedSegments:[],storedOriginalColorsRef:n}))}return{handleChartClick:d,clearBlur:f}}function S3e({resolvedCardConfig:e,card:t,records:n,chart:r,clickEvent:s}){var u,d,f,h,p,m,g,b,x,y;const o=r==null?void 0:r.getElementsAtEventForMode(s,"nearest",{intersect:!0},!0);if(!o.length)return;const i=o[0].datasetIndex,a=o[0].index,l=(d=(u=o[0].element)==null?void 0:u.$context)==null?void 0:d.raw;console.log("datasetIndex",i),console.log("clickIndex",a),console.log("value",l);try{if(!(n!=null&&n.length))return;const{keys:v}=rr(n),{groupByColumns:w=[],pivotByColumns:S=[],metricColumns:C=[]}=e||t.config,j=D=>w.find(k=>k.label===D)||S.find(k=>k.label===D)||C.find(k=>k.label===D);if(t.type==="map"){const D=v[0],k=((h=(f=l==null?void 0:l.feature)==null?void 0:f.properties)==null?void 0:h.name)||((m=(p=l==null?void 0:l.feature)==null?void 0:p.properties)==null?void 0:m.NAME),_=j(D);return!_||k==null?void 0:{conditions:[{field:_,operator:"=",value:k}]}}if(["pie","funnel","doughnut"].includes(t.type)){const D=v[0],k=v==null?void 0:v[1+i],_=j(D),M=j(k),R=(g=n==null?void 0:n[a])==null?void 0:g[D];if(!_||R==null){console.log("no dim field or value",D,R);return}return{conditions:[{field:_,operator:"=",value:R}],metrics:M?[{field:M,value:l}]:void 0}}if(["stackedBar","bar","line"].includes(t.type)){const D=v[0],k=j(D),_=(b=n==null?void 0:n[a])==null?void 0:b[D];if(!k||_==null){console.log("no dim field or value for stacked bar",D,_);return}const M=C[i]||C[0];if(!M){console.log("no metric field found");return}const R=S[0],T=Object.keys(n[0]).filter(B=>B!==D)[i],F=(T?(x=n==null?void 0:n[a])==null?void 0:x[T]:(y=n==null?void 0:n[a])==null?void 0:y[M.label])??l,z=[{field:k,operator:"=",value:_}];return R&&T&&z.push({field:R,operator:"=",value:T}),{conditions:z,metrics:[{field:M,value:F}]}}}catch(v){console.error("getClickContextFromChart error",v)}}function C3e(e){return e&&typeof e=="object"&&"field"in e&&"operator"in e}function N3e(e){return e&&typeof e=="object"&&"filterId"in e&&"operation"in e&&"values"in e}function oZ({filters:e,filterDefinitions:t,contextMode:n,className:r,showLabel:s=!0,labelText:o="Applied Filters:",icon:i}){if(!e||e.length===0)return n==="none"?c.jsx("div",{className:"px-6 pb-4",children:c.jsx("span",{className:"text-xs text-muted-foreground",children:"No filters applied"})}):null;const l=e.map(u=>{var d,f;if(C3e(u))return{fieldName:((d=u.field)==null?void 0:d.label)||((f=u.field)==null?void 0:f.name)||"Unknown",operator:u.operator,value:k3e(u)};if(N3e(u)){const h=t==null?void 0:t.find(p=>p.id===u.filterId);return{fieldName:(h==null?void 0:h.title)||u.name,operator:u.operation,value:j3e(u)}}else return{fieldName:"Unknown",operator:"=",value:String(u)}}).reduce((u,d)=>(u[d.fieldName]||(u[d.fieldName]=[]),u[d.fieldName].push(d),u),{});return c.jsxs("div",{className:r||"border-b px-6 pb-4",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s&&i&&c.jsxs("div",{className:"flex items-center gap-2 text-foreground/80",children:[i,c.jsx("span",{className:"whitespace-nowrap text-sm font-medium",children:o})]}),s&&!i&&c.jsx("span",{className:"whitespace-nowrap text-sm text-muted-foreground",children:o}),c.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(l).map(([u,d])=>c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsxs("span",{className:"text-sm font-medium",children:[u,":"]}),d.map((f,h)=>c.jsx(Fe,{variant:"outline",className:"cursor-pointer select-none border-primary/20 bg-gradient-to-r from-primary/5 to-primary/10 text-primary shadow-sm transition-all hover:from-primary/10 hover:to-primary/15 hover:shadow-md dark:border-primary/30 dark:from-primary/10 dark:to-primary/20 dark:text-primary dark:hover:from-primary/15 dark:hover:to-primary/25",children:f.value},`${u}-${h}`))]},u))})]}),n&&c.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:[n==="interactionFilters"&&c.jsx("span",{children:"Showing data filtered by interaction only"}),n==="full"&&c.jsx("span",{children:"Showing data with all dashboard filters + interaction filters"}),n==="none"&&c.jsx("span",{children:"Showing all data (no filters applied)"})]})]})}function j3e(e){const{values:t,operation:n}=e;return!t||t.length===0?"":n==="="||n==="!="||n===">"||n==="<"||n===">="||n==="<="?String(t[0]):n==="in"||n==="not in"?t.map(r=>String(r)).join(", "):(n==="between"||n==="not between")&&t.length===2?`${t[0]} - ${t[1]}`:String(t[0])}function k3e(e){const{operator:t,value:n}=e;if(e.label){const r=e.label.split(/[=><]/);if(r.length>1)return r[1].trim()}switch(t){case"=":return String(n);case"!=":return`≠ ${n}`;case">":return`> ${n}`;case"<":return`< ${n}`;case">=":return`≥ ${n}`;case"<=":return`≤ ${n}`;case"in":return Array.isArray(n)?n.join(", "):String(n);case"not in":return`not ${Array.isArray(n)?n.join(", "):n}`;case"contains":return`contains ${n}`;case"startsWith":return`starts with ${n}`;case"endsWith":return`ends with ${n}`;case"between":return Array.isArray(n)?`between ${n[0]} and ${n[1]}`:String(n);case"not between":return Array.isArray(n)?`not between ${n[0]} and ${n[1]}`:String(n);case"isNull":return"is null";case"isNotNull":return"is not null";default:return String(n)}}function E3e({cardId:e,className:t}){const n=Lt(d=>d.interactionStates[e]),r=Lt(d=>d.popInteractionStep),s=Lt(d=>d.resetInteractionState),o=(n==null?void 0:n.breadcrumbs)??[];if(n==null||n.hierarchyId,o.length===0)return null;const i=d=>{const f=o.length-d-1;for(let h=0;h<f;h++)r(e)},a=()=>{s(e)},l=d=>(d.sourceFilterGroups[0],d.toField?d.toField.label||d.toField.name:"Drill Step"),u=d=>{const f=d.sourceFilterGroups.flatMap(h=>h.filters);return c.jsxs("div",{className:"max-w-xs space-y-2 text-sm",children:[f.length>0&&c.jsx(oZ,{filters:f,className:"pb-2",labelText:"Drill Down Filters:",icon:c.jsx(Cae,{className:"h-4 w-4 text-foreground/80"})}),d.granularity&&c.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[c.jsx(os,{className:"h-4 w-4 text-foreground/80"}),c.jsxs("span",{className:"text-sm font-medium text-foreground/80",children:["Granularity: ",d.granularity]})]}),d.metric&&c.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[c.jsx(lae,{className:"h-4 w-4 text-foreground/80"}),c.jsxs("span",{className:"text-sm font-medium text-foreground/80",children:["Value:"," ",d.metric.formattedValue||d.metric.value]})]})]})};return c.jsx(Yn,{children:c.jsxs("div",{className:J("flex items-center gap-1 text-sm",t),children:[c.jsx(bn,{children:c.jsx(xn,{asChild:!0,children:c.jsx("button",{className:"flex items-center p-0 text-muted-foreground hover:text-foreground",onClick:a,"aria-label":"Reset drill path",children:c.jsx(K_,{className:"h-3.5 w-3.5"})})})}),c.jsx(Ci,{className:"ml-0.5 h-3 w-3 text-muted-foreground"}),c.jsx("div",{className:"flex items-center",children:o.map((d,f)=>c.jsxs("div",{className:"flex items-center",children:[f>0&&c.jsx(Ci,{className:"mx-1 h-3 w-3 text-muted-foreground"}),c.jsxs(bn,{delayDuration:0,children:[c.jsx(xn,{asChild:!0,children:c.jsx(oe,{variant:"link",size:"sm",className:"h-6 px-1 text-muted-foreground no-underline hover:text-foreground hover:no-underline",onClick:()=>i(f),"aria-label":`Go back to: ${l(d)}`,children:l(d)})}),c.jsx(lR,{className:"ml-4",side:"bottom",children:u(d)})]})]},f))})]})})}function _3e(e){switch(e){case"content-only":return{showHeader:!1,showTitle:!1,showDescription:!1,showTabs:!1,showFooter:!1,showFilters:!1,showBreadcrumbs:!1,showRefreshIndicator:!1,showFilterInfo:!1};case"print":return{showHeader:!0,showTitle:!0,showDescription:!0,showTabs:!1,showFilters:!1,showBreadcrumbs:!1,showRefreshIndicator:!1,showFilterInfo:!1,showTableToolbar:!1,showColumnSettings:!1};case"embed":return{showHeader:!1,showTitle:!0,showDescription:!1,showTabs:!0,showFooter:!1,showFilters:!1,showBreadcrumbs:!1,showRefreshIndicator:!1,showFilterInfo:!1};case"table-print":return{showHeader:!1,showTitle:!0,showDescription:!1,showTabs:!1,showFooter:!1,showFilters:!1,showBreadcrumbs:!1,showRefreshIndicator:!1,showFilterInfo:!1,showPagination:!1,showTableToolbar:!1,showColumnSettings:!1};case"full":default:return{showHeader:!0,showTitle:!0,showDescription:!0,showTabs:!0,showFooter:!0,showFilters:!0,showBreadcrumbs:!0,showRefreshIndicator:!0,showFilterInfo:!0}}}function SR({children:e,displayPreferences:t={mode:"full"},currentUser:n}){const r=N.useMemo(()=>{const s=t.mode||"full",o=_3e(s),i=vq(n||null),a={mode:s,overrides:{...o,...i,...t.overrides}};return{displayPreferences:a,shouldShowElement:u=>{var d;return((d=a.overrides)==null?void 0:d[u])??!0}}},[t,n]);return c.jsx(zB.Provider,{value:r,children:e})}function c3({card:e,frame:t}){var ie,fe,xe,Ce,je,de,Re,Oe,mt;const{customCards:n,placeholders:r,tokenProps:s}=qe(),{shouldShowElement:o}=Bc(),i=Lt(be=>be.interactionStates[e.id]),a=((ie=i==null?void 0:i.breadcrumbs)==null?void 0:ie.length)>0,l=ee(be=>be.themeStyle),u=ee(be=>be.selectedSheetId),d=ee(be=>be.isDashboardEditing);ee(be=>be.selectedLensId);const f=ee(be=>be.dashboard.filters),h=f==null?void 0:f.find(be=>be.id===t.filterId&&!be.hide),{setCardTitle:p,setCardDescription:m,setSelectedFrameId:g,updateFilter:b}=Yt(),{updateFrame:x}=Yt(),{handleChartClick:y}=w3e(e),v=o("showHeader")&&(((fe=e.customCardPreferences)==null?void 0:fe.showCardHeader)??!0),{isError:w,isLoading:S,isFetching:C,cfg:j,isPending:D,data:k,handleDatapointClick:_,pagination:M,comparisonMetadata:R}=Kb(e),O=N.useMemo(()=>(k==null?void 0:k.records)||[],[k==null?void 0:k.records]),[T,I]=N.useState({open:!1,position:null,interactions:[],context:null}),{breadcrumbs:F,hierarchyId:z}=Lt(be=>{var se,ue;return{breadcrumbs:((se=be.interactionStates[e.id])==null?void 0:se.breadcrumbs)??[],hierarchyId:(ue=be.interactionStates[e.id])==null?void 0:ue.hierarchyId}}),B=(be,se,ue)=>{var Nt;const we=F.length>0?[{mode:"drillUp",trigger:(Nt=be[0])==null?void 0:Nt.trigger,label:"Drill Up",hierarchyId:z}]:[],Se=[];for(const Ke of be)if(Ke.mode==="dynamicDrill"&&Ke.availableFields){const $t=Ke.availableFields.filter(Ne=>!F.some(Dt=>{var hn;return((hn=Dt.toField)==null?void 0:hn.id)===Ne.id}));for(const Ne of $t)Se.push({mode:"dynamicDrill",trigger:Ke.trigger,drillField:Ne,label:Ne.label,availableFields:Ke.availableFields})}const Pe=be.filter(Ke=>Ke.mode!=="dynamicDrill"),Qe=[...we,...Pe,...Se];I({open:!0,position:ue||{x:0,y:0},interactions:Qe,context:se})},{handlePointerInteraction:$,applySelectedInteraction:P}=t6(e,t.id,u||"",B),V=N_(e),L=N.useMemo(()=>{var be;return e.type!=="pivotTable"||!((be=k==null?void 0:k.records)!=null&&be.length)?null:{records:k.records,columnSubtotalMeta:k.columnSubtotalMeta,subtotalColumns:k.subtotalColumns||[],pivotSchema:k.pivotSchema||[],groupByColumns:k.groupByColumns}},[e.type,k==null?void 0:k.records,k==null?void 0:k.columnSubtotalMeta,k==null?void 0:k.subtotalColumns,k==null?void 0:k.pivotSchema,k==null?void 0:k.groupByColumns]),A=Pp(e,L),W=(be,se)=>{const ue={...e,paginationConfig:{page:be+1,pageSize:se}},we={...t,cards:t.cards.map(Se=>Se.id===e.id?ue:Se)};u&&x(u,we)},U=be=>{var Se,Pe;const se=gY(be,(Se=e.config)==null?void 0:Se.metricColumns,(Pe=e.config)==null?void 0:Pe.groupByColumns),ue={...e,config:{...e.config||{},sortByColumns:se}},we={...t,cards:t.cards.map(Qe=>Qe.id===e.id?ue:Qe)};u&&x(u,we)};function Y(be,se){be.stopPropagation();const ue=S3e({resolvedCardConfig:V,card:e,records:(k==null?void 0:k.records)||[],chart:se,clickEvent:be.nativeEvent});if(!ue)return;const we=di(e.interactionConfig),Se=Uw(we,ue),Pe=Se.length===1&&Se[0].mode==="clickFilter",Qe=Se.some($t=>$t.mode==="dynamicDrill"),Nt=Se.length>1||Qe;be.button===0&&Pe&&!Nt&&y(be.nativeEvent,se);const Ke={shift:be.shiftKey,ctrl:be.ctrlKey,meta:be.metaKey};be.button===0?$({context:ue,gesture:"leftClick",modifierKeys:Ke,position:{x:be.clientX,y:be.clientY}}):be.button===2&&$({context:ue,gesture:"rightClick",modifierKeys:Ke,position:{x:be.clientX,y:be.clientY}})}function K(){var be,se,ue;if(n&&n.length>0){const we=n.find(Se=>Se.cardId===e.id);if(we&&we.replaceDefault){const Se=we.content;if(Se)return c.jsx(Se,{card:e})}}if(e.type==="kpi"){if(((be=t==null?void 0:t.cards)==null?void 0:be.length)===1)return c.jsx(eb,{card:e,data:w?[]:(k==null?void 0:k.records)||[],isPending:D,isError:w});if(((se=t==null?void 0:t.cards)==null?void 0:se.length)>1)return c.jsx(g3e,{frame:t})}return e.type==="text"&&((ue=t==null?void 0:t.cards)==null?void 0:ue.length)===1?c.jsx(Ds,{className:"my-4 overflow-y-auto break-words px-4",children:c.jsx(Hh,{isLoading:S||C,card:e,data:(k==null?void 0:k.records)||[]})}):ne}function H(){if(w)return c.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[c.jsx(eD,{className:"size-8 text-destructive"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Error fetching data. Check your card settings."})]});if((S||C)&&(!(k!=null&&k.records)||k.records.length===0))return e.type==="table"?c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(yK,{})}):c.jsx("div",{className:"flex h-full w-full items-center justify-center",children:c.jsx(_c,{size:"md",color:"muted","aria-label":"Loading data"})});if(k!=null&&k.records&&(k==null?void 0:k.records.length)===0)return r!=null&&r.NoRecords?c.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:r.NoRecords}):c.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[c.jsx(sD,{className:"size-8 text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(e.type==="table")return c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(rx,{card:e,data:O,paginationMetadata:M,onPaginationChange:W,onSortChange:U,isLoading:S||C,frameId:t.id,sheetId:u||"",onMultipleInteractions:B})});if(e.type==="pivotTable"&&A)return c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(ax,{card:e,data:A.data,options:A.options,onAggregationChange:be=>{const se=jE(be,e.config),ue={...e,config:se},we={...t,cards:t.cards.map(Se=>Se.id===e.id?ue:Se)};u&&x(u,we)},onAggregationLabelChange:be=>{const se=wK(be,e.config),ue={...e,config:se},we={...t,cards:t.cards.map(Se=>Se.id===e.id?ue:Se)};u&&x(u,we)}})});if(e.type==="aggregateTable")return c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(aS,{card:e,data:(k==null?void 0:k.records)||[],groupByColumns:k==null?void 0:k.groupByColumns,pivotSchema:k==null?void 0:k.pivotSchema,paginationMetadata:M,onPaginationChange:W,onAggregationChange:be=>{const se=jE(be,e.config),ue={...e,config:se},we={...t,cards:t.cards.map(Se=>Se.id===e.id?ue:Se)};u&&x(u,we)},isLoading:S||C})});if(e.type==="text")return c.jsx(Ds,{className:"overflow-y-auto break-words pr-2",children:c.jsx(Hh,{isLoading:S||C,card:e,data:(k==null?void 0:k.records)||[]})});if(e.type==="custom")return c.jsx(wl,{FallbackComponent:uS,children:c.jsx(eR,{frame:t,card:e})});if(n&&n.length>0){const be=n.find(se=>se.cardId===e.id);if(be&&be.content){const se=be.content;return c.jsx(se,{card:e})}}if(j)return c.jsx(ix,{cfg:j,onChartClick:Y,onDatapointClick:_})}function q(){if(n&&n.length>0){const be=n.find(se=>se.cardId===e.id);if(be&&be.footer){const se=be.footer;if(se)return c.jsx(se,{card:e})}}return null}function X(){var ue;const be=t.cards.filter(we=>{var Se;return!((Se=we.tabTitle)!=null&&Se.endsWith("__Header"))&&(we.displayTab===!0||we.displayTab===void 0)}),se=l==null?void 0:l.controlInputRadius;return c.jsx(cs,{value:t.activeCardId,className:"flex items-center justify-end gap-3",onValueChange:we=>{const Se={...t,activeCardId:we};x(u,Se)},children:c.jsx(Wr,{style:{borderRadius:l==null?void 0:l.controlInputRadius},className:"flex-end flex h-9 flex-wrap items-center border border-border bg-background p-0",children:(ue=t.cards.filter(we=>{var Se;return!((Se=we.tabTitle)!=null&&Se.endsWith("__Header"))&&(we.displayTab===!0||we.displayTab===void 0)}))==null?void 0:ue.map((we,Se)=>c.jsx(Ht,{className:J("h-full items-center rounded-none data-[state=active]:bg-muted data-[state=active]:shadow-none",{"border-r":Se!==be.length-1}),style:{borderTopLeftRadius:Se===0?se:0,borderTopRightRadius:Se===be.length-1?se:0,borderBottomLeftRadius:Se===0?se:0,borderBottomRightRadius:Se===be.length-1?se:0},value:we.id,children:we.tabTitle||we.title},we.id))})})}function Z(){var se,ue,we,Se;let be=t.cards.find(Pe=>Pe.type==="kpi"&&Pe.tabTitle===`${e.tabTitle}__Header`);return be||(be=t.cards.find(Pe=>Pe.type==="kpi"&&Pe.tabTitle==="All__Header")),be?c.jsx("div",{className:"flex items-end gap-2",children:c.jsx(aFe,{renderFilterInfo:()=>{var Pe,Qe,Nt,Ke;return o("showFilterInfo")&&((Qe=(Pe=e.preferences)==null?void 0:Pe.displayOptions)==null?void 0:Qe.showFilterInfo)!==!1?c.jsx(NE,{cardId:e.id,cardFilters:(Nt=e.config)==null?void 0:Nt.filters,cardFilterCount:uw(((Ke=e.config)==null?void 0:Ke.filters)||null)}):null},card:be})}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{role:"card-title-container",className:"flex h-7 items-center gap-2",children:[o("showTitle")&&c.jsx(wi,{className:J("text-base",{}),children:c.jsx(qo,{value:e.title,onSave:Pe=>p(u,e.id,Pe),isEditable:d,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),o("showTitle")&&(d||e.info)&&c.jsx(xK,{card:e}),o("showRefreshIndicator")&&e.refreshInterval&&c.jsxs(bn,{children:[c.jsx(xn,{className:"pr-1",children:c.jsx("div",{className:J("h-2 w-2 rounded-full bg-green-500 transition-opacity",{"opacity-10":S||C})})}),c.jsx(Cn,{side:"right",align:"center",children:c.jsx("p",{className:"text-xs",children:`Realtime (${e==null?void 0:e.refreshInterval})`})})]}),o("showFilterInfo")&&((ue=(se=e.preferences)==null?void 0:se.displayOptions)==null?void 0:ue.showFilterInfo)!==!1&&c.jsx(NE,{cardId:e.id,cardFilters:(we=e.config)==null?void 0:we.filters,cardFilterCount:uw(((Se=e.config)==null?void 0:Se.filters)||null)}),R&&c.jsx(vK,{metadata:R,variant:"compact"})]}),c.jsxs("div",{"data-content":"card-description-and-breadcrumb",className:"flex h-6 items-center overflow-y-auto",children:[!a&&o("showDescription")&&c.jsx("div",{className:J("text-sm text-muted-foreground",{}),children:c.jsx(qo,{value:(e==null?void 0:e.description)||"",onSave:Pe=>m(u,e.id,Pe),isEditable:d,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})}),a&&o("showBreadcrumbs")&&c.jsx(E3e,{cardId:e.id})]})]})}if(!e.id)return null;const G=((Ce=(xe=e.preferences)==null?void 0:xe.displayOptions)==null?void 0:Ce.showChrome)??!0,Q=((de=(je=e.preferences)==null?void 0:je.displayOptions)==null?void 0:de.allowScroll)??!0,ne=G?c.jsxs(c.Fragment,{children:[v?c.jsx(vi,{children:c.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 basis-0 scroll-pb-2 overflow-x-auto",role:"header-container",children:Z()}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsx("div",{children:h&&o("showFilters")&&c.jsxs("div",{style:{borderRadius:(Oe=(Re=l==null?void 0:l.chart)==null?void 0:Re.options)==null?void 0:Oe.borderRadius},"data-content":"frame-filter-container",className:"flex shrink-0 items-center",children:[!Lc(h.dataType)&&c.jsx(ce,{className:"my-1 shrink-0 px-3",children:c.jsx(qo,{value:h.title||h.column,onSave:be=>b({...h,title:be}),isEditable:d,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),c.jsx(wS,{filter:h})]})}),t.cards.length>1&&o("showTabs")&&X()]})]})}):c.jsx("div",{className:"h-8"}),c.jsx(Si,{"data-role":"card-content",className:"relative flex min-h-0 grow flex-col",children:H()}),o("showFooter")&&c.jsx(r8,{children:q()})]}):H(),ae=()=>G&&Q?"flex h-full flex-col":G&&!Q?"flex h-full flex-col overflow-hidden":!G&&!Q?"h-full":"h-full overflow-auto";return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"relative h-full",children:[c.jsx("div",{className:J(ae(),{"animate-pulse":S||C}),children:K()}),(S||C)&&(k==null?void 0:k.records)&&k.records.length>0&&c.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-background/50",children:c.jsx(_c,{size:"md",color:"muted","aria-label":"Loading data"})})]}),T.context&&c.jsx(v3e,{open:T.open,onOpenChange:be=>{I(se=>({...se,open:be}))},position:T.position,interactions:T.interactions,selectedConditions:T.context.conditions,drillHierarchies:(mt=e.interactionConfig)==null?void 0:mt.drillHierarchies,cardId:e.id,card:e,onSelectInteraction:be=>{T.context&&P(be,T.context),I({open:!1,position:null,interactions:[],context:null})}})]})}function iZ({card:e,frame:t}){return e.displayPreferences?c.jsx(SR,{displayPreferences:e.displayPreferences,children:c.jsx(c3,{card:e,frame:t})}):c.jsx(c3,{card:e,frame:t})}function D3e({card:e,frame:t,showTitle:n=!0}){const{isError:r,isLoading:s,isFetching:o,cfg:i,data:a,pagination:l}=Kb(e),u=N.useMemo(()=>{var p;return e.type!=="pivotTable"||!((p=a==null?void 0:a.records)!=null&&p.length)?null:{records:a.records,columnSubtotalMeta:a.columnSubtotalMeta,subtotalColumns:a.subtotalColumns||[],pivotSchema:a.pivotSchema||[],groupByColumns:a.groupByColumns}},[e.type,a==null?void 0:a.records,a==null?void 0:a.columnSubtotalMeta,a==null?void 0:a.subtotalColumns,a==null?void 0:a.pivotSchema,a==null?void 0:a.groupByColumns]),d=Pp(e,u),f=N.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]);if(s||o)return c.jsxs("div",{className:"flex h-full grow flex-col items-center justify-center gap-4 p-12",children:[c.jsx(On,{className:"h-8 w-8 animate-spin text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading visual..."})]});if(r)return c.jsx("div",{className:"flex flex-col items-center justify-center gap-2 p-12",children:c.jsx("p",{className:"text-sm font-medium text-destructive",children:"Failed to load visual"})});function h(){return e.type==="kpi"?c.jsx(eb,{card:e,data:(a==null?void 0:a.records)||[],isPending:s||o}):e.type==="table"?c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(rx,{card:e,data:f,isLoading:s||o,paginationMetadata:l})}):e.type==="pivotTable"&&d?c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(ax,{card:e,data:(a==null?void 0:a.records)||[],onAggregationChange:()=>{},onAggregationLabelChange:()=>{}})}):e.type==="aggregateTable"?c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(aS,{card:e,data:(a==null?void 0:a.records)||[],groupByColumns:a==null?void 0:a.groupByColumns,pivotSchema:a==null?void 0:a.pivotSchema,paginationMetadata:l,onAggregationChange:()=>{},isLoading:s||o})}):e.type==="text"?c.jsx(Ds,{className:"overflow-y-auto break-words pr-2",children:c.jsx(Hh,{isLoading:s||o,card:e,data:(a==null?void 0:a.records)||[]})}):e.type==="custom"?c.jsx(wl,{FallbackComponent:uS,children:c.jsx(eR,{frame:t,card:e})}):i?c.jsx(ix,{cfg:i,onChartClick:()=>{},onDatapointClick:()=>{}}):null}return c.jsxs("div",{className:"flex h-full w-full flex-col",children:[n&&e.title&&c.jsxs("div",{className:"border-b px-4 py-2",children:[c.jsx("h3",{className:"text-lg font-medium",children:e.title}),e.description&&c.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:e.description})]}),c.jsx("div",{className:"min-h-0 flex-1 p-4",children:h()})]})}function aZ({insightId:e,filters:t,contextMode:n}){const{data:r,isLoading:s,isError:o,error:i}=ID(e,{enabled:!!e}),a=Lt(f=>f.setInteractionState),l=Lt(f=>f.resetInteractionState),u=N.useMemo(()=>{var h;if(!r)return null;const f=(r==null?void 0:r.frameObject)??((h=r==null?void 0:r.visual)==null?void 0:h.frameObject);if(!f)return null;if(typeof f=="string")try{return JSON.parse(f)}catch{return null}return f},[r]),d=N.useMemo(()=>{var f;return(f=u==null?void 0:u.cards)!=null&&f.length?u.activeCardId&&u.cards.find(h=>h.id===u.activeCardId)||u.cards[0]:null},[u]);return N.useEffect(()=>{if(!d)return;if(n==="none"||!(t!=null&&t.length)){const m={...Ao(),contextMode:n};a(d.id,m);return}const h={sourceCardId:"drill-to-insight",interactionMode:"clickFilter",filterGroups:[{filters:t}],applyToCardIds:[d.id]},p={...Ao(),appliedClickFilters:[h],contextMode:n};return a(d.id,p),()=>{l(d.id)}},[d,t,n,a,l]),s?c.jsxs("div",{className:"flex h-full grow flex-col items-center justify-center gap-4 p-12",children:[c.jsx(On,{className:"h-8 w-8 animate-spin text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading visual..."})]}):o?c.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 p-12",children:[c.jsx("p",{className:"text-sm font-medium text-destructive",children:"Failed to load insight"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:i instanceof Error?i.message:"Unknown error"})]}):!u||!d?c.jsx("div",{className:"flex items-center justify-center p-12",children:c.jsx("p",{className:"text-sm text-muted-foreground",children:"This insight has no visual data to display"})}):c.jsx("div",{className:"h-full w-full",children:c.jsx(D3e,{card:d,frame:u,showTitle:!1})})}function M3e({filters:e,contextMode:t}){if(!e||e.length===0)return t==="none"?c.jsxs(Fe,{variant:"outline",className:"gap-1 whitespace-nowrap",children:[c.jsx(ac,{className:"h-3 w-3"}),"No filters"]}):null;const n=e.reduce((s,o)=>{var a,l;const i=((a=o.field)==null?void 0:a.label)||((l=o.field)==null?void 0:l.name)||"Unknown";return s[i]||(s[i]=[]),s[i].push(o),s},{});e.length;const r=Object.keys(n).length;return c.jsx(Yn,{children:c.jsxs(bn,{delayDuration:200,children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"cursor-help gap-1 whitespace-nowrap border border-blue-500/20 bg-blue-500/10 text-blue-700 dark:text-blue-300",children:[c.jsx(ac,{className:"h-3 w-3"}),r," ",r===1?"filter":"filters"]})}),c.jsx(Cn,{side:"bottom",align:"start",className:"max-w-md",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Applied Filters"}),c.jsx("div",{className:"space-y-1.5",children:Object.entries(n).map(([s,o])=>c.jsxs("div",{className:"text-xs",children:[c.jsxs("span",{className:"font-medium",children:[s,":"]})," ",o.map((i,a)=>c.jsxs("span",{children:[T3e(i),a<o.length-1?", ":""]},a))]},s))}),t&&c.jsx("div",{className:"border-t pt-2 text-xs text-muted-foreground",children:R3e(t)})]})})]})})}function T3e(e){const{operator:t,value:n}=e;if(e.label){const r=e.label.split(/[=><]/);if(r.length>1)return r[1].trim()}switch(t){case"=":return String(n);case"!=":return`≠ ${n}`;case">":return`> ${n}`;case"<":return`< ${n}`;case">=":return`≥ ${n}`;case"<=":return`≤ ${n}`;case"in":return Array.isArray(n)?n.join(", "):String(n);case"not in":return`not ${Array.isArray(n)?n.join(", "):n}`;case"contains":return`contains ${n}`;case"startsWith":return`starts with ${n}`;case"endsWith":return`ends with ${n}`;case"between":return Array.isArray(n)?`${n[0]}-${n[1]}`:String(n);case"not between":return Array.isArray(n)?`not ${n[0]}-${n[1]}`:String(n);case"isNull":return"is null";case"isNotNull":return"is not null";default:return String(n)}}function R3e(e){switch(e){case"filters":case"interactionFilters":return"Showing data filtered by interaction only";case"full":return"Showing data with all dashboard filters + interaction filters";case"none":return"Showing all data (no filters applied)"}}function lZ(e,t={}){const{enabled:n=!0}=t,{data:r}=ID(e,{enabled:n&&!!e});return N.useMemo(()=>{var l,u;if(!r)return{title:"",description:void 0};const o=(r==null?void 0:r.frameObject)??((l=r==null?void 0:r.visual)==null?void 0:l.frameObject);if(!o)return{title:"",description:void 0};let i=null;if(typeof o=="string")try{i=JSON.parse(o)}catch{return{title:"",description:void 0}}else i=o;if(!((u=i==null?void 0:i.cards)!=null&&u.length))return{title:"",description:void 0};const a=i.activeCardId&&i.cards.find(d=>d.id===i.activeCardId)||i.cards[0];return{title:a.title,description:a.description}},[r])}function I3e({cardId:e,children:t}){const n=Lt(o=>o.replacedCards[e]),r=Lt(o=>o.restoreCard),s=lZ((n==null?void 0:n.insightId)||"",{enabled:!!(n!=null&&n.insightId)});return n?c.jsxs("div",{className:"flex h-full w-full flex-col",children:[c.jsxs("div",{className:"border-b bg-muted/30",children:[c.jsx("div",{className:"flex items-baseline gap-2 px-5 pb-2 pt-4",children:s.title&&c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"truncate text-sm font-semibold",children:s.title}),s.description&&c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-muted-foreground",children:"-"}),c.jsx("span",{className:"truncate text-xs text-muted-foreground",children:s.description})]})]})}),c.jsxs("div",{className:"flex items-center gap-3 px-4 pb-2",children:[c.jsxs(oe,{variant:"ghost",size:"sm",onClick:()=>r(e),className:"flex-shrink-0 gap-1",children:[c.jsx(o8,{className:"h-4 w-4"}),"Back"]}),c.jsx(M3e,{filters:n.filters,contextMode:n.contextMode})]})]}),c.jsx("div",{className:"min-h-0 flex-1",children:c.jsx(aZ,{insightId:n.insightId,filters:n.filters,contextMode:n.contextMode})})]}):c.jsx(c.Fragment,{children:t})}function A3e({frame:e,footer:t,className:n,...r}){var w,S;const s=N.useRef(null),[o,i]=N.useState(!1),a=ee(C=>C.themeStyle),l=ee(C=>C.isVisualEditing),u=ee(C=>C.selectedFrameId),d=ee(C=>C.isDashboardEditing),{setSelectedFrameId:f}=Yt(),{clearSelectedVisual:h}=Rb(),{setSelectedConnectionId:p,setSelectedDatabaseName:m,setSelectedSchemaName:g,setSelectedTableName:b,setCard:x}=ur();N.useEffect(()=>{if(u===e.id&&d&&!l){const C=s==null?void 0:s.current;C==null||C.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})}},[u,e.id,d,l,s]);const y=e.cards.find(C=>C.id===e.activeCardId);function v(C){C.stopPropagation(),f(e.id),h(),y&&x(y),y!=null&&y.connectionId&&p(y==null?void 0:y.connectionId),y!=null&&y.lastSelectedDatabase&&m(y==null?void 0:y.lastSelectedDatabase),y!=null&&y.lastSelectedSchema&&g(y==null?void 0:y.lastSelectedSchema),y!=null&&y.lastSelectedTable&&b(y==null?void 0:y.lastSelectedTable)}return c.jsx(wl,{FallbackComponent:dS,children:c.jsxs("div",{tabIndex:-1,ref:s,role:"card-frame","data-frame-id":e.id,"data-active-card-id":y==null?void 0:y.id,onClick:v,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{borderRadius:a==null?void 0:a.cardBorderRadius},className:J("relative flex h-full flex-col rounded-sm border bg-background shadow-sm",{"border-dashed border-foreground/50":u===e.id&&d},a==null?void 0:a.dashboardCard,n,"semaphor-card-frame"),...r,children:[(d||((S=(w=y==null?void 0:y.preferences)==null?void 0:w.displayOptions)==null?void 0:S.showCardToolbar)!==!1)&&c.jsx(iK,{frame:e,isHovered:o}),y&&c.jsx(I3e,{cardId:y.id,children:c.jsx(iZ,{card:y,frame:e},y.id)})]})})}function CR(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}var P3e=["color"],O3e=N.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=CR(e,P3e);return N.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),N.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),F3e=["color"],cZ=N.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=CR(e,F3e);return N.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),N.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),$3e=["color"],uZ=N.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=CR(e,$3e);return N.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),N.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Gh({text:e,className:t}){const[n,r]=N.useState(!1);return c.jsx(oe,{className:J("h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",t),variant:"ghost",size:"icon",onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>{r(!1)},1e3)},children:n?c.jsx(cZ,{className:"size-3.5"}):c.jsx(_g,{className:"size-3.5"})})}function L3e({filter:e,onUpdate:t}){const[n,r]=N.useState(""),s=ee(y=>y.dashboard.sheets)||[],o=ee(y=>y.selectedSheetId),i=N.useMemo(()=>{const y=[];return s==null||s.forEach(v=>{var w;(w=v.frames)==null||w.forEach(S=>{var C;(C=S.cards)==null||C.forEach(j=>{y.push({...j,sheetId:v.id,sheetTitle:v.title||v.id})})})}),y},[s]),a=()=>e.applyToSheetIds!==void 0?"specific-sheets":e.excludeSheetIds!==void 0?"all-except-specific":"all-sheets",l=()=>e.applyToCardIds!==void 0?"specific-cards":e.excludeCardIds!==void 0?"all-except-specific":"all-cards",u=y=>{const v={};switch(y){case"all-sheets":v.applyToSheetIds=void 0,v.excludeSheetIds=void 0;break;case"specific-sheets":v.applyToSheetIds=[],v.excludeSheetIds=void 0;break;case"all-except-specific":v.applyToSheetIds=void 0,v.excludeSheetIds=[];break}t(v)},d=y=>{const v={};switch(y){case"all-cards":v.applyToCardIds=void 0,v.excludeCardIds=void 0;break;case"specific-cards":v.applyToCardIds=[],v.excludeCardIds=void 0;break;case"all-except-specific":v.applyToCardIds=void 0,v.excludeCardIds=[];break}t(v)},f=(y,v)=>{if(v==="specific-sheets"){const w=e.applyToSheetIds||[],S=w.includes(y)?w.filter(C=>C!==y):[...w,y];t({applyToSheetIds:S})}else if(v==="all-except-specific"){const w=e.excludeSheetIds||[],S=w.includes(y)?w.filter(C=>C!==y):[...w,y];t({excludeSheetIds:S})}},h=(y,v)=>{if(v==="specific-cards"){const w=e.applyToCardIds||[],S=w.includes(y)?w.filter(C=>C!==y):[...w,y];t({applyToCardIds:S})}else if(v==="all-except-specific"){const w=e.excludeCardIds||[],S=w.includes(y)?w.filter(C=>C!==y):[...w,y];t({excludeCardIds:S})}},p=()=>{const y=a();return y==="specific-sheets"?e.applyToSheetIds||[]:y==="all-except-specific"?(s==null?void 0:s.filter(v=>{var w;return!((w=e.excludeSheetIds)!=null&&w.includes(v.id))}).map(v=>v.id))||[]:(s==null?void 0:s.map(v=>v.id))||[]},m=N.useMemo(()=>{const y=p();return i.filter(v=>y.includes(v.sheetId))},[i,e.applyToSheetIds,e.excludeSheetIds]),g=N.useMemo(()=>{if(!n.trim())return m;const y=n.toLowerCase();return m.filter(v=>{var w;return(w=v==null?void 0:v.title)==null?void 0:w.toLowerCase().includes(y)})},[n,m]),b=a(),x=l();return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Sheet Scope"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Which sheets should display this filter?"})]}),c.jsxs(ga,{value:b,onValueChange:y=>u(y),className:"space-y-3",children:[c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"all-sheets",id:"all-sheets",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"all-sheets",className:"cursor-pointer text-sm font-medium",children:"All sheets"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:["Display filter on all sheets (",(s==null?void 0:s.length)||0," sheets)"]})]})]}),c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"specific-sheets",id:"specific-sheets",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"specific-sheets",className:"cursor-pointer text-sm font-medium",children:"Only specific sheets"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Display filter on selected sheets only"})]})]}),b==="specific-sheets"&&c.jsx("div",{className:"ml-7 space-y-2",children:c.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:s==null?void 0:s.map(y=>{const v=(e.applyToSheetIds||[]).includes(y.id);return c.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[c.jsx(dn,{id:`sheet-${y.id}`,checked:v,onCheckedChange:()=>f(y.id,"specific-sheets")}),c.jsxs(ce,{htmlFor:`sheet-${y.id}`,className:"cursor-pointer text-sm font-medium",children:[y.title||y.id,y.id===o&&c.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:"(this sheet)"})]})]},y.id)})})}),c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"all-except-specific",id:"all-sheets-except",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"all-sheets-except",className:"cursor-pointer text-sm font-medium",children:"All sheets except specific ones"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Display filter on all sheets except selected ones"})]})]}),b==="all-except-specific"&&c.jsx("div",{className:"ml-7 space-y-2",children:c.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:s==null?void 0:s.map(y=>{const v=(e.excludeSheetIds||[]).includes(y.id);return c.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[c.jsx(dn,{id:`sheet-exclude-${y.id}`,checked:v,onCheckedChange:()=>f(y.id,"all-except-specific")}),c.jsxs(ce,{htmlFor:`sheet-exclude-${y.id}`,className:"cursor-pointer text-sm font-medium",children:[y.title||y.id,y.id===o&&c.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:"(this sheet)"})]})]},y.id)})})})]})]}),c.jsxs("div",{className:"space-y-3 border-t pt-4",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Card Scope"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Which cards should receive this filter?"})]}),c.jsxs(ga,{value:x,onValueChange:y=>d(y),className:"space-y-3",children:[c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"all-cards",id:"all-cards",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"all-cards",className:"cursor-pointer text-sm font-medium",children:"All cards"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:["Apply filter to all cards in applicable sheets (",m.length," cards)"]})]})]}),c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"specific-cards",id:"specific-cards",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"specific-cards",className:"cursor-pointer text-sm font-medium",children:"Only specific cards"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to selected cards only"})]})]}),x==="specific-cards"&&c.jsxs("div",{className:"ml-7 space-y-2",children:[c.jsx(Nn,{placeholder:"Search cards...",value:n,onChange:y=>r(y.target.value),className:"mb-2"}),c.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:g.length>0?g.map(y=>{const v=(e.applyToCardIds||[]).includes(y.id);return c.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[c.jsx(dn,{id:`card-${y.id}`,checked:v,onCheckedChange:()=>h(y.id,"specific-cards")}),c.jsxs("div",{className:"flex-1",children:[c.jsx(ce,{htmlFor:`card-${y.id}`,className:"cursor-pointer text-sm font-medium",children:y.title}),c.jsx("p",{className:"text-xs text-muted-foreground",children:y.sheetTitle})]})]},y.id)}):c.jsxs("p",{className:"py-4 text-center text-sm text-muted-foreground",children:['No cards found matching "',n,'"']})})]}),c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"all-except-specific",id:"all-cards-except",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"all-cards-except",className:"cursor-pointer text-sm font-medium",children:"All cards except specific ones"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to all cards except selected ones"})]})]}),x==="all-except-specific"&&c.jsxs("div",{className:"ml-7 space-y-2",children:[c.jsx(Nn,{placeholder:"Search cards...",value:n,onChange:y=>r(y.target.value),className:"mb-2"}),c.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:g.length>0?g.map(y=>{const v=(e.excludeCardIds||[]).includes(y.id);return c.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[c.jsx(dn,{id:`card-exclude-${y.id}`,checked:v,onCheckedChange:()=>h(y.id,"all-except-specific")}),c.jsxs("div",{className:"flex-1",children:[c.jsx(ce,{htmlFor:`card-exclude-${y.id}`,className:"cursor-pointer text-sm font-medium",children:y.title}),c.jsx("p",{className:"text-xs text-muted-foreground",children:y.sheetTitle})]})]},y.id)}):c.jsxs("p",{className:"py-4 text-center text-sm text-muted-foreground",children:['No cards found matching "',n,'"']})})]})]})]}),c.jsx("div",{className:"rounded-md bg-blue-50 p-3 text-xs text-blue-900 dark:bg-blue-950 dark:text-blue-100",children:"ℹ️ Cards are filtered based on sheet scope selection. Only cards from applicable sheets are shown in card scope."})]})}function z3e(e){for(const[n,r]of Object.entries(e8))if(JSON.stringify(r)===JSON.stringify(e))return n;const t={day:"day",week:"week",month:"month",quarter:"quarter",year:"year"};switch(e.mode){case"last":{const n=e.complete?" (complete)":"",r=e.n>1?"s":"";return`Last ${e.n} ${t[e.unit]}${r}${n}`}case"this":{const n=e.toDate?" to date":"";return`This ${t[e.unit]}${n}`}case"previous":return`Previous ${t[e.unit]}`;case"between":return`Between ${e.from} and ${e.to} ${t[e.unit]}s`}}function B3e({filter:e}){var M,R;const[t,n]=N.useState(e.sql),[r,s]=N.useState(!1),[o,i]=N.useState({}),[a,l]=N.useState(e.title||""),[u,d]=N.useState(e.column),[f,h]=N.useState(e.searchMode||"auto"),[p,m]=N.useState(((M=e.defaultValues)==null?void 0:M.map(O=>String(O)))||[]),[g,b]=N.useState(e.defaultDateFilter);ee(O=>O.selectedSheetId);const{updateFilter:x}=Yt(),{tokenProps:y}=qe(),v=N.useMemo(()=>Ks(e.dataType)==="date",[e.dataType]),w=((R=y==null?void 0:y.params)==null?void 0:R.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone,S=N.useMemo(()=>{if(!g)return;const[O,T]=J6(g,w);return{from:O,to:T}},[g,w]),{data:C}=dR(e);function j(){const O=a.trim(),T=u.trim(),I={sql:t,...o},F=T||e.column;T&&T!==e.column&&(I.column=F),I.title=O||F,Vo(e.dataType)&&(I.searchMode=f),I.defaultValues=p.length>0?p.map(B=>{const $=Number(B);return!isNaN($)&&Vo(e.dataType)?$:B}):void 0,v&&(I.defaultDateFilter=g);const z={...e,...I};x(z),i({}),s(!1)}N.useEffect(()=>{var O;r&&(i({}),n(e.sql),l(e.title===e.column?"":e.title||""),d(e.column),h(e.searchMode||"auto"),m(((O=e.defaultValues)==null?void 0:O.map(T=>String(T)))||[]),b(e.defaultDateFilter))},[r,e.sql,e.title,e.column,e.searchMode,e.defaultValues,e.defaultDateFilter]);function D(O){const T={...e,type:O};x(T)}function k(O){const T={...e,uiType:O};x(T)}function _(O){const T={...e,dateSelectionMode:O};x(T)}return c.jsxs(Ns,{open:r,onOpenChange:s,children:[c.jsx(js,{children:c.jsx(Ku,{className:"invisible h-3 w-3 cursor-pointer text-muted-foreground hover:text-foreground group-hover:visible"})}),c.jsx(ks,{onMouseDown:O=>O.stopPropagation(),onDoubleClick:O=>O.stopPropagation(),className:"z-50 m-2 h-[600px] w-[500px]",children:c.jsxs("div",{className:"flex h-full flex-col",children:[c.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[c.jsx("h4",{className:"font-medium leading-none",title:e.column,children:e.column.split(".").pop()}),c.jsx(Fe,{variant:"secondary",className:"flex-shrink-0 text-xs font-normal",children:e.dataType})]}),c.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:"Customize filter settings and scope"}),c.jsxs(cs,{defaultValue:"scope",className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:[c.jsxs(Wr,{className:"grid w-full flex-shrink-0 grid-cols-2",children:[c.jsx(Ht,{value:"scope",children:"Scope"}),c.jsx(Ht,{value:"advanced",children:"Configuration"})]}),c.jsx(Gn,{value:"scope",className:"mt-4 flex-1 overflow-y-auto",children:c.jsx(L3e,{filter:{...e,...o},onUpdate:O=>{i(T=>({...T,...O}))}})}),c.jsxs(Gn,{value:"advanced",className:"mt-4 flex-1 space-y-5 overflow-y-auto",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Custom Title (optional)"}),c.jsx(Yn,{children:c.jsxs(bn,{delayDuration:0,children:[c.jsx(xn,{asChild:!0,children:c.jsx(xr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),c.jsx(Cn,{side:"right",className:"max-w-xs",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("p",{className:"text-xs",children:"Leave empty to use the column name. Provide a custom title to override it."}),c.jsxs("div",{className:"space-y-1 border-t pt-2",children:[c.jsx("p",{className:"text-xs font-medium",children:"Filter ID"}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("p",{className:"break-all font-mono text-xs text-muted-foreground",children:e.id}),c.jsx(Gh,{text:e.id})]})]})]})})]})})]}),c.jsx(Bn,{value:a,onChange:O=>l(O.target.value),placeholder:e.column,className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-1",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Column Name"}),c.jsx(Bn,{value:u,onChange:O=>d(O.target.value),placeholder:"Enter column name",className:"h-8 font-mono text-xs"})]}),v?c.jsxs("div",{className:"space-y-1",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Date Picker Type"}),c.jsxs(rt,{value:e.dateSelectionMode||"range",onValueChange:O=>_(O),children:[c.jsx(Je,{className:"h-8",children:c.jsx(lt,{})}),c.jsxs(et,{children:[c.jsx(pe,{value:"range",children:"Date Range Picker"}),c.jsx(pe,{value:"months",children:"Month Picker"})]})]})]}):c.jsxs("div",{className:"space-y-1",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Selection Type"}),c.jsxs(rt,{value:e.type||"multiple",onValueChange:D,children:[c.jsx(Je,{className:"h-8",children:c.jsx(lt,{})}),c.jsxs(et,{children:[c.jsx(pe,{value:"multiple",children:"Multiple"}),c.jsx(pe,{value:"single",children:"Single"})]})]})]}),!v&&e.type==="single"&&c.jsxs("div",{className:"space-y-1",children:[c.jsx(ce,{className:"text-sm font-medium",children:"UI Component"}),c.jsxs(rt,{value:e.uiType||"dropdown",onValueChange:k,children:[c.jsx(Je,{className:"h-8",children:c.jsx(lt,{})}),c.jsxs(et,{children:[c.jsx(pe,{value:"dropdown",children:"Dropdown"}),c.jsx(pe,{value:"radio",children:"Radio"}),c.jsx(pe,{value:"tabs",children:"Tabs"})]})]})]}),Vo(e.dataType)&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Search Mode"}),c.jsx(Yn,{children:c.jsxs(bn,{delayDuration:0,children:[c.jsx(xn,{asChild:!0,children:c.jsx(xr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),c.jsx(Cn,{side:"right",className:"max-w-xs",children:c.jsxs("div",{className:"space-y-2 text-xs",children:[c.jsxs("p",{children:[c.jsx("strong",{children:"Text Search:"}),' Treats numbers as text (e.g., ZIP codes, IDs). Search for "90210".']}),c.jsxs("p",{children:[c.jsx("strong",{children:"Numeric Operators:"})," Supports comparison operators (e.g., >100, <=50, =100) for quantities, prices."]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Auto-detect:"})," Tries numeric first, falls back to text search."]})]})})]})})]}),c.jsxs(rt,{value:f,onValueChange:O=>h(O),children:[c.jsx(Je,{className:"h-8",children:c.jsx(lt,{})}),c.jsxs(et,{children:[c.jsx(pe,{value:"text",children:"Text Search"}),c.jsx(pe,{value:"numeric",children:"Numeric Operators"}),c.jsx(pe,{value:"auto",children:"Auto-detect"})]})]})]}),v?c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Default Date Filter (optional)"}),c.jsx(Yn,{children:c.jsxs(bn,{delayDuration:0,children:[c.jsx(xn,{asChild:!0,children:c.jsx(xr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),c.jsx(Cn,{side:"right",className:"max-w-xs",children:c.jsx("p",{className:"text-xs",children:"Set a relative date filter that will be automatically applied when the dashboard first loads. The dates will recalculate on each dashboard load and scheduled report execution."})})]})})]}),e.dateSelectionMode==="months"?c.jsxs(rt,{value:g?JSON.stringify(g):"__none__",onValueChange:O=>{if(O==="__none__"){b(void 0);return}try{const T=JSON.parse(O);b(T)}catch(T){console.error("Failed to parse relative date filter",T)}},children:[c.jsx(Je,{className:"h-8",children:c.jsx(lt,{placeholder:"Select default month range..."})}),c.jsxs(et,{children:[c.jsx(pe,{value:"__none__",children:"None"}),c.jsx(pe,{value:JSON.stringify({mode:"this",unit:"month"}),children:"This month"}),c.jsx(pe,{value:JSON.stringify({mode:"previous",unit:"month"}),children:"Last month"})]})]}):c.jsx(uR,{value:S,onRelativeSelect:(O,T)=>{b(T)},showRelativeTab:!0,hideCalendar:!0,timezone:w,placeholder:"Select default date range...",buttonClassName:"h-8"}),g&&c.jsx("div",{className:"flex items-center gap-2",children:c.jsxs(Fe,{variant:"secondary",className:"gap-1.5 text-xs",children:[z3e(g),c.jsx(vt,{className:"h-3 w-3 cursor-pointer hover:text-destructive",onClick:()=>b(void 0)})]})})]}):c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Default Values (optional)"}),c.jsx(Yn,{children:c.jsxs(bn,{delayDuration:0,children:[c.jsx(xn,{asChild:!0,children:c.jsx(xr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),c.jsx(Cn,{side:"right",className:"max-w-xs",children:c.jsx("p",{className:"text-xs",children:"Select values that will be automatically applied when the dashboard first loads. Works like a filter selection."})})]})})]}),C!=null&&C.records&&C.records.length>0?c.jsxs(rt,{value:"",onValueChange:O=>{O&&!p.includes(O)&&m([...p,O])},children:[c.jsx(Je,{className:"h-8",children:c.jsx(lt,{placeholder:"Select values to add..."})}),c.jsxs(et,{children:[C.records.filter(O=>{var F;const T=(F=e.column.split(".").pop())==null?void 0:F.replace(/"/g,""),I=T?O[T]:O.value;return I!=null&&!p.includes(String(I))}).map(O=>{var F;const T=(F=e.column.split(".").pop())==null?void 0:F.replace(/"/g,""),I=T?O[T]:O.value;return c.jsx(pe,{value:String(I),children:String(I)},String(I))}),C.records.every(O=>{var F;const T=(F=e.column.split(".").pop())==null?void 0:F.replace(/"/g,""),I=T?O[T]:O.value;return I==null||p.includes(String(I))})&&c.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"All values selected"})]})]}):c.jsx("div",{className:"flex h-8 items-center rounded-md border bg-muted px-2 text-xs text-muted-foreground",children:"Loading filter options..."}),p.length>0&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsxs("div",{className:"text-xs font-medium text-muted-foreground",children:["Selected (",p.length,"):"]}),c.jsx("div",{className:"flex flex-wrap gap-1.5",children:p.map(O=>c.jsxs(Fe,{variant:"secondary",className:"gap-1.5 text-xs",children:[String(O),c.jsx(vt,{className:"h-3 w-3 cursor-pointer hover:text-destructive",onClick:()=>{m(T=>T.filter(I=>I!==O))}})]},O))})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"SQL"}),c.jsx(Yn,{children:c.jsxs(bn,{delayDuration:0,children:[c.jsx(xn,{asChild:!0,children:c.jsx(xr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),c.jsx(Cn,{side:"right",className:"max-w-xs",children:c.jsx("p",{className:"text-xs",children:"This SQL will be used to fetch the filter values"})})]})})]}),c.jsx(qd,{onKeyDown:O=>{O.stopPropagation()},value:t,onChange:O=>n(O.target.value),className:`h-32 w-full resize-none break-all font-mono text-xs ${Wf}`,placeholder:"SELECT column FROM table..."})]}),c.jsx("div",{className:"border-t pt-2"})]})]}),c.jsx("div",{className:"mt-3 flex justify-end gap-2 border-t pt-3",children:c.jsxs(oe,{onClick:j,size:"sm",variant:"outline",children:[c.jsx(Rr,{className:"mr-2 size-4"}),"Accept"]})})]})})]})}function NR({filter:e}){var u;const t=ee(d=>d.isDashboardEditing),{preferences:n}=dp(),r=((u=n==null?void 0:n.cardDisplay)==null?void 0:u.mode)==="print",s=ee(d=>d.filterValues),o=s==null?void 0:s.some(d=>d.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:l}=Yt();return c.jsxs("div",{className:"group mb-1 flex h-5 items-center justify-between",children:[c.jsxs("div",{className:"flex grow items-center gap-2",children:[c.jsx(ce,{className:"my-1 inline-block text-sm",children:c.jsx(qo,{value:e.title||e.column,onSave:d=>l({...e,title:d}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),o&&!r&&c.jsx("button",{onClick:()=>i(e.id),className:"text-muted-foreground",children:c.jsx(pae,{className:"size-3.5"})}),t&&c.jsx("button",{className:"invisible group-hover:visible",onClick:()=>{l({...e,hide:!e.hide})},children:e.hide?c.jsx(bc,{className:"size-3.5 text-muted-foreground hover:text-foreground"}):c.jsx(t1,{className:"size-3.5 text-muted-foreground hover:text-foreground"})}),t&&c.jsx(B3e,{filter:e})]}),c.jsx("div",{className:"flex items-center gap-2",children:t&&c.jsx(vt,{onClick:()=>{i(e.id),a(e.id)},className:"size-3 cursor-pointer text-muted-foreground hover:cursor-pointer hover:text-foreground"})})]})}function dZ(){var g;const e=ee(b=>b.isDashboardEditing),t=ee(b=>b.selectedSheetId),n=ee(b=>b.dashboard),r=n==null?void 0:n.sheets,s=r==null?void 0:r.find(b=>b.id===t),o=_e(b=>b.card),i=_e(b=>b.selectedConnectionId),{addFrame:a,setSelectedFrameId:l,setIsVisualEditing:u}=Yt(),{setFrame:d,setCard:f,setActiveTabCardId:h}=ur();function p(){var v,w;const b=o==null?void 0:o.dataSource;if(b)return b;const x=(w=(v=n==null?void 0:n.aiContext)==null?void 0:v.selectedEntities)==null?void 0:w[0],y=x==null?void 0:x.type;if(x)return{connectionId:x.connectionId,connectionType:x.connectionType,type:y,selectedEntities:[x]}}function m(b){const x=(b==null?void 0:b.sheetId)||t,y=r==null?void 0:r.find(j=>j.id===x);if(!y){console.warn("Cannot add frame: No sheet found");return}if(!(!y.frames||y.frames.length===0)&&!e){console.warn("Cannot add frame: Dashboard not in editing mode");return}const w=p(),S={id:Mr(),title:"Title",type:"bar",connectionId:i||"",dataSource:w,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},sql:"",data:[]},C={id:Mr(),cards:[S],activeCardId:S.id};return x&&(a(x,C),l(C.id)),b!=null&&b.openVisualEditor&&(d(C),f(S),h(S.id),u(!0)),C}return{handleAddNewFrame:m,canAddFrame:e||!((g=s==null?void 0:s.frames)!=null&&g.length)}}function V3e({sheetId:e}){const{handleAddNewFrame:t}=dZ(),n=ee(s=>s.themeStyle),r=()=>{t({openVisualEditor:!0,sheetId:e})};return c.jsx("div",{className:"flex h-full min-h-[400px] items-start justify-start p-4",children:c.jsxs("button",{onClick:r,style:{borderRadius:n==null?void 0:n.cardBorderRadius},className:"group flex h-96 w-[600px] flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed border-muted-foreground/25 bg-background transition-all hover:border-muted-foreground/50 hover:bg-muted/50",children:[c.jsx("div",{className:"rounded-full bg-primary/10 p-3 transition-colors group-hover:bg-primary/20",children:c.jsx(jr,{className:"h-6 w-6 text-primary"})}),c.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Add new Visual"})]})})}function sb(e){const t=(e||"").toLowerCase(),n=Ks(t);return n==="string"?c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-blue-200/70 bg-gradient-to-r from-blue-100/60 to-blue-200/40 text-blue-900 shadow-sm dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100",children:c.jsx(Vj,{className:"h-3 w-3"})}):n==="number"?c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-green-200/70 bg-gradient-to-r from-green-100/60 to-green-200/40 text-green-900 shadow-sm dark:border-green-800/50 dark:from-green-950/40 dark:to-green-900/30 dark:text-green-100",children:c.jsx(E8,{className:"h-3 w-3"})}):n==="date"?c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-purple-200/70 bg-gradient-to-r from-purple-100/60 to-purple-200/40 text-purple-900 shadow-sm dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100",children:c.jsx(os,{className:"h-3 w-3"})}):n==="boolean"?c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-orange-200/70 bg-gradient-to-r from-orange-100/60 to-orange-200/40 text-orange-900 shadow-sm dark:border-orange-800/50 dark:from-orange-950/40 dark:to-orange-900/30 dark:text-orange-100",children:c.jsx(_ae,{className:"h-3 w-3"})}):n==="json"?c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-gray-200/70 bg-gradient-to-r from-gray-100/60 to-gray-200/40 text-gray-900 shadow-sm dark:border-gray-800/50 dark:from-gray-950/40 dark:to-gray-900/30 dark:text-gray-100",children:c.jsx(v8,{className:"h-3 w-3"})}):n==="geo"?c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-amber-200/70 bg-gradient-to-r from-amber-100/60 to-amber-200/40 text-amber-900 shadow-sm dark:border-amber-800/50 dark:from-amber-950/40 dark:to-amber-900/30 dark:text-amber-100",children:c.jsx(bae,{className:"h-3 w-3"})}):n==="calculated"?c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-indigo-200/70 bg-gradient-to-r from-indigo-100/60 to-indigo-200/40 text-indigo-900 shadow-sm dark:border-indigo-800/50 dark:from-indigo-950/40 dark:to-indigo-900/30 dark:text-indigo-100",children:c.jsx(q_,{className:"h-3 w-3"})}):c.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-gray-200/70 bg-gradient-to-r from-gray-100/60 to-gray-200/40 text-gray-900 shadow-sm dark:border-gray-800/50 dark:from-gray-950/40 dark:to-gray-900/30 dark:text-gray-100",children:c.jsx(Vj,{className:"h-3 w-3"})})}function H3e({value:e,onChange:t,metrics:n,attributes:r}){const s=(o,i)=>(e==null?void 0:e.field.id)===o.id&&(e==null?void 0:e.type)===i;return c.jsx(Yn,{children:c.jsxs("div",{className:"space-y-4",children:[n.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Value of Metric"}),c.jsxs(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsx(xr,{className:"h-3.5 w-3.5 text-muted-foreground"})}),c.jsxs(Cn,{className:"max-w-xs",children:[c.jsx("p",{className:"text-xs font-medium mb-1",children:"Captures intersection of all dimensions"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:`Example: Clicking a bar segment in "Sales by Country, stacked by State" captures both Country='USA' AND State='California'`})]})]})]}),c.jsx("div",{className:"space-y-1",children:n.map(o=>{const i=s(o,"metric");return c.jsxs(oe,{variant:i?"default":"outline",size:"sm",className:J("w-full justify-start font-normal",i&&"bg-primary text-primary-foreground"),onClick:()=>t({type:"metric",field:o}),children:[i&&c.jsx(Rr,{className:"mr-2 h-4 w-4"}),sb(o.dataType),c.jsx("span",{className:"ml-2",children:o.label})]},o.id)})})]}),r.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Value of Attribute"}),c.jsxs(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsx(xr,{className:"h-3.5 w-3.5 text-muted-foreground"})}),c.jsxs(Cn,{className:"max-w-xs",children:[c.jsx("p",{className:"text-xs font-medium mb-1",children:"Captures only this dimension"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:`Example: If configured on "State", clicking a bar in "Sales by Country, stacked by State" captures only State='California' (Country is not included)`})]})]})]}),c.jsx("div",{className:"space-y-1",children:r.map(o=>{const i=s(o,"attribute");return c.jsxs(oe,{variant:i?"default":"outline",size:"sm",className:J("w-full justify-start font-normal",i&&"bg-primary text-primary-foreground"),onClick:()=>t({type:"attribute",field:o}),children:[i&&c.jsx(Rr,{className:"mr-2 h-4 w-4"}),sb(o.dataType),c.jsx("span",{className:"ml-2",children:o.label})]},o.id)})})]}),n.length===0&&r.length===0&&c.jsx("div",{className:"text-sm text-muted-foreground text-center py-8",children:"No metrics or attributes available in this chart"})]})})}const u3=[{value:"clickFilter",label:"Cross filter",description:"Filter other cards on the dashboard"},{value:"drillDown",label:"Drill down",description:"Navigate through a hierarchy of dimensions"},{value:"dynamicDrill",label:"Explore dimensions",description:"Let users explore any dimension dynamically"},{value:"drillThrough",label:"Drill into dashboard",description:"Navigate to another dashboard"},{value:"drillToDetail",label:"Drill into insight",description:"Navigate to a saved insight"},{value:"drillToURL",label:"Drill into URL",description:"Navigate to a custom URL"}];function U3e({value:e,onChange:t}){const n=u3.find(r=>r.value===e);return c.jsx("div",{className:"space-y-2",children:c.jsxs(rt,{value:e,onValueChange:t,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:"Choose action...",children:n&&c.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const r=hw(n.value);return c.jsx(r,{className:"h-4 w-4"})})(),c.jsx("span",{children:n.label})]})})}),c.jsx(et,{children:u3.map(r=>{const s=hw(r.value);return c.jsx(pe,{value:r.value,children:c.jsxs("div",{className:"flex items-start gap-2 py-1",children:[c.jsx(s,{className:"mt-0.5 h-4 w-4 shrink-0"}),c.jsxs("div",{className:"flex flex-col",children:[c.jsx("span",{className:"font-medium",children:r.label}),c.jsx("span",{className:"text-xs text-muted-foreground",children:r.description})]})]})},r.value)})})]})})}function W3e({interaction:e,onUpdate:t}){const[n,r]=N.useState(""),s=h6(),o=()=>e.applyToCardIds!==void 0?"specific-cards":e.excludeCardIds!==void 0?"all-except-specific":"all-cards",i=d=>{const f={};switch(d){case"all-cards":f.applyToCardIds=void 0,f.excludeCardIds=void 0;break;case"specific-cards":f.applyToCardIds=[],f.excludeCardIds=void 0;break;case"all-except-specific":f.applyToCardIds=void 0,f.excludeCardIds=[];break}t({...e,...f})},a=(d,f)=>{if(f==="specific-cards"){const h=e.applyToCardIds||[],p=h.includes(d)?h.filter(m=>m!==d):[...h,d];t({...e,applyToCardIds:p})}else if(f==="all-except-specific"){const h=e.excludeCardIds||[],p=h.includes(d)?h.filter(m=>m!==d):[...h,d];t({...e,excludeCardIds:p})}},l=N.useMemo(()=>{if(!n.trim())return s;const d=n.toLowerCase();return s==null?void 0:s.filter(f=>{var h;return(h=f==null?void 0:f.title)==null?void 0:h.toLowerCase().includes(d)})},[n,s]),u=o();return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Filter scope"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose which cards should receive the filter"})]}),c.jsxs(ga,{value:u,onValueChange:d=>i(d),className:"space-y-2",children:[c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"all-cards",id:"all-cards",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"all-cards",className:"cursor-pointer text-sm font-medium",children:"All cards"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to all cards in the dashboard"})]})]}),c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"specific-cards",id:"specific-cards",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"specific-cards",className:"cursor-pointer text-sm font-medium",children:"Only specific cards"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to selected cards only"})]})]}),u==="specific-cards"&&c.jsxs("div",{className:"ml-7 space-y-2",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Cards to filter"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Select which cards should receive the filter"})]}),c.jsx(Nn,{placeholder:"Search cards...",value:n,onChange:d=>r(d.target.value),className:"mb-2"}),c.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:l&&l.length>0?l.map(d=>{const f=(e.applyToCardIds||[]).includes(d.id);return c.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[c.jsx(dn,{id:`card-${d.id}`,checked:f,onCheckedChange:()=>a(d.id,"specific-cards")}),c.jsxs("div",{className:"flex-1",children:[c.jsx(ce,{htmlFor:`card-${d.id}`,className:"cursor-pointer text-sm font-medium",children:d.title}),d.description&&c.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:d.description})]})]},d.id)}):c.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:n?`No cards found matching "${n}"`:"No cards available"})})]}),c.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[c.jsx(Nr,{value:"all-except-specific",id:"all-except-specific",className:"mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsx(ce,{htmlFor:"all-except-specific",className:"cursor-pointer text-sm font-medium",children:"All cards except specific ones"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to all cards, excluding selected ones"})]})]}),u==="all-except-specific"&&c.jsxs("div",{className:"ml-7 space-y-2",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Cards to exclude"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Select which cards should be excluded from filtering"})]}),c.jsx(Nn,{placeholder:"Search cards...",value:n,onChange:d=>r(d.target.value),className:"mb-2"}),c.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:l&&l.length>0?l.map(d=>{const f=(e.excludeCardIds||[]).includes(d.id);return c.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[c.jsx(dn,{id:`card-exclude-${d.id}`,checked:f,onCheckedChange:()=>a(d.id,"all-except-specific")}),c.jsxs("div",{className:"flex-1",children:[c.jsx(ce,{htmlFor:`card-exclude-${d.id}`,className:"cursor-pointer text-sm font-medium",children:d.title}),d.description&&c.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:d.description})]})]},d.id)}):c.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:n?`No cards found matching "${n}"`:"No cards available"})})]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Menu label"}),c.jsx(Nn,{value:e.label||"",onChange:d=>t({...e,label:d.target.value}),placeholder:tf(e.mode)}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}var jR="Collapsible",[q3e,fZ]=Er(jR),[Y3e,kR]=q3e(jR),hZ=E.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:s,disabled:o,onOpenChange:i,...a}=e,[l=!1,u]=$r({prop:r,defaultProp:s,onChange:i});return c.jsx(Y3e,{scope:n,disabled:o,contentId:nr(),open:l,onOpenToggle:E.useCallback(()=>u(d=>!d),[u]),children:c.jsx(Be.div,{"data-state":MR(l),"data-disabled":o?"":void 0,...a,ref:t})})});hZ.displayName=jR;var pZ="CollapsibleTrigger",ER=E.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,s=kR(pZ,n);return c.jsx(Be.button,{type:"button","aria-controls":s.contentId,"aria-expanded":s.open||!1,"data-state":MR(s.open),"data-disabled":s.disabled?"":void 0,disabled:s.disabled,...r,ref:t,onClick:Ee(e.onClick,s.onOpenToggle)})});ER.displayName=pZ;var _R="CollapsibleContent",DR=E.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=kR(_R,e.__scopeCollapsible);return c.jsx(sr,{present:n||s.open,children:({present:o})=>c.jsx(G3e,{...r,ref:t,present:o})})});DR.displayName=_R;var G3e=E.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:s,...o}=e,i=kR(_R,n),[a,l]=E.useState(r),u=E.useRef(null),d=ft(t,u),f=E.useRef(0),h=f.current,p=E.useRef(0),m=p.current,g=i.open||a,b=E.useRef(g),x=E.useRef(void 0);return E.useEffect(()=>{const y=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(y)},[]),Lr(()=>{const y=u.current;if(y){x.current=x.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const v=y.getBoundingClientRect();f.current=v.height,p.current=v.width,b.current||(y.style.transitionDuration=x.current.transitionDuration,y.style.animationName=x.current.animationName),l(r)}},[i.open,r]),c.jsx(Be.div,{"data-state":MR(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!g,...o,ref:d,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":m?`${m}px`:void 0,...e.style},children:g&&s})});function MR(e){return e?"open":"closed"}var mZ=hZ,K3e=ER,Z3e=DR;const Dc=mZ,Mc=ER,Tc=DR;function X3e(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return N.useMemo(()=>r=>{t.forEach(s=>s(r))},t)}const SS=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Up(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function TR(e){return"nodeType"in e}function Is(e){var t,n;return e?Up(e)?e:TR(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function RR(e){const{Document:t}=Is(e);return e instanceof t}function yx(e){return Up(e)?!1:e instanceof Is(e).HTMLElement}function gZ(e){return e instanceof Is(e).SVGElement}function Wp(e){return e?Up(e)?e.document:TR(e)?RR(e)?e:yx(e)||gZ(e)?e.ownerDocument:document:document:document}const Ei=SS?N.useLayoutEffect:N.useEffect;function CS(e){const t=N.useRef(e);return Ei(()=>{t.current=e}),N.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)},[])}function Q3e(){const e=N.useRef(null),t=N.useCallback((r,s)=>{e.current=setInterval(r,s)},[]),n=N.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function ob(e,t){t===void 0&&(t=[e]);const n=N.useRef(e);return Ei(()=>{n.current!==e&&(n.current=e)},t),n}function vx(e,t){const n=N.useRef();return N.useMemo(()=>{const r=e(n.current);return n.current=r,r},[...t])}function pw(e){const t=CS(e),n=N.useRef(null),r=N.useCallback(s=>{s!==n.current&&(t==null||t(s,n.current)),n.current=s},[]);return[n,r]}function mw(e){const t=N.useRef();return N.useEffect(()=>{t.current=e},[e]),t.current}let C2={};function wx(e,t){return N.useMemo(()=>{if(t)return t;const n=C2[e]==null?0:C2[e]+1;return C2[e]=n,e+"-"+n},[e,t])}function bZ(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];return r.reduce((o,i)=>{const a=Object.entries(i);for(const[l,u]of a){const d=o[l];d!=null&&(o[l]=d+e*u)}return o},{...t})}}const th=bZ(1),ib=bZ(-1);function J3e(e){return"clientX"in e&&"clientY"in e}function NS(e){if(!e)return!1;const{KeyboardEvent:t}=Is(e.target);return t&&e instanceof t}function e$e(e){if(!e)return!1;const{TouchEvent:t}=Is(e.target);return t&&e instanceof t}function gw(e){if(e$e(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return J3e(e)?{x:e.clientX,y:e.clientY}:null}const _i=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[_i.Translate.toString(e),_i.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+" "+n+"ms "+r}}}),d3="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function t$e(e){return e.matches(d3)?e:e.querySelector(d3)}const n$e={display:"none"};function r$e(e){let{id:t,value:n}=e;return N.createElement("div",{id:t,style:n$e},n)}function s$e(e){let{id:t,announcement:n,ariaLiveType:r="assertive"}=e;const s={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return N.createElement("div",{id:t,style:s,role:"status","aria-live":r,"aria-atomic":!0},n)}function o$e(){const[e,t]=N.useState("");return{announce:N.useCallback(r=>{r!=null&&t(r)},[]),announcement:e}}const xZ=N.createContext(null);function i$e(e){const t=N.useContext(xZ);N.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function a$e(){const[e]=N.useState(()=>new Set),t=N.useCallback(r=>(e.add(r),()=>e.delete(r)),[e]);return[N.useCallback(r=>{let{type:s,event:o}=r;e.forEach(i=>{var a;return(a=i[s])==null?void 0:a.call(i,o)})},[e]),t]}const l$e={draggable:`
977
977
  To pick up a draggable item, press the space bar.
978
978
  While dragging, use the arrow keys to move the item.
979
979
  Press space again to drop the item in its new position, or press escape to cancel.
@@ -1063,7 +1063,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1063
1063
 
1064
1064
  `)},flush(e){e.enqueue(`data: [DONE]
1065
1065
 
1066
- `)}})}});var gXe=cZe(()=>VJ(Ar([Wn({type:ut("text-start"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("text-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Wn({type:ut("text-end"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("error"),errorText:$e()}),Wn({type:ut("tool-input-start"),toolCallId:$e(),toolName:$e(),providerExecuted:Sr().optional(),dynamic:Sr().optional()}),Wn({type:ut("tool-input-delta"),toolCallId:$e(),inputTextDelta:$e()}),Wn({type:ut("tool-input-available"),toolCallId:$e(),toolName:$e(),input:co(),providerExecuted:Sr().optional(),providerMetadata:ir.optional(),dynamic:Sr().optional()}),Wn({type:ut("tool-input-error"),toolCallId:$e(),toolName:$e(),input:co(),providerExecuted:Sr().optional(),providerMetadata:ir.optional(),dynamic:Sr().optional(),errorText:$e()}),Wn({type:ut("tool-output-available"),toolCallId:$e(),output:co(),providerExecuted:Sr().optional(),dynamic:Sr().optional(),preliminary:Sr().optional()}),Wn({type:ut("tool-output-error"),toolCallId:$e(),errorText:$e(),providerExecuted:Sr().optional(),dynamic:Sr().optional()}),Wn({type:ut("reasoning-start"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-end"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("source-url"),sourceId:$e(),url:$e(),title:$e().optional(),providerMetadata:ir.optional()}),Wn({type:ut("source-document"),sourceId:$e(),mediaType:$e(),title:$e(),filename:$e().optional(),providerMetadata:ir.optional()}),Wn({type:ut("file"),url:$e(),mediaType:$e(),providerMetadata:ir.optional()}),Wn({type:FJ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:$e().optional(),data:co(),transient:Sr().optional()}),Wn({type:ut("start-step")}),Wn({type:ut("finish-step")}),Wn({type:ut("start"),messageId:$e().optional(),messageMetadata:co().optional()}),Wn({type:ut("finish"),messageMetadata:co().optional()}),Wn({type:ut("abort")}),Wn({type:ut("message-metadata"),messageMetadata:co()})])));function bXe(e){return e.type.startsWith("data-")}function ZJ(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]=ZJ(o,s):n[r]=s}return n}function xXe(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 XJ(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Aw({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Aw({text:xXe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Vy(e){return e.type.startsWith("tool-")}function yXe(e){return e.type==="dynamic-tool"}function a_(e){return Vy(e)||yXe(e)}function bL(e){return e.type.split("-").slice(1).join("-")}function vXe({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 wXe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,p,m;function g(w){const C=u.message.parts.filter(Vy).find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function b(w){const C=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function x(w){var S;const C=u.message.parts.find(k=>Vy(k)&&k.toolCallId===w.toolCallId),j=w,D=C;C!=null?(C.state=w.state,D.input=j.input,D.output=j.output,D.errorText=j.errorText,D.rawInput=j.rawInput,D.preliminary=j.preliminary,D.providerExecuted=(S=j.providerExecuted)!=null?S:C.providerExecuted,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function y(w){var S;const C=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===w.toolCallId),j=w,D=C;C!=null?(C.state=w.state,D.toolName=w.toolName,D.input=j.input,D.output=j.output,D.errorText=j.errorText,D.rawInput=(S=j.rawInput)!=null?S:D.rawInput,D.preliminary=j.preliminary,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,errorText:j.errorText,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}async function v(w){if(w!=null){const S=u.message.metadata!=null?ZJ(u.message.metadata,w):w;t!=null&&await fL({value:S,schema:t}),u.message.metadata=S}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,w.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const w=u.message.parts.filter(Vy);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:S}=await XJ(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:bL(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:bL(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(bXe(a)){(n==null?void 0:n[a.type])!=null&&await fL({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const S=w.id!=null?u.message.parts.find(C=>w.type===C.type&&w.id===C.id):void 0;S!=null?S.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function SXe({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()}}Ax({prefix:"aitxt",size:24});Ax({prefix:"aiobj",size:24});var CXe=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()})}};Ax({prefix:"aiobj",size:24});var NXe={};iXe(NXe,{object:()=>kXe,text:()=>jXe});var jXe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),kXe=({schema:e})=>{const t=sXe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await XJ(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 Aw({text:n});if(!s.success)throw new mL({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 NI({value:s.value,schema:t});if(!o.success)throw new mL({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}}},EXe=Bf({name:$e(),version:$e()}),kI=Bf({_meta:mr(Wt({}).loose())}),yb=kI,_Xe=Wt({method:$e(),params:mr(kI)}),DXe=Bf({experimental:mr(Wt({}).loose()),logging:mr(Wt({}).loose()),prompts:mr(Bf({listChanged:mr(Sr())})),resources:mr(Bf({subscribe:mr(Sr()),listChanged:mr(Sr())})),tools:mr(Bf({listChanged:mr(Sr())}))});yb.extend({protocolVersion:$e(),capabilities:DXe,serverInfo:EXe,instructions:mr($e())});var MXe=yb.extend({nextCursor:mr($e())}),TXe=Wt({name:$e(),description:mr($e()),inputSchema:Wt({type:ut("object"),properties:mr(Wt({}).loose())}).loose()}).loose();MXe.extend({tools:nu(TXe)});var RXe=Wt({type:ut("text"),text:$e()}).loose(),IXe=Wt({type:ut("image"),data:TJ(),mimeType:$e()}).loose(),QJ=Wt({uri:$e(),mimeType:mr($e())}).loose(),AXe=QJ.extend({text:$e()}),PXe=QJ.extend({blob:TJ()}),OXe=Wt({type:ut("resource"),resource:Ar([AXe,PXe])}).loose();yb.extend({content:nu(Ar([RXe,IXe,OXe])),isError:Sr().default(!1).optional()}).or(yb.extend({toolResult:co()}));var eC="2.0",FXe=Wt({jsonrpc:ut(eC),id:Ar([$e(),bb().int()])}).merge(_Xe).strict(),$Xe=Wt({jsonrpc:ut(eC),id:Ar([$e(),bb().int()]),result:yb}).strict(),LXe=Wt({jsonrpc:ut(eC),id:Ar([$e(),bb().int()]),error:Wt({code:bb().int(),message:$e(),data:mr(co())})}).strict(),zXe=Wt({jsonrpc:ut(eC)}).merge(Wt({method:$e(),params:mr(kI)})).strict();Ar([FXe,zXe,$Xe,LXe]);async function BXe(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 VXe=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 Nf(this.body),l=await Nf(this.headers),u=await Nf(this.credentials),d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...l,...t.headers},credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(r=d==null?void 0:d.api)!=null?r:this.api,h=(d==null?void 0:d.headers)!==void 0?d.headers:{...l,...t.headers},p=(d==null?void 0:d.body)!==void 0?d.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},m=(s=d==null?void 0:d.credentials)!=null?s:u,b=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:dL({"Content-Type":"application/json",...h},`ai-sdk/${gL}`,uL()),body:JSON.stringify(p),credentials:m,signal:e});if(!b.ok)throw new Error((i=await b.text())!=null?i:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await Nf(this.body),a=await Nf(this.headers),l=await Nf(this.credentials),u=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:{...a,...e.headers},credentials:l,requestMetadata:e.metadata})),d=(n=u==null?void 0:u.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=(u==null?void 0:u.headers)!==void 0?u.headers:{...a,...e.headers},h=(r=u==null?void 0:u.credentials)!=null?r:l,m=await((s=this.fetch)!=null?s:globalThis.fetch)(d,{method:"GET",headers:dL(f,`ai-sdk/${gL}`,uL()),credentials:h});if(m.status===204)return null;if(!m.ok)throw new Error((o=await m.text())!=null?o:"Failed to fetch the chat response.");if(!m.body)throw new Error("The response body is empty.");return this.processResponseStream(m.body)}},EI=class extends VXe{constructor(e={}){super(e)}processResponseStream(e){return fZe({stream:e,schema:gXe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},HXe=class{constructor({generateId:e=eZe,id:t=e(),transport:n=new EI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new CXe,this.sendMessage=async(f,h)=>{var p,m,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await BXe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(m=x.role)!=null?m:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const p=f==null?this.state.messages.length-1:this.state.messages.findIndex(m=>m.id===f);if(p===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({state:f="output-available",tool:h,toolCallId:p,output:m,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>a_(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>a_(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=l,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let u=!1,d=!1,f=!1;try{const h={state:vXe({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};h.abortController.signal.addEventListener("abort",()=>{u=!0}),this.activeResponse=h;let p;if(e==="resume-stream"){const g=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(g==null){this.setStatus({status:"ready"});return}p=g}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:h.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const m=g=>this.jobExecutor.run(()=>g({state:h.state,write:()=>{var b;this.setStatus({status:"streaming"}),h.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,h.state.message):this.state.pushMessage(h.state.message)}}));await SXe({stream:wXe({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:m,onError:g=>{throw g}}),onError:g=>{throw g}}),this.setStatus({status:"ready"})}catch(h){if(u||h.name==="AbortError")return u=!0,this.setStatus({status:"ready"}),null;f=!0,h instanceof TypeError&&(h.message.toLowerCase().includes("fetch")||h.message.toLowerCase().includes("network"))&&(d=!0),this.onError&&h instanceof Error&&this.onError(h),this.setStatus({status:"error",error:h})}finally{try{(o=this.onFinish)==null||o.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:u,isDisconnect:d,isError:f})}catch(h){console.error(h)}this.activeResponse=void 0}(i=this.sendAutomaticallyWhen)!=null&&i.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(a=this.lastMessage)==null?void 0:a.id,metadata:t,headers:n,body:r})}};function UXe({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(a_);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function WXe(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 qXe=WXe;const YXe=$c(qXe);var JJ=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Tn=(e,t,n)=>(JJ(e,t,"read from private field"),n?n.call(e):t.get(e)),Bi=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Ol=(e,t,n,r)=>(JJ(e,t,"write to private field"),t.set(e,n),n);function GXe(e,t){return t!=null?YXe(e,t):e}var jo,Hy,Uy,Vm,Hm,Um,Mf,l_,c_,KXe=class{constructor(e=[]){Bi(this,jo,void 0),Bi(this,Hy,"ready"),Bi(this,Uy,void 0),Bi(this,Vm,new Set),Bi(this,Hm,new Set),Bi(this,Um,new Set),this.pushMessage=t=>{Ol(this,jo,Tn(this,jo).concat(t)),Tn(this,Mf).call(this)},this.popMessage=()=>{Ol(this,jo,Tn(this,jo).slice(0,-1)),Tn(this,Mf).call(this)},this.replaceMessage=(t,n)=>{Ol(this,jo,[...Tn(this,jo).slice(0,t),this.snapshot(n),...Tn(this,jo).slice(t+1)]),Tn(this,Mf).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?GXe(t,n):t;return Tn(this,Vm).add(r),()=>{Tn(this,Vm).delete(r)}},this["~registerStatusCallback"]=t=>(Tn(this,Hm).add(t),()=>{Tn(this,Hm).delete(t)}),this["~registerErrorCallback"]=t=>(Tn(this,Um).add(t),()=>{Tn(this,Um).delete(t)}),Bi(this,Mf,()=>{Tn(this,Vm).forEach(t=>t())}),Bi(this,l_,()=>{Tn(this,Hm).forEach(t=>t())}),Bi(this,c_,()=>{Tn(this,Um).forEach(t=>t())}),Ol(this,jo,e)}get status(){return Tn(this,Hy)}set status(e){Ol(this,Hy,e),Tn(this,l_).call(this)}get error(){return Tn(this,Uy)}set error(e){Ol(this,Uy,e),Tn(this,c_).call(this)}get messages(){return Tn(this,jo)}set messages(e){Ol(this,jo,[...e]),Tn(this,Mf).call(this)}};jo=new WeakMap;Hy=new WeakMap;Uy=new WeakMap;Vm=new WeakMap;Hm=new WeakMap;Um=new WeakMap;Mf=new WeakMap;l_=new WeakMap;c_=new WeakMap;var Tf,xL=class extends HXe{constructor({messages:e,...t}){const n=new KXe(e);super({...t,state:n}),Bi(this,Tf,void 0),this["~registerMessagesCallback"]=(r,s)=>Tn(this,Tf)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Tn(this,Tf)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Tn(this,Tf)["~registerErrorCallback"](r),Ol(this,Tf,n)}};Tf=new WeakMap;function eee({experimental_throttle:e,resume:t=!1,...n}={}){const r=N.useRef("chat"in n?n.chat:new xL(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new xL(n));const o="id"in n?n.id:null,i=N.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=N.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=N.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=N.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=N.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return N.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolResult}}function ZXe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function XXe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function QXe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function JXe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function tee(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:JXe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function nee(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 eQe(){var b;const{authToken:e,tokenProps:t}=qe(),n=ee(x=>x.dashboard.aiScopeTables),r=(b=Zw().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=eee({transport:new EI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Pi.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:DW(x)}})}),onToolCall:p,sendAutomaticallyWhen:UXe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function p({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:tee(n||[])}}),x.toolName==="getDashboardContext"){const y=ee.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const m=!["ready","error"].includes(l),g=nee(d);return{sendMessage:s,regenerate:a,isLoading:m,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function ree(){var u;const{authToken:e,tokenProps:t}=qe(),n=(u=Zw().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=un({queryKey:["assistant-profile",n],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function see({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(y8,{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 Pw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(rD,{className:r});case"view":return c.jsx(bc,{className:r});case"materialized view":return c.jsx(uae,{className:r});case"model":return c.jsx(r1,{className:r});case"file":return c.jsx(Ni,{className:r});case"dataset":return c.jsx(sl,{className:r});case"upload":return c.jsx(aD,{className:r});case"url":return c.jsx(D8,{className:r});default:return c.jsx(n1,{className:r})}}const oee=E.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(xa,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(ds.Input,{ref:n,className:J("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));oee.displayName=ds.Input.displayName;const hy=e=>e.label||(e==null?void 0:e.name),yL=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function tQe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=qe(),f=(d==null?void 0:d.type)==="dashboard",[h,p]=N.useState(""),[m,g]=N.useState(""),b=s.filter(C=>{if(!h)return!0;const j=hy(C).toLowerCase(),D=yL(C).toLowerCase(),k=h.toLowerCase();return j.includes(k)||D.includes(k)});N.useEffect(()=>{e||(p(""),g(""))},[e]),N.useEffect(()=>{b.length>0&&!m&&g(hy(b[0]))},[b,m]);const x=()=>{if(!m)return;const C=b.find(j=>hy(j)===m);C&&(o.some(D=>"id"in C&&"id"in D?C.id===D.id:C.name===D.name&&C.connectionId===D.connectionId)||t(C),i(C),r())},y=C=>{(C.key==="Tab"||C.key==="Enter")&&(C.preventDefault(),x())};if(!e)return null;const v=C=>o.some(j=>"id"in C&&"id"in j?C.id===j.id:C.name===j.name&&C.connectionId===j.connectionId),w=o.length===s.length,S=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(IS,{shouldFilter:!1,value:m,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(oee,{placeholder:"Search entities...",value:h,onValueChange:p,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(jr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),a==null||a()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),S&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),l==null||l()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(vt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(AS,{className:"min-h-60",children:[c.jsx(PS,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(jr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(OS,{children:b.map((C,j)=>{const D=v(C),k="id"in C?C.id:`${C.connectionId}-${C.name}`,_=hy(C);return c.jsxs(FS,{value:_,onSelect:()=>{D?n==null||n(C):t(C)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:J("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:Pw(C.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:_}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:yL(C)})]}),D&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx(Rr,{className:"h-3 w-3 text-background"})})]},k)})})]})]})})}const u_=e=>e.name||e.name,nQe=e=>{const t=u_(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 rQe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=N.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(Yn,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[Pw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:u_(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(Cn,{side:"top",className:"max-w-xs",children:nQe(d)})]},h)}),u&&c.jsxs(bn,{open:s,onOpenChange:o,children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(dae,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(Cn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:Pw(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:u_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(vt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function iee(e){return e.type==="dataset"&&e.label||e.name}function sQe(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(ce,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(Fe,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),iee(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(vt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function iQe(e){const{tokenProps:t}=qe(),n=ee(l=>l.authToken)||e;_e(l=>l.selectedConnectionId),_e(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=un({queryKey:["semantic-domains"],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function aQe(e,t){const{tokenProps:n}=qe(),r=ee(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=un({queryKey:["datasets",e],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function lQe(e){var g,b;const{tokenProps:t}=qe(),n=ee(x=>x.authToken)||e,{connections:r}=Ai(e),s=_e(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:p}=un({queryKey:["databases",s],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),m=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:m||[],refetch:p,label:l}}function cQe(e){var g;const{tokenProps:t}=qe(),n=ee(b=>b.authToken)||e,{connections:r}=Ai(e),s=_e(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=_e(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:p}=un({queryKey:["schemas",s,o],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),m=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:m||[],refetch:p,label:l}}function aee(e){const{tokenProps:t}=qe(),n=ee(h=>h.authToken)||e,{connections:r}=Ai(e),s=_e(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=un({queryKey:["dataModels",s],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function uQe(){var S,C,j;const e=_e(D=>D.card.dataSource);_e(D=>D.actions.updateDirectSource);const t=_e(D=>D.actions.updateDataSource),[n,r]=N.useState(""),{selectedConnection:s,error:o}=Ai(),{databases:i,isPending:a,error:l,label:u}=lQe(),{schemas:d,isPending:f,error:h,label:p}=cQe(),{error:m}=aee(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=p==null?void 0:p.toLowerCase(),v=D=>{e&&t({...e,dbSelection:{database:D,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=D=>{var _;if(!((_=e==null?void 0:e.dbSelection)!=null&&_.database))return;const k=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...k,schema:D},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||m)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[p,": ",h.message]}),m&&c.jsxs("li",{children:["Data Models: ",m.message]})]})]})}),c.jsx(oe,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:u}),c.jsxs(rt,{value:((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)||"",onValueChange:v,disabled:a,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(et,{children:i.map(D=>c.jsx(pe,{className:"hover:bg-muted",value:D.id,children:D.name},D.id))})]})]}),((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:p}),c.jsxs(rt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(et,{children:d.map(D=>c.jsx(pe,{className:"hover:bg-muted",value:D.id,children:D.name},D.id))})]})]})]})]})}function dQe(){const e=_e(l=>l.card.dataSource),t=_e(l=>l.actions.updateDataSource),[n,r]=N.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(aD,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Ni,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},l.id))})]})]})}function fQe(){const e=_e(f=>f.card.dataSource),t=_e(f=>f.actions.updateDataSource),[n,r]=N.useState(""),[s,o]=N.useState(""),[i,a]=N.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(p=>p.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(Nn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(Nn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[c.jsx("option",{value:"api",children:"API Endpoint"}),c.jsx("option",{value:"csv",children:"CSV File"}),c.jsx("option",{value:"json",children:"JSON File"})]})]}),c.jsxs(oe,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(jr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(n1,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},f.id))})]})]})}function hQe(e,t){var y,v;const{tokenProps:n}=qe(),r=ee(w=>w.authToken)||t,{connections:s}=Ai(t),o=_e(w=>{var S,C;return(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.connectionId}),i=_e(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.database}),a=_e(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:p,isLoading:m,error:g,refetch:b}=un({queryKey:[e,o,i,a],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(w=>{var S;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(S=w==null?void 0:w.table_type)==null?void 0:S.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:p,isLoading:m,error:g,entities:x||[],refetch:b,label:d}}function Ow({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(pd,{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 pQe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Ai(),[i,a]=N.useState(""),[l,u]=N.useState(""),[d,f]=N.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=ur(),{entities:m,isLoading:g,error:b}=hQe("table"),{dataModels:x,isPending:y,error:v}=aee(),w=_=>{const M=s.find(O=>O.id===_);if(!M)return;const R=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:_,connectionType:M.type,mode:R,dbSelection:{database:"",schema:"",entityType:"table"}}),p(_)},S=_=>{var T,I;const M=n||[],R=M.some(F=>F.name===_.name&&F.type===_.type);let O;if(R)O=M.filter(F=>!(F.name===_.name&&F.type===_.type));else{const F={connectionId:e.connectionId,connectionType:e.connectionType,type:_.type,dbObjectType:_.dbObjectType,database:((T=e.dbSelection)==null?void 0:T.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:_.name,dialect:_.dialect};O=[...M,F]}t==null||t(O)},C=_=>{const M=n||[],R=M.some(T=>T.type==="model"&&T.name===_.name);let O;R?O=M.filter(T=>!(T.type==="model"&&T.name===_.name)):O=[...M,_],t==null||t(O)},j=m.filter(_=>_.name.toLowerCase().includes(i.toLowerCase())),D=x.filter(_=>_.name.toLowerCase().includes(l.toLowerCase())),k=N.useCallback(()=>{if(!t)return;const _=n||[];let M=[..._];if(d==="tables"){const O=j.filter(T=>!_.some(I=>I.name===T.name&&I.type==="table")).map(T=>{var I,F;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:T.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((F=e.dbSelection)==null?void 0:F.schema)||"",name:T.name,dialect:T.dialect}});M=[..._,...O]}else if(d==="datamodels"){const R=D.filter(O=>!_.some(T=>T.name===O.name&&T.type==="model"));M=[..._,...R]}t(M)},[d,j,D,n,e,t]);return N.useEffect(()=>{r&&r(k)},[r,k]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(rt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(et,{children:s.map(_=>c.jsx(pe,{className:"hover:bg-muted",value:_.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(sl,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:_.name}),c.jsx(Fe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:_.type})]})},_.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(dQe,{}),e.connectionType==="url"&&c.jsx(fQe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(uQe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(cs,{defaultValue:"tables",value:d,onValueChange:_=>f(_),className:"w-full",children:[c.jsxs(Wr,{className:"grid w-full grid-cols-2",children:[c.jsxs(Ht,{value:"tables",children:["Tables & Views (",j.length,")"]}),c.jsxs(Ht,{value:"datamodels",children:["Data Models (",D.length,")"]})]}),c.jsxs(Gn,{value:"tables",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search tables and views...",value:i,onChange:_=>a(_.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(Ow,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(_=>{const M=n.some(R=>R.name===_.name&&R.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(_),children:[c.jsx(dn,{id:`table-${_.name}`,checked:M,onCheckedChange:()=>S(_),onClick:R=>R.stopPropagation(),disabled:g}),c.jsxs(ce,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[_.name,_.dbObjectType==="view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),_.dbObjectType==="materialized view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},_.name)})})]}),c.jsxs(Gn,{value:"datamodels",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search data models...",value:l,onChange:_=>u(_.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(Ow,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):D.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):D.map(_=>{const M=n.some(R=>R.name===_.name&&R.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(_),children:[c.jsx(dn,{id:`dataModel-${_.name}`,checked:M,onCheckedChange:()=>C(_),onClick:R=>R.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer",children:_.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:_.description})]})]},_.name)})})]})]})})})]})]})]})}function mQe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var S;const[l,u]=N.useState(""),d=N.useCallback(C=>{const j={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:C};t({...j})},[e,t]);N.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:p}=iQe(),m=o?f.filter(C=>s.includes(C.id)):f,{datasets:g,isPending:b,error:x}=aQe(e==null?void 0:e.semanticDomainId),y=C=>{const j=r||[],D=j.some(_=>_.id===C.id&&_.type==="dataset");let k;if(D)k=j.filter(_=>!(_.id===C.id&&_.type==="dataset"));else{const _={id:C.id,datasetType:C.type,name:C.name||C.table,label:C.label,domainId:C.domainId,description:C.description,database:C.database,schema:C.schema,type:"dataset",connectionId:C.connectionId,connectionType:C.connectionType,dialect:C.dialect,datamodelId:C.datamodelId,sql:C.sql};k=[...j,_]}n==null||n(k)},v=g.filter(C=>C.name.toLowerCase().includes(l.toLowerCase())),w=N.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const C=r||[],D=v.filter(_=>!C.some(M=>M.id===_.id&&M.type==="dataset")).map(_=>({id:_.id,datasetType:_.type,name:_.name||_.table,label:_.label,domainId:_.domainId,description:_.description,database:_.database,schema:_.schema,type:"dataset",connectionId:_.connectionId,connectionType:_.connectionType,dialect:_.dialect,datamodelId:_.datamodelId,sql:_.sql})),k=[...C,...D];n(k)},[v,r,e==null?void 0:e.semanticDomainId,n]);return N.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(rt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((S=m.find(C=>C.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:S.label)||"Select semantic domain"})}),c.jsx(et,{children:m.map(C=>c.jsx(pe,{className:"hover:bg-muted",value:C.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:C.label}),c.jsx("span",{className:"text-xs",children:C.description})]})},C.id))})]}),p&&c.jsx(Ow,{title:"Error loading semantic models",message:p.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search datasets...",value:l,onChange:C=>u(C.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(Ow,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(C=>{const j=r.some(D=>D.id===C.id&&D.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(C),children:[c.jsx(dn,{id:`dataset-${C.id}`,checked:j,onCheckedChange:()=>y(C),onClick:D=>D.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer font-medium",children:C.label||C.name}),c.jsx("span",{className:"text-xs text-gray-500",children:C.description})]})]},C.label||C.name)})})]})]})]})}function _I({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=qe(),{allowedSemanticDomains:i}=o,[a,l]=N.useState([]),{updateDataSource:u}=ur(),d=ee(M=>M.isVisualEditing),f=ee(M=>M.dashboard.aiContext),{setAiContext:h}=Yt(),p=N.useRef(null),[m,g]=N.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=N.useCallback(M=>{const R=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:R,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...R!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=N.useCallback(M=>{u({...n,...M})},[n,u]);N.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),N.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),N.useEffect(()=>{e?l(s||[]):(p.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const S=M=>{const R=a.filter(O=>!(O.name===M.name&&O.type===M.type));l(R)},C=()=>{l([])},j=N.useCallback(M=>{l(M)},[]),D=N.useCallback(()=>{p.current&&p.current()},[]),k=N.useCallback(M=>{p.current=M,g(!0)},[]);function _(){var M,R;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const O=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,T=(R=a==null?void 0:a[0])==null?void 0:R.connectionType;u({...n,connectionId:O,connectionType:T,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsx(Vr,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Hr,{className:"flex-shrink-0",children:[c.jsx(Ur,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(Rs,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(cs,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(Wr,{className:"grid w-full grid-cols-2",children:[c.jsx(Ht,{value:"database",children:"Direct Source"}),c.jsx(Ht,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(mQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:k}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(pQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:k})]})}),c.jsx(oQe,{selectedEntities:a,onDeselectEntity:S}),c.jsx(Ts,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(oe,{variant:"outline",onClick:D,disabled:!m,children:"Select All"}),c.jsx(oe,{variant:"outline",onClick:C,disabled:a.length===0,children:"Clear All"}),c.jsxs(oe,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(vt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(oe,{onClick:_,children:[c.jsx(Rr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function gQe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=N.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=$a-n;if(l.length>u){Le.error(`You can only attach ${$a} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=HQ(l);if(f.forEach(({file:h,error:p})=>{Le.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>mI(p)));e(h)}catch(h){console.error("Failed to process files:",h),Le.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>=$a}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=$a,title:n>=$a?`Maximum ${$a} files allowed`:"Attach files",children:c.jsx(Q_,{className:"h-4 w-4 text-muted-foreground"})})]})}function bQe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=N.useState(!1),a=N.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=N.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),p=f.clientX,m=f.clientY;(p<h.left||p>=h.right||m<h.top||m>=h.bottom)&&i(!1)},[]),u=N.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=N.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const p=$a-r;if(h.length>p){Le.error(`You can only attach ${$a} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=HQ(h);if(g.forEach(({file:b,error:x})=>{Le.error(`${b.name}: ${x}`)}),m.length>0)try{const b=await Promise.all(m.map(x=>mI(x)));t(b),Le.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),Le.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:J("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(aD,{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:[$a-r," slot(s) available"]})]})})]})}const DI=N.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=N.useState(!1),[h,p]=N.useState(!1),[m,g]=N.useState(!1),b=N.useRef(null),x=Ip();SNe(),wNe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:S}=H1(),{queueMessage:C}=Ap(),{addFileAttachment:j,removeFileAttachment:D,clearFileAttachments:k,getFileAttachments:_}=YM(),M=qM(l),R=_e(H=>H.card.dataSource),O=ee(H=>H.dashboard.aiContext),T=ee(H=>{var q;return(q=H.dashboard.aiContext)==null?void 0:q.selectedEntities});N.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=N.useCallback(()=>{const H=b.current;if(H){if(!e||e.length===0){H.style.height="10px";return}H.style.height="auto";const q=Math.min(Math.max(H.scrollHeight,10),200);H.style.height=`${q}px`}},[e]);N.useEffect(()=>{I()},[I]),N.useEffect(()=>{const H=setTimeout(()=>{I()},0);return()=>clearTimeout(H)},[I]);const F=()=>{const H=e.trim();!H&&M.length===0||(a!=="ready"?(C(l,H,M),t(""),k(l)):r({preventDefault:()=>{}}))},z=H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),F()),H.key==="@"&&(K(),f(!0))},B=N.useCallback(H=>{const q=TWe(H.nativeEvent);q.length>0&&(H.preventDefault(),q.forEach(async X=>{const Z=await mI(X);j(l,Z)}))},[j,l]),$=N.useCallback(H=>{H.forEach(q=>{j(l,q)})},[j,l]),P=N.useCallback(H=>{H.forEach(q=>{j(l,q)})},[j,l]),V=N.useCallback(H=>{D(l,H)},[D,l]),L=H=>{if(x.selectedEntities.some(X=>X.id&&X.id===H.id||X.name===H.name)){const X=x.selectedEntities.filter(Z=>!(Z.id&&Z.id===H.id||Z.name===H.name));y({selectedEntities:X})}else{const X=[...x.selectedEntities,H];y({selectedEntities:X})}},A=H=>{L(H)},W=H=>{var Z;if(!x.selectedEntities.some(G=>G.id&&G.id===H.id||G.name===H.name)){const G=[...x.selectedEntities,H];y({selectedEntities:G})}const X="label"in H?H.label:H.name;t(e+`@${X} `),f(!1),(Z=b.current)==null||Z.focus()},U=H=>{const q=x.selectedEntities.filter(G=>!(G.id&&G.id===H.id||G.name===H.name));y({selectedEntities:q});const Z=`@${"label"in H?H.label:H.name}`;e.includes(Z)&&t(e.replace(Z,"").trim())},Y=H=>{const q=new Set(H.map(G=>G.id||G.name)),X=x.selectedEntities.filter(G=>!q.has(G.id||G.name));y({selectedEntities:X});let Z=e;H.forEach(G=>{const ne=`@${"label"in G?G.label:G.name}`;Z=Z.replace(ne,"").trim()}),t(Z)},K=N.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})},[x.selectedEntities.length,O==null?void 0:O.selectedEntities,y]);return c.jsxs(bQe,{onFilesDropped:$,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(rQe,{entities:x.selectedEntities,availableEntities:T||[],onRemoveEntity:U,onRemoveEntities:Y}),M.length>0&&c.jsx(RWe,{files:M,onRemove:V,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:z,onPaste:B,onFocus:()=>{I(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(Ns,{open:d,onOpenChange:H=>{H&&K(),f(H)},children:[c.jsx(js,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(sae,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(ks,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:H=>H.preventDefault(),children:c.jsx(tQe,{isOpen:!0,onSelect:L,onDeselect:A,onClose:()=>{var H;f(!1),(H=b.current)==null||H.focus()},availableEntities:T||[],selectedEntities:x.selectedEntities,onTabComplete:W,onSelectAll:()=>{T&&y({selectedEntities:T})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),p(!0)}})})]}),c.jsx(gQe,{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:F,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(O8,{className:"size-4"})})]})]})]}),c.jsx(_I,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:p,dataSource:R||XS,dialogMode:"aiContext"})]})});DI.displayName="ChatInputWithContext";function lee({assistantType:e,className:t}){const n=MW(e),{removeFromQueue:r}=Ap();return n.length===0?null:c.jsxs("div",{className:J("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(dl,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>c.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(vt,{className:"h-3 w-3"})})]})},s.id))})]})}function cee({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=MW(e),{dequeueMessage:o}=Ap();N.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function uee(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=N.useRef(null),[a,l]=N.useState(!0),[u,d]=N.useState(!0),[f,h]=N.useState(!1),[p,m]=N.useState(0),g=N.useRef(0),b=N.useRef(!1),x=N.useRef(0),y=N.useRef(a),v=N.useRef(),w=N.useRef({key:null,count:0,length:0}),S=N.useCallback(()=>{const k=i.current;return k?k.scrollHeight-k.scrollTop-k.clientHeight:0},[]),C=N.useCallback((k={})=>{if(!i.current)return;const{force:M=!1,instant:R=!1}=k;if(!M&&!y.current||!a&&!M)return;const O=R||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!M&&!y.current){b.current=!1,v.current=void 0;return}const T=i.current;if(!T){b.current=!1,v.current=void 0;return}const I=T.scrollHeight;O==="smooth"&&"scrollTo"in T?T.scrollTo({top:I,behavior:O}):T.scrollTop=I,g.current=T.scrollTop,d(!0),l(!0),y.current=!0,h(!1),m(0),b.current=!1,v.current=void 0})},[r,a]),j=N.useCallback(()=>{const k=i.current;if(!k)return;const _=g.current,M=k.scrollTop,R=M-_;if(g.current=M,R<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const O=S()<=n;d(O),l(O),y.current=O,O&&(h(!1),m(0))},[S,n]),D=N.useCallback(()=>{m(0),h(!1)},[]);return N.useEffect(()=>{y.current=a},[a]),N.useEffect(()=>{const k=i.current;if(!k||!e||e.length===0){h(!1),m(0),w.current={key:null,count:0,length:0},g.current=k?k.scrollTop:0,x.current=k?k.scrollHeight:0;return}g.current=k.scrollTop,x.current=k.scrollHeight;const _=w.current,M=e[e.length-1],R=(M==null?void 0:M.id)??(M==null?void 0:M.messageId)??(M==null?void 0:M.createdAt)??(M==null?void 0:M.timestamp)??e.length,O=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce(($,P)=>P?typeof P=="string"?$+P.length:typeof P.text=="string"?$+P.text.length:typeof P.content=="string"?$+P.content.length:typeof P.value=="string"?$+P.value.length:$:$,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,T=e.length>_.count,I=R!==_.key,F=O>_.length,z=s&&(M==null?void 0:M.role)==="assistant"&&!T&&(I||F),B=o||z;if(w.current={key:R,count:e.length,length:O},a&&(T||I||F||B)){C({force:!1,instant:B});return}if(!a&&T){const $=e.length-_.count;$>0&&(h(!0),m(P=>P+$))}else!a&&F&&(h(!0),m($=>$>0?$:1))},[e,C,a,s,o]),N.useEffect(()=>{C({instant:!0})},[C]),N.useEffect(()=>{if(typeof ResizeObserver>"u")return;const k=i.current;if(!k)return;x.current=k.scrollHeight;const _=new ResizeObserver(()=>{const M=i.current;if(!M)return;const R=x.current,O=M.scrollHeight;x.current=O,!b.current&&y.current&&O>R&&C({force:!1,instant:!0})});return _.observe(k),()=>{_.disconnect()}},[C]),N.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:p,scrollToBottom:C,handleScroll:j,resetNewMessageCount:D}}function dee(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=N.useState(r),a=N.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=N.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=N.useCallback(()=>{i(r)},[r]);return N.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function fee(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:UQ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const xQe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function yQe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=N.useState(!1),[a,l]=N.useState(Ww),[u,d]=N.useState(!1),[f,h]=N.useState(!1),[p,m]=N.useState(!1),g=n??p,{isLocalDev:b,isConsoleMode:x}=dp(),y=N.useRef(null);ee(Ve=>Ve.dashboard.aiScopeTables),ee(Ve=>Ve.isDashboardEditing);const v=ee(Ve=>Ve.selectedSheetId),{setDataSource:w}=ur(),{addFrame:S,setSelectedFrameId:C,setIsDashboardEditing:j}=Yt(),D=Ip(),{setCurrentAIContext:k,updateSelectedEntities:_,setReasoningEffort:M,setShowReasoning:R}=H1(),{clearQueue:O}=Ap(),{clearFileAttachments:T,getFileAttachments:I}=YM(),F=qM("dashboard"),z=ee(Ve=>Ve.dashboard.aiContext),B=_e(Ve=>Ve.card.dataSource),{assistantProfile:$}=ree(),P=ee(Ve=>Ve.handleOpenAssistantProfile),{sendMessage:V,isLoading:L,messages:A,setMessages:W,status:U,stop:Y,errorMessage:K,clearError:H}=eQe(),q=N.useCallback(Ve=>{r==null||r(Ve),n===void 0&&m(Ve)},[n,r]),X=N.useCallback(()=>{q(!g)},[g,q]);N.useEffect(()=>{if(!g)return;function Ve(Ue){Ue.key==="Escape"&&q(!1)}return window.addEventListener("keydown",Ve),()=>{window.removeEventListener("keydown",Ve)}},[g,q]);const[Z,G]=N.useState(""),Q=Ve=>{G(Ve.target.value)};function ne({sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ze,python:ve,cardConfig:ke,dataSource:Te}){if(console.log("handleAddNewFrame",{sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ze,python:ve,cardConfig:ke,dataSource:Te}),!v)return;const ze={id:Mr(),title:ht||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ze==="horizontalBar"?"y":"x"}},type:Ze,sql:Ve,python:ve,dataSource:Te,config:ke,connectionId:He},nt={id:Mr(),cards:[ze],activeCardId:ze.id};j(!0),S(v,nt,"end"),C(nt.id)}const ae=Ve=>{Ve.preventDefault();const Ue=Z.trim();if(!Ue&&F.length===0)return;const ht=[];Ue&&ht.push({type:"text",text:Ue}),F.forEach(He=>{He.data&&ht.push({type:"file",mediaType:He.type,filename:He.name,url:`data:${He.type};base64,${He.data}`})}),V({role:"user",parts:ht}),G(""),T("dashboard"),se({force:!0})};N.useEffect(()=>{var Ve;e&&((Ve=y.current)==null||Ve.focus())},[e]),cee({assistantType:"dashboard",status:U,isLoading:L,sendMessage:V});const{hasActiveTools:ie}=fee(A),{visibleMessages:fe,hasMoreMessages:xe,totalMessageCount:Ce,loadMoreMessages:je,resetMessageWindow:de}=dee(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Re,isAtBottom:Oe,hasNewMessages:mt,newMessageCount:be,scrollToBottom:se,handleScroll:ue,resetNewMessageCount:we}=uee(fe,{threshold:50,behavior:"smooth",isStreaming:L});function Se(Ve){Ke();const Ue={role:"user",parts:[{type:"text",text:Ve.title+" "+Ve.subtitle}]};V(Ue)}function Pe(Ve){Ke(),V({role:"user",parts:[{type:"text",text:Ve}]})}function Qe(Ve){Ke(),V({role:"user",parts:[{type:"text",text:Ve}]}),se({force:!0})}const Nt=N.useCallback(async()=>{const Ve=JSON.stringify(A??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Ve),Le.success("Conversation copied")}catch(Ue){console.error("Failed to copy conversation",Ue),Le.error("Unable to copy conversation")}},[A]);function Ke(){D.selectedEntities.length===0&&k({selectedEntities:(z==null?void 0:z.selectedEntities)||[]})}const $t=(Z==null?void 0:Z.length)===0&&(A==null?void 0:A.filter(Ve=>Ve.role==="user").length)===0;function Ne(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Dt(){return c.jsxs(cp,{children:[c.jsx(up,{asChild:!0,children:c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(ep,{className:"size-3.5"})})}),c.jsxs(Ud,{align:"end",children:[c.jsx(Kf,{children:"Options"}),c.jsx(bd,{}),c.jsx(Gm,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Gm,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Gm,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const hn=c.jsxs("div",{"data-role":"dashboard-assistant",className:J("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ne(),P&&c.jsx(oe,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:P,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&Dt(),a&&c.jsx(oe,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Nt,children:"Copy Conversation"}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:X,children:g?c.jsx(X_,{className:"size-4"}):c.jsx(s1,{className:"size-4"})}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),O("dashboard"),H(),de()},children:c.jsx(o1,{className:"size-4"})}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(vt,{className:"size-4"})})]})]}),c.jsxs(yl,{"data-role":"dashboard-assistant-scroll-area",ref:Re,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:ue,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[xe&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:je,className:"text-xs",children:["Load ",Math.min(5,Ce-fe.length)," ","more messages (",Ce-fe.length," ","hidden)"]})}),c.jsx(qQ,{showTools:a,showSystemMessage:u,messages:fe,onAddToDashboard:ne,onQuickReply:Qe,disableQuickReplies:L}),!ie&&c.jsx(WQ,{status:U,errorMessage:K})]}),c.jsx(Zo,{orientation:"horizontal"})]}),e&&!Oe&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{se({force:!0}),we()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(Ys,{className:"h-4 w-4"}),mt&&be>0&&c.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:be>9?"9+":be})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&$t&&c.jsx(YQ,{onClick:Se,placeholders:xQe}),c.jsx("div",{children:$t&&$&&c.jsx(see,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Pe})}),c.jsx(lee,{assistantType:"dashboard",className:"mb-3"}),c.jsx(DI,{ref:y,setInput:G,stop:Y,input:Z,handleInputChange:Q,handleSubmit:Ve=>{Ke(),ae(Ve),se({force:!0})},isLoading:L,status:U,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(_I,{incomingSelectedEntities:(z==null?void 0:z.selectedEntities)||[],open:f,onOpenChange:h,dataSource:B||XS,dialogMode:"aiContext"})]});return g&&s?In.createPortal(c.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:c.jsx("div",{className:"flex h-full w-full",children:hn})}),s):hn}function vQe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Yt(),o=ee(d=>d.dashboard.sheets),a=ee(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=ee(d=>d.isDashboardEditing),u=ee(d=>d.isVisualEditing);N.useEffect(()=>{if(!l||u)return;async function d(p){const m=p.ctrlKey||p.metaKey;m&&p.key==="c"?(await f(),Le.success("Card copied to clipboard"),p.preventDefault()):m&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText();try{const m=JSON.parse(p);if(m!=null&&m.id){const g=tR(m),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),Le.success("Card pasted from clipboard")}}catch(m){console.error("Failed to parse clipboard contents: ",m)}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function wQe(e,t){switch(e.interactionMode){case"drillToDetail":SQe(e,t);break;case"drillThrough":CQe(e,t);break;case"drillToURL":NQe(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 SQe(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 CQe(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 NQe(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 jQe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsxs(Vr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Hr,{children:[c.jsx(Ur,{children:i||"Insight Detail"}),c.jsx(Rs,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(oZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(aZ,{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 kQe(){const e=Lt(w=>w.interactionStates),t=Lt(w=>w.setInteractionState),n=Lt(w=>w.clearLastInteractionEvent),r=Lt(w=>w.replaceCardWithInsight),s=Lt(w=>w.setPendingDrillThrough),o=Lt(w=>w.pendingDrillThrough),i=Lt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Yt(),{selectDashboard:u}=Rb(),d=ee(w=>w.dashboard),f=ee(w=>w.filterValues),{data:h,isLoading:p}=Ffe((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[m,g]=N.useState({open:!1,insightId:""}),b=lZ(m.insightId,{enabled:m.open&&!!m.insightId}),x=N.useRef(new Set),y=N.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:S,contextMode:C})=>{g({open:!0,insightId:w,filters:S,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:C})},replaceCardContent:({cardId:w,insightId:S,filters:C,contextMode:j})=>{r(w,S,C,j)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:D})=>{const _={sourceCardId:ra,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...Ao(),appliedClickFilters:[_],contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:D};t(ra,M)}}),[a,r,f,l,d,s,t]);N.useEffect(()=>{Object.entries(e).forEach(([w,S])=>{if(S!=null&&S.lastInteractionEvent){const C=S.lastInteractionEvent,j=`${w}-${C.interactionMode}-${C.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{wQe(C,y)}catch(D){console.error("Error executing interaction event:",D)}finally{n(w),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),N.useEffect(()=>{if(!(!o||!h||p))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,p,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(jQe,{open:m.open,onOpenChange:v,insightId:m.insightId,filters:m.filters,filterDefinitions:m.filterDefinitions,contextMode:m.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&p&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(On,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function EQe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=_Qe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function _Qe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function DQe(e){return e?`Back to ${e}`:"Back"}function MQe(){var x,y,v,w,S;const e=Lt(C=>C.interactionStates[ra]),t=ee(C=>C.actions.goBackFromDrill),n=ee(C=>C.actions.clearDrillContext),{selectDashboard:r}=Rb(),[s,o]=N.useState({x:16,y:16}),[i,a]=N.useState(!1),l=N.useRef({x:0,y:0});N.useEffect(()=>{if(!i)return;const C=D=>{o({x:D.clientX-l.current.x,y:D.clientY-l.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",C),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:w.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((S=e.appliedClickFilters)!=null&&S.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(C){console.error("[DrillBack] Error during back navigation:",C)}},m=()=>{n()},g=C=>{C.target.closest("button")||(a(!0),l.current={x:C.clientX-s.x,y:C.clientY-s.y})};EQe(f);const b=DQe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((C,j)=>{const D=C.field.label||C.field.name,k=String(C.value);return c.jsxs(Fe,{variant:"secondary",className:"pointer-events-none text-xs",children:[D," = ",k]},j)})})]}),c.jsx(oe,{variant:"ghost",size:"sm",onClick:m,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(vt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(oe,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(o8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function hee(){var G;const{showAssistant:e,tokenProps:t}=qe(),{preferences:n,isConsoleMode:r}=dp(),s=((G=n==null?void 0:n.cardDisplay)==null?void 0:G.mode)==="print",o=N.useRef(null),i=N.useRef(null),[a,l]=N.useState(!1),u=nd(Q=>Q.setFullscreen),d=nd(Q=>Q.setPanelOpen),f=nd(Q=>Q.setContainer),h=kW("dashboard"),p=EW(),m=_W("dashboard"),g=h.isOpen,b=p==="dashboard",x=ee(Q=>Q.isVisualEditing),y=ee(Q=>Q.themeStyle),v=ee(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.sheets}),w=ee(Q=>Q.isDashboardEditing),S=ee(Q=>Q.selectedSheetId),C=ee(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.id}),j=ee(Q=>Q.isDashboardPanelOpen),D=ee(Q=>Q.actions.setIsDashboardPanelOpen),{getDefaultSheetId:k,setDefaultSheetId:_,clearDefaultSheetId:M}=L6(C),[R,O]=N.useState(null);v1(At.DASHBOARD);const{setSelectedSheetId:T,setSheetTitle:I,addSheet:F,setSheets:z}=Yt();vQe(i);const{setActiveAssistantType:B}=H1();N.useEffect(()=>{if(C){const Q=k();O(Q)}},[C,k]),N.useEffect(()=>{g?B("dashboard"):p==="dashboard"&&u(null)},[g,B,p,u]);function $(Q){var ne,ae;Q?((ne=o.current)==null||ne.resize(40),d("dashboard",!0),B("dashboard")):(d("dashboard",!1),u(null),(ae=o.current)==null||ae.resize(0),B(null))}function P(){const Q={id:Mr(),title:"New Sheet"};F(Q),T(Q.id)}function V(Q,ne){if(!C)return;R===Q?(M(),O(null),Le.success("Default sheet cleared")):(_(Q),O(Q),Le.success(`"${ne}" set as default sheet`))}function L(Q){Q<1?(d("dashboard",!1),u(null),B(null)):(g||d("dashboard",!0),B("dashboard"))}function A(){return(y==null?void 0:y.canvasTheme)==="muted"||!(y!=null&&y.canvasTheme)?"hsl(var(--semaphor-muted))":(y==null?void 0:y.canvasTheme)==="clear"?"":y==null?void 0:y.canvasTheme}const W=(Q,ne)=>{Q.dataTransfer.setData("tabIndex",ne.toString())},U=Q=>{Q.preventDefault()},Y=(Q,ne)=>{const ae=Q.dataTransfer.getData("tabIndex");if(ae===ne.toString())return;const ie=Array.from(v||[]),[fe]=ie.splice(parseInt(ae),1);ie.splice(ne,0,fe),z(ie)},K=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail;function H(){var Q,ne;if(v&&v.length>1||w)return c.jsxs(Wr,{role:"tab-list",className:"flex h-11 items-center justify-start gap-2 rounded-none border-b border-b-muted bg-transparent px-2.5 py-3",children:[r&&K&&c.jsx(oe,{variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{D(!j)},className:"h-8 p-2",children:j?c.jsx(b8,{className:"h-4 w-4"}):c.jsx(x8,{className:"h-4 w-4"})}),v==null?void 0:v.map((ae,ie)=>{const fe=S===ae.id,xe=R===ae.id;return c.jsxs(Ht,{draggable:!0,onDragStart:Ce=>W(Ce,ie),onDragOver:U,onDrop:Ce=>Y(Ce,ie),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>T(ae.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:ae.id,children:[c.jsx(Jg,{enabled:w&&fe,text:ae.title,onSave:Ce=>I(ae.id,Ce),children:ae.title},ae.id),!w&&fe&&c.jsx("div",{title:xe?"Clear default sheet":"Set as default sheet",children:c.jsx(nD,{className:J("ml-1 size-3 cursor-pointer transition-all",xe?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:Ce=>{Ce.stopPropagation(),V(ae.id,ae.title||"Sheet")}})}),w&&fe&&v.length>1&&c.jsx(vt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},ae.id)}),w&&c.jsx("div",{style:{borderRadius:(ne=(Q=y==null?void 0:y.chart)==null?void 0:Q.options)==null?void 0:ne.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:P,children:c.jsx(jr,{className:"size-3"})})]})}function q(){return c.jsx("div",{ref:i,style:{},className:"grow",children:v==null?void 0:v.map(Q=>c.jsx(Gn,{style:{backgroundColor:A()},className:J("mt-0",{}),value:Q.id,children:c.jsx(q6e,{sheet:Q})},Q.id))})}function X(){var Q;return c.jsxs(cs,{"data-role":"dashboard-tabs-container",className:J("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:ne=>{T(ne)},value:S||((Q=v==null?void 0:v[0])==null?void 0:Q.id),children:[H(),c.jsx(yl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:q()}),c.jsx(j8e,{open:a,setOpen:l})]})}const Z=N.useCallback(Q=>{f("dashboard",Q)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(kQe,{}),c.jsx(MQe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(_X,{className:J("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(BE,{children:X()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(N8e,{open:g,onTabClick:$,withHandle:!0}),c.jsx(BE,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:L,defaultSize:g?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(yQe,{open:g,setOpen:$,isFullscreen:b,onFullscreenChange:Q=>u(Q?"dashboard":null),fullscreenContainer:m})})})]})]}),c.jsx("div",{ref:Z,className:J("absolute inset-0",!b&&"pointer-events-none")}),e===!0&&!s&&!g&&!x&&c.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:c.jsx(oe,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>$(!0),title:"Open Assistant",children:c.jsx(tD,{className:"h-5 w-5"})})})]})]}):null}function MI({children:e}){return c.jsx(wa,{style:{height:"100%",width:"100%"},children:c.jsx(ise,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(Yn,{delayDuration:0,children:e})})})}function pee({children:e,preferences:t}){const{currentUser:n}=Ms(),r=N.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return c.jsx(D9.Provider,{value:r,children:c.jsx(SR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function mee(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(wl,{FallbackComponent:dS,children:c.jsx(L_,{dashboardProps:e,children:c.jsx(MI,{children:c.jsx(pee,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(GM,{...e,type:"dashboard",children:c.jsx(hee,{})})})})})})})}function TI(e){const{tokenProps:t,authToken:n}=qe(),r=t==null?void 0:t.apiServiceUrl;return un({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return Vn(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function gee(e,t,n){if(t==="source")return{isValid:!0};const r=Ks(e.dataType);if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function bee(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 xee=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=TI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=ur(),h=_e(T=>T.card.type),p=e==null?void 0:e.id,m=N.useCallback(T=>{if(!(e!=null&&e.config))return[];switch(T){case"groupBy":return(e.config.groupByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,dateFormat:I.dateFormat,customFormat:I.customFormat,granularity:I.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,direction:I.direction}));case"source":return[];default:return[]}},[e]),g=N.useCallback((T,I)=>{if(p)switch(T){case"groupBy":{r(p,{groupByColumns:I});break}case"metrics":{r(p,{metricColumns:I});break}case"pivotBy":{r(p,{pivotByColumns:I});break}case"sortBy":{r(p,{sortByColumns:I});break}}},[p,r]),b=N.useCallback((T,I,F)=>{if(!p)return;const B=m(T)[I];if(B)switch(T){case"groupBy":s(p,B.id,{label:F});break;case"metrics":o(p,B.id,{label:F});break;case"pivotBy":i(p,B.id,{label:F});break;case"sortBy":a(p,B.id,{label:F});break}},[p,m,s,o,i,a]),x=N.useCallback((T,I)=>{if(!p)return;const z=m("metrics")[T];z&&o(p,z.id,{aggregate:I,label:sU(z.name,I)})},[p,m,o]),y=N.useCallback((T,I,F)=>{if(!p)return;const B=m("groupBy")[T];if(!B)return;const $={dateFormat:I};I==="custom"&&F?$.customFormat=F:$.customFormat=void 0,s(p,B.id,$)},[p,m,s]),v=N.useCallback((T,I)=>{if(!p)return;const z=m("groupBy")[T];z&&s(p,z.id,{granularity:I})},[p,m,s]),w=N.useCallback((T,I)=>{if(!p)return;const z=m("metrics")[T];z&&o(p,z.id,{aliasTemplate:I})},[p,m,o]),S=N.useCallback((T,I)=>{if(console.log("handleValueAliasesChange",T,I),!p)return;console.log("handleValueAliasesChange",T,I);const z=m("metrics")[T];z&&(console.log("handleValueAliasesChange",I),o(p,z.id,{valueAliases:I}))},[p,m,o]),C=N.useCallback(T=>{if(!p)return;if(m("metrics").length===0){Le.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:T})},[p,r,m]),j=N.useCallback(T=>{p&&r(p,{showTrendline:T})},[p,r]),D=N.useCallback(T=>{p&&r(p,{trendlineWindow:T})},[p,r]),k=N.useCallback(T=>{p&&r(p,{trendlineGranularity:T})},[p,r]),_=N.useCallback(T=>{p&&r(p,{targetValue:T})},[p,r]),M=N.useCallback(T=>{var V;if(!p)return;const I=[...m("groupBy"),...m("pivotBy"),...m("metrics"),...m("sortBy")],F=qSe(T,I,{joinPlan:(V=e==null?void 0:e.config)==null?void 0:V.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!F.isValid){F.showError&&tU();return}const z=KSe(T,I,h);if(!z){Le.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const B=gee(T,z,h);if(!B.isValid){Le.error("Invalid Field Type",{description:B.reason,position:"top-center",duration:3e3});return}const $=m(z);if(nU(T,$))return;const P=oU(T,z,$);if(P){const L=[...$,P];g(z,L),z==="metrics"&&bee(h,e==null?void 0:e.config,r,p,L)}},[p,e==null?void 0:e.config,m,g,t,n,h,r]),R=N.useCallback((T,I)=>{if(!p)return;const z=m(T)[I];if(z){if(T!=="sortBy"){const B=m("sortBy"),$=B.filter(P=>!(P.name===z.name&&P.qualifiedEntityName===z.qualifiedEntityName));$.length!==B.length&&r(p,{sortByColumns:$})}switch(T){case"groupBy":l(p,z.id);break;case"metrics":u(p,z.id);break;case"pivotBy":d(p,z.id);break;case"sortBy":f(p,z.id);break}}},[p,m,l,u,d,f,r]);return{getFieldsForContainer:m,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:S,removeField:R,handleFieldClick:M,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:j,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:_,cardType:h}};function Px(e,t){var Pe,Qe,Nt,Ke,$t;const{tokenProps:n}=qe(),r=Zs(),s=qe().authToken||e,o=_e(Ne=>Ne.selectedConnectionId),i=_e(Ne=>Ne.card),{queryKey:a}=zpe(i),l=_e(Ne=>Ne.selectedDatamodelId),u=_e(Ne=>Ne.isDevMode),d=_e(Ne=>Ne.selectedDatabaseName),f=_e(Ne=>Ne.selectedSchemaName),h=_e(Ne=>Ne.selectedTableName),p=_e(Ne=>Ne.actions.setSelectedConnectionId),m=_e(Ne=>Ne.actions.setSelectedDatamodelId),g=_e(Ne=>Ne.actions.setSelectedDatabaseName),b=_e(Ne=>Ne.actions.setSelectedSchemaName),x=_e(Ne=>Ne.actions.setSelectedTableName);_e(Ne=>Ne.actions.setCardSql);const{setQueryConfig:y}=ur();function v(Ne){var hn;return o&&Ne==="API"?!1:o&&Ne==="S3"?!0:!(!o||!d||d==="NA"||((hn=k==null?void 0:k.capabilities)==null?void 0:hn.path.includes("schema"))&&!f)}function w(Ne){return o&&Ne?!(Ne==="API"||Ne==="S3"):!1}const{refetchConnections:S,connectionsData:C,isConnectionsLoading:j,isConnectionsError:D,selectedConnection:k}=Ai(e),{refetch:_,data:M,isLoading:R,isError:O}=un({queryKey:["models",o],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),T=k==null?void 0:k.type,I=(k==null?void 0:k.type)==="API"||(k==null?void 0:k.type)==="S3",{data:F,isLoading:z,isFetching:B,isError:$,refetch:P}=un({queryKey:["databases",o],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(T)}),{data:V,isLoading:L,isFetching:A,isError:W,refetch:U}=un({queryKey:["schemas",o,d],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!I&&d!=="NA"}),{data:Y,isLoading:K,isFetching:H,isError:q,refetch:X}=un({queryKey:["tables",o,d,f],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(T)}),{columns:Z,isColumnsLoading:G,isColumnsFetching:Q,isColumnsError:ne,refetchColumns:ae}=iU(e);N.useEffect(()=>{(T==="S3"||T==="API")&&(g(""),b(""),m(""),T==="API"&&x("api"))},[T,x,g,b,m]);const ie=(k==null?void 0:k.type)==="API"?(Pe=k==null?void 0:k.type)==null?void 0:Pe.toLowerCase():h||"",fe=I?"":f||"";function xe(Ne){x(Ne),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Ce(Ne){b(Ne),x("")}function je(Ne){g(Ne==="none"?"":Ne),b(""),x(""),Ne!=="none"&&Ne!==""&&m("")}function de(Ne){p(Ne)}function Re(Ne){m(Ne==="none"?"":Ne),Ne!=="none"&&Ne!==""&&g("")}F&&((Qe=F==null?void 0:F.databases)==null?void 0:Qe.length)>0,V&&((Nt=V==null?void 0:V.schemas)==null?void 0:Nt.length)>0;const Oe=C==null?void 0:C.connections.map(Ne=>({id:Ne.id,name:Ne.name,type:Ne.type})),mt=(Ke=M==null?void 0:M.datamodels)==null?void 0:Ke.map(Ne=>({id:Ne.id,name:Ne.name})),be=F==null?void 0:F.databases.map(Ne=>({id:Ne.database_name,name:Ne.database_name})),se=V==null?void 0:V.schemas.map(Ne=>({id:Ne.schema_name,name:Ne.schema_name})),ue=Y==null?void 0:Y.tables.map(Ne=>({id:Ne.table_name,name:Ne.table_name})),we=($t=M==null?void 0:M.datamodels.find(Ne=>Ne.id===l))==null?void 0:$t.name,Se=Ky({schemaName:fe,tableName:ie,modelName:we,connectionType:T,databaseName:d||""});return{connectionItems:Oe,selectedConnectionId:o,selectedConnection:k,isConnectionsLoading:j,isConnectionsError:D,modelItems:mt,selectedDatamodelId:l,selectedDatamodelName:we,isModelsLoading:R,isModelsError:O,selectedDatabaseName:d,databaseItems:be,isDatabasesLoadingOrFetching:z||B,isDatabaseError:$,schemaItems:se,selectedSchemaName:f,isSchemaLoadingOrFetching:L||A,isSchemaError:W,tableItems:ue,selectedTableName:h,isTableLoadingOrFetching:K||H,isTableError:q,columns:Z,isColumnsLoadingOrFetching:G||Q,isColumnsError:ne,isNonDbConnection:I,connectionType:T,tableName:ie,formattedTableName:Se,schemaName:fe,refetchConnections:S,refetchModels:_,refetchDatabases:P,refetchSchemas:U,refetchTables:X,refetchColumns:ae,handleConnectionChange:de,handleDatamodelChange:Re,handleDatabaseChange:je,handleSchemaChange:Ce,handleTableChange:xe}}function py(e){return`${e}-${Mr()}`}function vL(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 TQe(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 RI(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 yee(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function vee(){const e=_e(C=>C.sqlGen),t=_e(C=>C.isDevMode),n=_e(C=>C.card.dataSource),r=_e(C=>{var j,D;return(D=(j=C.card)==null?void 0:j.queryConfig)==null?void 0:D.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=RI(n),a=yee(n),l=_e(C=>C.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:m}=ur(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Px(),y=C=>({column_name:C.name,data_type:C.dataType,label:C.label,description:C.description});return{handleDevModeFieldClick:C=>{var D;if(!t)return;const j=y(C);if(t&&a&&s){const k=M_(j,e);p(k);const _=(D=b==null?void 0:b.find(R=>R.id===l))==null?void 0:D.name,M=D_(k,fi(o||""),fi(s),_||"",g,i||"");M&&(f(M),h(!0))}else if(!t){if(Mb(j.data_type))if(r&&r.length>0){const k={...j,role:"groupby",id:py(j.column_name),name:j.column_name,type:j.data_type};d(k)}else{const k={...j,role:"metric",id:py(j.column_name),name:j.column_name,label:vL(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(k)}if(Lc(j.data_type)){const k={...j,role:"groupby",id:py(j.column_name),name:j.column_name,type:j.data_type,label:TQe(j.column_name,"month"),granularity:"month"};d(k)}if(Vo(j.data_type)){const k={...j,role:"metric",id:py(j.column_name),name:j.column_name,label:vL(j.column_name,"SUM"),type:j.data_type,aggregate:"SUM"};u(k)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Ky({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});m(!1);const j=g==="MSSQL"?`SELECT top 10 * FROM ${C}`:`SELECT * FROM ${C} LIMIT 10`;f(j),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Ky({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${C}`),h(!0)},isNumberField:C=>Vo(C.dataType)}}function wee(){const e=_e(m=>m.selectedConnectionId),t=_e(m=>m.selectedDatamodelId),n=_e(m=>m.selectedDatabaseName),r=_e(m=>m.selectedSchemaName),s=_e(m=>m.selectedTableName),o=ee(m=>m.dashboard.filters)||[],i=ee(m=>m.selectedSheetId),a=ee(m=>m.actions.addFilter),l=ee(m=>m.actions.removeFilter),{removeFilterValues:u}=Yt(),{modelItems:d,tableName:f,connectionType:h}=Px();function p(m,g="sheet",b){var k;const x=fi(m.column_name),y=fi(n||""),v=fi(r||""),w=fi(f);let S=qw({schemaName:v,tableName:w,connectionType:h,databaseName:y}),C=`${S}.${x}`;const j=(k=d==null?void 0:d.find(_=>_.id===t))==null?void 0:k.name;t&&t!=="none"&&(C=`${Cg}.${j}.${x}`,S=`${Cg}.${j}`),b!=null&&b.qualifiedFieldName&&(C=b.qualifiedFieldName,S=b.qualifiedFieldName.split(".").slice(0,-1).join(".")),b!=null&&b.entityName;let D;if(g==="sheet"&&i?D=Nke(o,C,w,n||"",y,i):D=o==null?void 0:o.find(_=>_.column===C&&_.table===w&&(_.database===y||_.database===n)),D)u(D.id),l(D.id);else{const _=Mr(),M=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:_,column:C,title:m.label||m.column_name,dataType:m.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:M,sql:V4(m.data_type,S,x)}),_):(a({id:_,location:g,column:C,title:m.label||m.column_name,dataType:m.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:M,sql:V4(m.data_type,S,(b==null?void 0:b.qualifiedFieldName)||x)}),_)}}return{assignFilter:p}}function RQe({column:e}){const[t,n]=N.useState(!1),r=_e(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=RI(r),a=_e(x=>x.selectedDatamodelId),l=_e(x=>x.sqlGen),{modelItems:u,connectionType:d}=Px(),f=_e(x=>x.actions.setSqlGen),h=_e(x=>x.actions.setCardSql),p=_e(x=>x.actions.setRunSql),m=yee(r);function g(x,y){var C;if(!m||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=M_(x,l,y),w=(C=u==null?void 0:u.find(j=>j.id===a))==null?void 0:C.name;f(v);const S=D_(v,fi(o||""),fi(s),w||"",d,i||"");S&&(h(S),p(!0)),n(!1)}function b(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>g(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>g(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>g(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>g(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>g(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return m?c.jsxs(Mp,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(Tp,{asChild:!0,children:c.jsx(ep,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(Xd,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function IQe({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 AQe({field:e,context:t="editor",fieldState:n}){const r=_e(L=>L.isDevMode),s=t==="filter",o=r||s||(n==null?void 0:n.state)==="unreachable"&&!s,i=ee(L=>L.dashboard.filters),a=ee(L=>L.selectedSheetId),l=ee(L=>L.actions.removeFilter),{removeFilterValues:u}=Yt(),{assignFilter:d}=wee(),f=s?Zc(i,a):i,h=s?f==null?void 0:f.find(L=>{var A;return L.title===e.name||((A=L.column)==null?void 0:A.includes(e.name))}):void 0,p=!!h,m=h&&s?i==null?void 0:i.find(L=>L.id===h.id):void 0,g=m&&(m.applyToSheetIds&&m.applyToSheetIds.length>1||m.excludeSheetIds&&m.excludeSheetIds.length>0||!m.applyToSheetIds&&!m.excludeSheetIds&&!m.sheetId);s&&p&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:p,activeFilterOnSheet:h?{id:h.id,title:h.title,column:h.column,applyToSheetIds:h.applyToSheetIds,excludeSheetIds:h.excludeSheetIds}:null,activeFilterForField:m?{id:m.id,title:m.title,column:m.column,applyToSheetIds:m.applyToSheetIds,excludeSheetIds:m.excludeSheetIds}:null,isMultiSheetFilter:g,selectedSheetId:a});const[b,x]=N.useState(!1),[y,v]=N.useState(null),{attributes:w,listeners:S,setNodeRef:C,transform:j,transition:D,isDragging:k}=TS({id:e.id,disabled:o}),[_,M]=N.useState(!1),R=_e(L=>L.card),{handleFieldClick:O}=xee(R),{handleDevModeFieldClick:T,isNumberField:I}=vee(),F=()=>{m&&(console.log("[SourceField] Removing multi-sheet filter:",m.id),u(m.id),l(m.id)),v(null),x(!1)},z=()=>{if(s){const L={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};p&&g?(v({column:L,field:e}),x(!0)):d(L,"sheet",e)}else r?T(e):O(e)},B={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},$={transform:_i.Transform.toString(j),transition:D},V=(()=>{if(!n||s)return{};const A={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...A},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...A},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...A}}[n.state]||A})();return c.jsxs("div",{ref:C,style:$,...o?{}:w,...o?{}:S,className:J("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",k&&"scale-95 opacity-50",!k&&"border",V.borderColor||"border-transparent",V.bgColor||"",V.hoverBorderColor,V.hoverBgColor||"hover:bg-muted",V.opacity,V.cursor,p&&"border-accent-foreground/20 bg-accent",{"cursor-pointer":r||s,"cursor-grab active:cursor-grabbing":!o&&!r&&!s}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:z,children:[sb(e.dataType),c.jsx(Yn,{children:c.jsxs(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${_?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(Cn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(IQe,{field:e,fieldState:n})})]})}),r&&!s&&I(e)&&c.jsx("div",{onClick:L=>L.stopPropagation(),children:c.jsx(RQe,{column:B})})]}),_&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(xo,{className:"",children:c.jsxs(Si,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(F8,{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(jae,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Fe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx(Hb,{open:b,onOpenChange:x,children:c.jsxs(fp,{children:[c.jsxs(hp,{children:[c.jsx(mp,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(gp,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(pp,{children:[c.jsx(xp,{children:"Cancel"}),c.jsx(bp,{onClick:F,children:"Remove Filter"})]})]})})]})}const PQe="SEMAPHOR_CALCULATED_FIELD",OQe=["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 See(e){return!!e.expression}function FQe(e){return!!e.expression}function $Qe(e){return!!e.expression}var Cee=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(Cee||{}),jl="Accordion",LQe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[II,zQe,BQe]=i1(jl),[tC]=Er(jl,[BQe,fZ]),AI=fZ(),Nee=N.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(II.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(WQe,{...o,ref:t}):c.jsx(UQe,{...s,ref:t})})});Nee.displayName=jl;var[jee,VQe]=tC(jl),[kee,HQe]=tC(jl,{collapsible:!1}),UQe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=$r({prop:n,defaultProp:r,onChange:s});return c.jsx(jee,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:N.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(kee,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(Eee,{...i,ref:t})})})}),WQe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i=[],a]=$r({prop:n,defaultProp:r,onChange:s}),l=N.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=N.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(jee,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(kee,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(Eee,{...o,ref:t})})})}),[qQe,nC]=tC(jl),Eee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=N.useRef(null),l=ft(a,t),u=zQe(n),f=zd(s)==="ltr",h=Ee(e.onKeyDown,p=>{var D;if(!LQe.includes(p.key))return;const m=p.target,g=u().filter(k=>{var _;return!((_=k.ref.current)!=null&&_.disabled)}),b=g.findIndex(k=>k.ref.current===m),x=g.length;if(b===-1)return;p.preventDefault();let y=b;const v=0,w=x-1,S=()=>{y=b+1,y>w&&(y=v)},C=()=>{y=b-1,y<v&&(y=w)};switch(p.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?S():C());break;case"ArrowDown":o==="vertical"&&S();break;case"ArrowLeft":o==="horizontal"&&(f?C():S());break;case"ArrowUp":o==="vertical"&&C();break}const j=y%x;(D=g[j].ref.current)==null||D.focus()});return c.jsx(qQe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(II.Slot,{scope:n,children:c.jsx(Be.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Fw="AccordionItem",[YQe,PI]=tC(Fw),_ee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=nC(Fw,n),i=VQe(Fw,n),a=AI(n),l=nr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(YQe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(mZ,{"data-orientation":o.orientation,"data-state":Aee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});_ee.displayName=Fw;var Dee="AccordionHeader",Mee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=nC(jl,n),o=PI(Dee,n);return c.jsx(Be.h3,{"data-orientation":s.orientation,"data-state":Aee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Mee.displayName=Dee;var d_="AccordionTrigger",Tee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=nC(jl,n),o=PI(d_,n),i=HQe(d_,n),a=AI(n);return c.jsx(II.ItemSlot,{scope:n,children:c.jsx(K3e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Tee.displayName=d_;var Ree="AccordionContent",Iee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=nC(jl,n),o=PI(Ree,n),i=AI(n);return c.jsx(Z3e,{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}})});Iee.displayName=Ree;function Aee(e){return e?"open":"closed"}var GQe=Nee,KQe=_ee,ZQe=Mee,Pee=Tee,Oee=Iee;const Fee=GQe,OI=E.forwardRef(({className:e,...t},n)=>c.jsx(KQe,{ref:n,className:J("border-b",e),...t}));OI.displayName="AccordionItem";const FI=E.forwardRef(({className:e,children:t,...n},r)=>c.jsx(ZQe,{className:"flex",children:c.jsxs(Pee,{ref:r,className:J("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,c.jsx(Ys,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));FI.displayName=Pee.displayName;const $I=E.forwardRef(({className:e,children:t,...n},r)=>c.jsx(Oee,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:J("pb-4 pt-0",e),children:t})}));$I.displayName=Oee.displayName;function XQe({context:e="editor"}={}){var _,M,R,O;const[t,n]=N.useState(""),[r,s]=N.useState("all");_e(T=>T.isDevMode);const o=_e(T=>T.card.dataSource),i=_e(T=>T.card.config),a=_e(T=>T.card),{autoJoinMetadata:l}=ha(a),{columns:u=[],columnGroups:d=[],isLoading:f,error:h}=MM(),p=(o==null?void 0:o.mode)==="semanticDomain"?o.semanticDomainId:void 0,{data:m}=TI(p),g=[...(i==null?void 0:i.groupByColumns)||[],...(i==null?void 0:i.metricColumns)||[]];(M=(_=i==null?void 0:i.joinPlan)==null?void 0:_.baseEntity)==null||M.name,(O=(R=l==null?void 0:l.resolvedJoinPlan)==null?void 0:R.baseEntity)==null||O.name,vee();const b=u.filter(T=>T.name.toLowerCase().includes(t.toLowerCase())||T.dataType.toLowerCase().includes(t.toLowerCase())||T.label&&T.label.toLowerCase().includes(t.toLowerCase())||T.qualifiedEntityName&&T.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),x=T=>{if(T.role==="metric"&&See(T)||T.role==="groupby"&&T.expression)return"calculated";if(T.dataType==="number"||T.dataType==="integer"||T.dataType==="float"||T.dataType==="decimal"||T.dataType==="currency")return"metrics";const I=Ks(T.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},v=(r==="all"?b:b.filter(T=>x(T)===r)).reduce((T,I)=>{const F=I.qualifiedEntityName||"Other Fields";return T[F]||(T[F]={label:R_(I.entityName),fields:[]}),T[F].fields.push(I),T},{}),S=Object.keys(v),C=b.filter(T=>x(T)==="dimensions").length,j=b.filter(T=>x(T)==="metrics").length,D=b.filter(T=>x(T)==="calculated").length,k=b.length>0;return f?c.jsx("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:c.jsx(_c,{size:"md",color:"muted","aria-label":"Loading data"})}):h?c.jsxs("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:[c.jsx(sl,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:h.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?c.jsx(Ds,{className:"h-[calc(100vh-200px)] w-[290px]",children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx(sl,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:e==="filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]})}):c.jsxs("div",{className:"mt-2 flex h-full w-full grow flex-col gap-2 px-6 pb-6",children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[u.length>0&&c.jsxs("div",{className:"relative mb-4",children:[c.jsx(xa,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(Bn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:t,onChange:T=>n(T.target.value)}),t&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:c.jsx(vt,{className:"size-3.5"})})]}),k&&c.jsx(cs,{defaultValue:"all",value:r,onValueChange:T=>s(T),className:"mb-4",children:c.jsxs(Wr,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(Ht,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:b.length})]}),c.jsxs(Ht,{value:"dimensions",className:"text-xs",children:[c.jsx(r1,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]}),c.jsxs(Ht,{value:"metrics",className:"text-xs",children:[c.jsx(Jh,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),c.jsxs(Ht,{value:"calculated",className:"text-xs",children:[c.jsx(q_,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:D})]})]})})]}),c.jsxs(yl,{className:"py-2",children:[c.jsx(Fee,{type:"multiple",defaultValue:S,className:"space-y-2",children:Object.entries(v).map(([T,I])=>{const F=d.find(z=>z.entityName===T)||{entityName:T,label:I.label};return c.jsxs(OI,{value:T,className:"border-none",children:[c.jsx(FI,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:F.label||F.entityName,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:F.label||F.entityName}),c.jsx(Fe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:I.fields.length})]})}),c.jsx($I,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:I.fields.map(z=>{const B=TM(z,{joinabilityMap:(m==null?void 0:m.joinabilityMap)||null,selectedFields:g,cardConfig:i,autoJoinMetadata:l});return c.jsx(AQe,{field:z,context:e,fieldState:B},z.id)})})})]},T)})}),Object.keys(v).length===0&&u.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:e==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(v).length===0&&u.length>0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(Zo,{orientation:"horizontal"}),c.jsx(Zo,{orientation:"vertical"})]})]})}function $ee({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(XQe,{context:e})," "]})}function Lee(){const e=_e(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=ur();N.useEffect(()=>{var p;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=RI(e),d=(p=e.selectedEntities)==null?void 0:p[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function QQe(){Lee();const e=ee(l=>l.selectedSheetId),t=ee(l=>l.selectedFrameId),n=ee(l=>l.dashboard),r=ee(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Yt(),{setCard:o}=ur(),i=_e(l=>l.card.dataSource);return N.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function JQe(){const e=ee(n=>n.actions.setShowFilters),{hasEntities:t}=QQe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(ce,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsx(oe,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(uZ,{})})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(sl,{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(DS,{collisionDetection:jS,children:c.jsx(MS,{items:[],strategy:FR,children:c.jsx($ee,{context:"filter"})})})})]})}function eJe(){const e=ee(r=>r.dashboard.filters),t=ee(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:J("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(NR,{filter:r}),c.jsx(wS,{filter:r})]},r.id))}):null}function tJe(){const e=ee(r=>r.showFilters),t=ee(r=>r.isVisualEditing),n=ee(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:J("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[c.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&c.jsx(eJe,{}),c.jsx(hee,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(JQe,{})})]})}const nJe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-CRc6gw-F.js"))),rJe=N.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-tRQ806YP.js"))),sJe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-BOlcQgKG.js"))),oJe=N.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-CwGyO8S9.js")).then(e=>({default:e.ResourceManagementPanel})));function iJe({showControls:e=!1,showFooter:t=!0,...n}){const r=ee(l=>l.isDashboardPanelOpen),s=ee(l=>l.isVisualEditing),o=ee(l=>l.showDashboardJSON),i=ee(l=>l.actions.setIsDashboardPanelOpen),{preferences:a}=n;return c.jsx(wl,{FallbackComponent:dS,children:c.jsxs(L_,{dashboardProps:n,children:[c.jsx(Jde,{}),c.jsx(MI,{children:c.jsxs(pee,{preferences:a,children:[o&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(sJe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(nJe,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(N.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(GM,{...n,type:"dashboard",children:[s&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(rJe,{})}),c.jsx(tJe,{})]})})]})]})]})})]})})}var aJe=Object.defineProperty,lJe=(e,t,n)=>t in e?aJe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,my=(e,t,n)=>lJe(e,typeof t!="symbol"?t+"":t,n);const cJe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},uJe={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}},dJe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},fJe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},hJe={stringify:e=>e,parse:e=>e},Q2={string:hJe,number:fJe,boolean:cJe,function:uJe,json:dJe};function pJe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const gy=Symbol.for("r2wc.render"),by=Symbol.for("r2wc.connected"),gu=Symbol.for("r2wc.context"),Ta=Symbol.for("r2wc.props");function mJe(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const p of i){l[p]=Array.isArray(t.props)?"string":t.props[p];const m=pJe(p);d[p]=m,f[m]=p}for(const p of a)u[p]=Array.isArray(t.events)?{}:t.events[p];class h extends HTMLElement{constructor(){super(),my(this,o,!0),my(this,s),my(this,r,{}),my(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Ta].container=this.container;for(const m of i){const g=d[m],b=this.getAttribute(g),x=l[m],y=x?Q2[x]:null;y!=null&&y.parse&&b&&(this[Ta][m]=y.parse(b,g,this))}for(const m of a)this[Ta][m]=g=>{const b=m.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[m]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[by]=!0,this[gy]()}disconnectedCallback(){this[by]=!1,this[gu]&&n.unmount(this[gu]),delete this[gu]}attributeChangedCallback(m,g,b){const x=f[m],y=l[x],v=y?Q2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[Ta][x]=v.parse(b,m,this),this[gy]())}[(o=by,s=gu,r=Ta,gy)](){this[by]&&(this[gu]?n.update(this[gu],this[Ta]):this[gu]=n.mount(this.container,e,this[Ta]))}}for(const p of i){const m=d[p],g=l[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[Ta][p]},set(b){this[Ta][p]=b;const x=g?Q2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,m,this);this.getAttribute(m)!==y&&this.setAttribute(m,y)}else this[gy]()}})}return h}function gJe(e,t,n){const r=dj(e),s=N.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function bJe({root:e,ReactComponent:t},n){const r=N.createElement(t,n);e.render(r)}function xJe({root:e}){e.unmount()}function yJe(e,t={}){return mJe(e,t,{mount:gJe,update:bJe,unmount:xJe})}const vJe={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"},wJe=yJe(mee,{props:vJe});function SJe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function wL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function SL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?wL(Object(n),!0).forEach(function(r){SJe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):wL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function CJe(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 NJe(e,t){if(e==null)return{};var n=CJe(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 jJe(e,t){return kJe(e)||EJe(e,t)||_Je(e,t)||DJe()}function kJe(e){if(Array.isArray(e))return e}function EJe(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 _Je(e,t){if(e){if(typeof e=="string")return CL(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 CL(e,t)}}function CL(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 DJe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1066
+ `)}})}});var gXe=cZe(()=>VJ(Ar([Wn({type:ut("text-start"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("text-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Wn({type:ut("text-end"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("error"),errorText:$e()}),Wn({type:ut("tool-input-start"),toolCallId:$e(),toolName:$e(),providerExecuted:Sr().optional(),dynamic:Sr().optional()}),Wn({type:ut("tool-input-delta"),toolCallId:$e(),inputTextDelta:$e()}),Wn({type:ut("tool-input-available"),toolCallId:$e(),toolName:$e(),input:co(),providerExecuted:Sr().optional(),providerMetadata:ir.optional(),dynamic:Sr().optional()}),Wn({type:ut("tool-input-error"),toolCallId:$e(),toolName:$e(),input:co(),providerExecuted:Sr().optional(),providerMetadata:ir.optional(),dynamic:Sr().optional(),errorText:$e()}),Wn({type:ut("tool-output-available"),toolCallId:$e(),output:co(),providerExecuted:Sr().optional(),dynamic:Sr().optional(),preliminary:Sr().optional()}),Wn({type:ut("tool-output-error"),toolCallId:$e(),errorText:$e(),providerExecuted:Sr().optional(),dynamic:Sr().optional()}),Wn({type:ut("reasoning-start"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-end"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("source-url"),sourceId:$e(),url:$e(),title:$e().optional(),providerMetadata:ir.optional()}),Wn({type:ut("source-document"),sourceId:$e(),mediaType:$e(),title:$e(),filename:$e().optional(),providerMetadata:ir.optional()}),Wn({type:ut("file"),url:$e(),mediaType:$e(),providerMetadata:ir.optional()}),Wn({type:FJ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:$e().optional(),data:co(),transient:Sr().optional()}),Wn({type:ut("start-step")}),Wn({type:ut("finish-step")}),Wn({type:ut("start"),messageId:$e().optional(),messageMetadata:co().optional()}),Wn({type:ut("finish"),messageMetadata:co().optional()}),Wn({type:ut("abort")}),Wn({type:ut("message-metadata"),messageMetadata:co()})])));function bXe(e){return e.type.startsWith("data-")}function ZJ(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]=ZJ(o,s):n[r]=s}return n}function xXe(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 XJ(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Aw({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Aw({text:xXe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Vy(e){return e.type.startsWith("tool-")}function yXe(e){return e.type==="dynamic-tool"}function a_(e){return Vy(e)||yXe(e)}function bL(e){return e.type.split("-").slice(1).join("-")}function vXe({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 wXe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,p,m;function g(w){const C=u.message.parts.filter(Vy).find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function b(w){const C=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function x(w){var S;const C=u.message.parts.find(k=>Vy(k)&&k.toolCallId===w.toolCallId),j=w,D=C;C!=null?(C.state=w.state,D.input=j.input,D.output=j.output,D.errorText=j.errorText,D.rawInput=j.rawInput,D.preliminary=j.preliminary,D.providerExecuted=(S=j.providerExecuted)!=null?S:C.providerExecuted,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function y(w){var S;const C=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===w.toolCallId),j=w,D=C;C!=null?(C.state=w.state,D.toolName=w.toolName,D.input=j.input,D.output=j.output,D.errorText=j.errorText,D.rawInput=(S=j.rawInput)!=null?S:D.rawInput,D.preliminary=j.preliminary,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,errorText:j.errorText,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}async function v(w){if(w!=null){const S=u.message.metadata!=null?ZJ(u.message.metadata,w):w;t!=null&&await fL({value:S,schema:t}),u.message.metadata=S}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,w.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const w=u.message.parts.filter(Vy);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:S}=await XJ(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:bL(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:bL(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(bXe(a)){(n==null?void 0:n[a.type])!=null&&await fL({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const S=w.id!=null?u.message.parts.find(C=>w.type===C.type&&w.id===C.id):void 0;S!=null?S.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function SXe({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()}}Ax({prefix:"aitxt",size:24});Ax({prefix:"aiobj",size:24});var CXe=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()})}};Ax({prefix:"aiobj",size:24});var NXe={};iXe(NXe,{object:()=>kXe,text:()=>jXe});var jXe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),kXe=({schema:e})=>{const t=sXe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await XJ(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 Aw({text:n});if(!s.success)throw new mL({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 NI({value:s.value,schema:t});if(!o.success)throw new mL({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}}},EXe=Bf({name:$e(),version:$e()}),kI=Bf({_meta:mr(Wt({}).loose())}),yb=kI,_Xe=Wt({method:$e(),params:mr(kI)}),DXe=Bf({experimental:mr(Wt({}).loose()),logging:mr(Wt({}).loose()),prompts:mr(Bf({listChanged:mr(Sr())})),resources:mr(Bf({subscribe:mr(Sr()),listChanged:mr(Sr())})),tools:mr(Bf({listChanged:mr(Sr())}))});yb.extend({protocolVersion:$e(),capabilities:DXe,serverInfo:EXe,instructions:mr($e())});var MXe=yb.extend({nextCursor:mr($e())}),TXe=Wt({name:$e(),description:mr($e()),inputSchema:Wt({type:ut("object"),properties:mr(Wt({}).loose())}).loose()}).loose();MXe.extend({tools:nu(TXe)});var RXe=Wt({type:ut("text"),text:$e()}).loose(),IXe=Wt({type:ut("image"),data:TJ(),mimeType:$e()}).loose(),QJ=Wt({uri:$e(),mimeType:mr($e())}).loose(),AXe=QJ.extend({text:$e()}),PXe=QJ.extend({blob:TJ()}),OXe=Wt({type:ut("resource"),resource:Ar([AXe,PXe])}).loose();yb.extend({content:nu(Ar([RXe,IXe,OXe])),isError:Sr().default(!1).optional()}).or(yb.extend({toolResult:co()}));var eC="2.0",FXe=Wt({jsonrpc:ut(eC),id:Ar([$e(),bb().int()])}).merge(_Xe).strict(),$Xe=Wt({jsonrpc:ut(eC),id:Ar([$e(),bb().int()]),result:yb}).strict(),LXe=Wt({jsonrpc:ut(eC),id:Ar([$e(),bb().int()]),error:Wt({code:bb().int(),message:$e(),data:mr(co())})}).strict(),zXe=Wt({jsonrpc:ut(eC)}).merge(Wt({method:$e(),params:mr(kI)})).strict();Ar([FXe,zXe,$Xe,LXe]);async function BXe(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 VXe=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 Nf(this.body),l=await Nf(this.headers),u=await Nf(this.credentials),d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...l,...t.headers},credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(r=d==null?void 0:d.api)!=null?r:this.api,h=(d==null?void 0:d.headers)!==void 0?d.headers:{...l,...t.headers},p=(d==null?void 0:d.body)!==void 0?d.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},m=(s=d==null?void 0:d.credentials)!=null?s:u,b=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:dL({"Content-Type":"application/json",...h},`ai-sdk/${gL}`,uL()),body:JSON.stringify(p),credentials:m,signal:e});if(!b.ok)throw new Error((i=await b.text())!=null?i:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await Nf(this.body),a=await Nf(this.headers),l=await Nf(this.credentials),u=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:{...a,...e.headers},credentials:l,requestMetadata:e.metadata})),d=(n=u==null?void 0:u.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=(u==null?void 0:u.headers)!==void 0?u.headers:{...a,...e.headers},h=(r=u==null?void 0:u.credentials)!=null?r:l,m=await((s=this.fetch)!=null?s:globalThis.fetch)(d,{method:"GET",headers:dL(f,`ai-sdk/${gL}`,uL()),credentials:h});if(m.status===204)return null;if(!m.ok)throw new Error((o=await m.text())!=null?o:"Failed to fetch the chat response.");if(!m.body)throw new Error("The response body is empty.");return this.processResponseStream(m.body)}},EI=class extends VXe{constructor(e={}){super(e)}processResponseStream(e){return fZe({stream:e,schema:gXe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},HXe=class{constructor({generateId:e=eZe,id:t=e(),transport:n=new EI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new CXe,this.sendMessage=async(f,h)=>{var p,m,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await BXe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(m=x.role)!=null?m:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const p=f==null?this.state.messages.length-1:this.state.messages.findIndex(m=>m.id===f);if(p===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({state:f="output-available",tool:h,toolCallId:p,output:m,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>a_(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>a_(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=l,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let u=!1,d=!1,f=!1;try{const h={state:vXe({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};h.abortController.signal.addEventListener("abort",()=>{u=!0}),this.activeResponse=h;let p;if(e==="resume-stream"){const g=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(g==null){this.setStatus({status:"ready"});return}p=g}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:h.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const m=g=>this.jobExecutor.run(()=>g({state:h.state,write:()=>{var b;this.setStatus({status:"streaming"}),h.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,h.state.message):this.state.pushMessage(h.state.message)}}));await SXe({stream:wXe({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:m,onError:g=>{throw g}}),onError:g=>{throw g}}),this.setStatus({status:"ready"})}catch(h){if(u||h.name==="AbortError")return u=!0,this.setStatus({status:"ready"}),null;f=!0,h instanceof TypeError&&(h.message.toLowerCase().includes("fetch")||h.message.toLowerCase().includes("network"))&&(d=!0),this.onError&&h instanceof Error&&this.onError(h),this.setStatus({status:"error",error:h})}finally{try{(o=this.onFinish)==null||o.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:u,isDisconnect:d,isError:f})}catch(h){console.error(h)}this.activeResponse=void 0}(i=this.sendAutomaticallyWhen)!=null&&i.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(a=this.lastMessage)==null?void 0:a.id,metadata:t,headers:n,body:r})}};function UXe({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(a_);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function WXe(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 qXe=WXe;const YXe=$c(qXe);var JJ=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Tn=(e,t,n)=>(JJ(e,t,"read from private field"),n?n.call(e):t.get(e)),Bi=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Ol=(e,t,n,r)=>(JJ(e,t,"write to private field"),t.set(e,n),n);function GXe(e,t){return t!=null?YXe(e,t):e}var jo,Hy,Uy,Vm,Hm,Um,Mf,l_,c_,KXe=class{constructor(e=[]){Bi(this,jo,void 0),Bi(this,Hy,"ready"),Bi(this,Uy,void 0),Bi(this,Vm,new Set),Bi(this,Hm,new Set),Bi(this,Um,new Set),this.pushMessage=t=>{Ol(this,jo,Tn(this,jo).concat(t)),Tn(this,Mf).call(this)},this.popMessage=()=>{Ol(this,jo,Tn(this,jo).slice(0,-1)),Tn(this,Mf).call(this)},this.replaceMessage=(t,n)=>{Ol(this,jo,[...Tn(this,jo).slice(0,t),this.snapshot(n),...Tn(this,jo).slice(t+1)]),Tn(this,Mf).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?GXe(t,n):t;return Tn(this,Vm).add(r),()=>{Tn(this,Vm).delete(r)}},this["~registerStatusCallback"]=t=>(Tn(this,Hm).add(t),()=>{Tn(this,Hm).delete(t)}),this["~registerErrorCallback"]=t=>(Tn(this,Um).add(t),()=>{Tn(this,Um).delete(t)}),Bi(this,Mf,()=>{Tn(this,Vm).forEach(t=>t())}),Bi(this,l_,()=>{Tn(this,Hm).forEach(t=>t())}),Bi(this,c_,()=>{Tn(this,Um).forEach(t=>t())}),Ol(this,jo,e)}get status(){return Tn(this,Hy)}set status(e){Ol(this,Hy,e),Tn(this,l_).call(this)}get error(){return Tn(this,Uy)}set error(e){Ol(this,Uy,e),Tn(this,c_).call(this)}get messages(){return Tn(this,jo)}set messages(e){Ol(this,jo,[...e]),Tn(this,Mf).call(this)}};jo=new WeakMap;Hy=new WeakMap;Uy=new WeakMap;Vm=new WeakMap;Hm=new WeakMap;Um=new WeakMap;Mf=new WeakMap;l_=new WeakMap;c_=new WeakMap;var Tf,xL=class extends HXe{constructor({messages:e,...t}){const n=new KXe(e);super({...t,state:n}),Bi(this,Tf,void 0),this["~registerMessagesCallback"]=(r,s)=>Tn(this,Tf)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Tn(this,Tf)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Tn(this,Tf)["~registerErrorCallback"](r),Ol(this,Tf,n)}};Tf=new WeakMap;function eee({experimental_throttle:e,resume:t=!1,...n}={}){const r=N.useRef("chat"in n?n.chat:new xL(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new xL(n));const o="id"in n?n.id:null,i=N.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=N.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=N.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=N.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=N.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return N.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolResult}}function ZXe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function XXe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function QXe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function JXe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function tee(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:JXe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function nee(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 eQe(){var b;const{authToken:e,tokenProps:t}=qe(),n=ee(x=>x.dashboard.aiScopeTables),r=(b=Zw().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=eee({transport:new EI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Pi.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:DW(x)}})}),onToolCall:p,sendAutomaticallyWhen:UXe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function p({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:tee(n||[])}}),x.toolName==="getDashboardContext"){const y=ee.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const m=!["ready","error"].includes(l),g=nee(d);return{sendMessage:s,regenerate:a,isLoading:m,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function ree(){var u;const{authToken:e,tokenProps:t}=qe(),n=(u=Zw().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=un({queryKey:["assistant-profile",n],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function see({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(y8,{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 Pw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(rD,{className:r});case"view":return c.jsx(bc,{className:r});case"materialized view":return c.jsx(uae,{className:r});case"model":return c.jsx(r1,{className:r});case"file":return c.jsx(Ni,{className:r});case"dataset":return c.jsx(sl,{className:r});case"upload":return c.jsx(aD,{className:r});case"url":return c.jsx(D8,{className:r});default:return c.jsx(n1,{className:r})}}const oee=E.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(xa,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(ds.Input,{ref:n,className:J("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));oee.displayName=ds.Input.displayName;const hy=e=>e.label||(e==null?void 0:e.name),yL=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function tQe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=qe(),f=(d==null?void 0:d.type)==="dashboard",[h,p]=N.useState(""),[m,g]=N.useState(""),b=s.filter(C=>{if(!h)return!0;const j=hy(C).toLowerCase(),D=yL(C).toLowerCase(),k=h.toLowerCase();return j.includes(k)||D.includes(k)});N.useEffect(()=>{e||(p(""),g(""))},[e]),N.useEffect(()=>{b.length>0&&!m&&g(hy(b[0]))},[b,m]);const x=()=>{if(!m)return;const C=b.find(j=>hy(j)===m);C&&(o.some(D=>"id"in C&&"id"in D?C.id===D.id:C.name===D.name&&C.connectionId===D.connectionId)||t(C),i(C),r())},y=C=>{(C.key==="Tab"||C.key==="Enter")&&(C.preventDefault(),x())};if(!e)return null;const v=C=>o.some(j=>"id"in C&&"id"in j?C.id===j.id:C.name===j.name&&C.connectionId===j.connectionId),w=o.length===s.length,S=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(IS,{shouldFilter:!1,value:m,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(oee,{placeholder:"Search entities...",value:h,onValueChange:p,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(jr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),a==null||a()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),S&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),l==null||l()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(vt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(AS,{className:"min-h-60",children:[c.jsx(PS,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(jr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(OS,{children:b.map((C,j)=>{const D=v(C),k="id"in C?C.id:`${C.connectionId}-${C.name}`,_=hy(C);return c.jsxs(FS,{value:_,onSelect:()=>{D?n==null||n(C):t(C)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:J("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:Pw(C.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:_}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:yL(C)})]}),D&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx(Rr,{className:"h-3 w-3 text-background"})})]},k)})})]})]})})}const u_=e=>e.name||e.name,nQe=e=>{const t=u_(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 rQe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=N.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(Yn,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[Pw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:u_(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(Cn,{side:"top",className:"max-w-xs",children:nQe(d)})]},h)}),u&&c.jsxs(bn,{open:s,onOpenChange:o,children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(dae,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(Cn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:Pw(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:u_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(vt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function iee(e){return e.type==="dataset"&&e.label||e.name}function sQe(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(ce,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(Fe,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),iee(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(vt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function iQe(e){const{tokenProps:t}=qe(),n=ee(l=>l.authToken)||e;_e(l=>l.selectedConnectionId),_e(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=un({queryKey:["semantic-domains"],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function aQe(e,t){const{tokenProps:n}=qe(),r=ee(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=un({queryKey:["datasets",e],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function lQe(e){var g,b;const{tokenProps:t}=qe(),n=ee(x=>x.authToken)||e,{connections:r}=Ai(e),s=_e(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:p}=un({queryKey:["databases",s],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),m=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:m||[],refetch:p,label:l}}function cQe(e){var g;const{tokenProps:t}=qe(),n=ee(b=>b.authToken)||e,{connections:r}=Ai(e),s=_e(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=_e(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:p}=un({queryKey:["schemas",s,o],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),m=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:m||[],refetch:p,label:l}}function aee(e){const{tokenProps:t}=qe(),n=ee(h=>h.authToken)||e,{connections:r}=Ai(e),s=_e(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=un({queryKey:["dataModels",s],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function uQe(){var S,C,j;const e=_e(D=>D.card.dataSource);_e(D=>D.actions.updateDirectSource);const t=_e(D=>D.actions.updateDataSource),[n,r]=N.useState(""),{selectedConnection:s,error:o}=Ai(),{databases:i,isPending:a,error:l,label:u}=lQe(),{schemas:d,isPending:f,error:h,label:p}=cQe(),{error:m}=aee(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=p==null?void 0:p.toLowerCase(),v=D=>{e&&t({...e,dbSelection:{database:D,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=D=>{var _;if(!((_=e==null?void 0:e.dbSelection)!=null&&_.database))return;const k=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...k,schema:D},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||m)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[p,": ",h.message]}),m&&c.jsxs("li",{children:["Data Models: ",m.message]})]})]})}),c.jsx(oe,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:u}),c.jsxs(rt,{value:((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)||"",onValueChange:v,disabled:a,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(et,{children:i.map(D=>c.jsx(pe,{className:"hover:bg-muted",value:D.id,children:D.name},D.id))})]})]}),((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:p}),c.jsxs(rt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(et,{children:d.map(D=>c.jsx(pe,{className:"hover:bg-muted",value:D.id,children:D.name},D.id))})]})]})]})]})}function dQe(){const e=_e(l=>l.card.dataSource),t=_e(l=>l.actions.updateDataSource),[n,r]=N.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(aD,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Ni,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},l.id))})]})]})}function fQe(){const e=_e(f=>f.card.dataSource),t=_e(f=>f.actions.updateDataSource),[n,r]=N.useState(""),[s,o]=N.useState(""),[i,a]=N.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(p=>p.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(Nn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(Nn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[c.jsx("option",{value:"api",children:"API Endpoint"}),c.jsx("option",{value:"csv",children:"CSV File"}),c.jsx("option",{value:"json",children:"JSON File"})]})]}),c.jsxs(oe,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(jr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(n1,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},f.id))})]})]})}function hQe(e,t){var y,v;const{tokenProps:n}=qe(),r=ee(w=>w.authToken)||t,{connections:s}=Ai(t),o=_e(w=>{var S,C;return(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.connectionId}),i=_e(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.database}),a=_e(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:p,isLoading:m,error:g,refetch:b}=un({queryKey:[e,o,i,a],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(w=>{var S;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(S=w==null?void 0:w.table_type)==null?void 0:S.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:p,isLoading:m,error:g,entities:x||[],refetch:b,label:d}}function Ow({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(pd,{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 pQe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Ai(),[i,a]=N.useState(""),[l,u]=N.useState(""),[d,f]=N.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=ur(),{entities:m,isLoading:g,error:b}=hQe("table"),{dataModels:x,isPending:y,error:v}=aee(),w=_=>{const M=s.find(O=>O.id===_);if(!M)return;const R=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:_,connectionType:M.type,mode:R,dbSelection:{database:"",schema:"",entityType:"table"}}),p(_)},S=_=>{var T,I;const M=n||[],R=M.some(F=>F.name===_.name&&F.type===_.type);let O;if(R)O=M.filter(F=>!(F.name===_.name&&F.type===_.type));else{const F={connectionId:e.connectionId,connectionType:e.connectionType,type:_.type,dbObjectType:_.dbObjectType,database:((T=e.dbSelection)==null?void 0:T.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:_.name,dialect:_.dialect};O=[...M,F]}t==null||t(O)},C=_=>{const M=n||[],R=M.some(T=>T.type==="model"&&T.name===_.name);let O;R?O=M.filter(T=>!(T.type==="model"&&T.name===_.name)):O=[...M,_],t==null||t(O)},j=m.filter(_=>_.name.toLowerCase().includes(i.toLowerCase())),D=x.filter(_=>_.name.toLowerCase().includes(l.toLowerCase())),k=N.useCallback(()=>{if(!t)return;const _=n||[];let M=[..._];if(d==="tables"){const O=j.filter(T=>!_.some(I=>I.name===T.name&&I.type==="table")).map(T=>{var I,F;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:T.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((F=e.dbSelection)==null?void 0:F.schema)||"",name:T.name,dialect:T.dialect}});M=[..._,...O]}else if(d==="datamodels"){const R=D.filter(O=>!_.some(T=>T.name===O.name&&T.type==="model"));M=[..._,...R]}t(M)},[d,j,D,n,e,t]);return N.useEffect(()=>{r&&r(k)},[r,k]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(rt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(et,{children:s.map(_=>c.jsx(pe,{className:"hover:bg-muted",value:_.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(sl,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:_.name}),c.jsx(Fe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:_.type})]})},_.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(dQe,{}),e.connectionType==="url"&&c.jsx(fQe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(uQe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(cs,{defaultValue:"tables",value:d,onValueChange:_=>f(_),className:"w-full",children:[c.jsxs(Wr,{className:"grid w-full grid-cols-2",children:[c.jsxs(Ht,{value:"tables",children:["Tables & Views (",j.length,")"]}),c.jsxs(Ht,{value:"datamodels",children:["Data Models (",D.length,")"]})]}),c.jsxs(Gn,{value:"tables",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search tables and views...",value:i,onChange:_=>a(_.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(Ow,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(_=>{const M=n.some(R=>R.name===_.name&&R.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(_),children:[c.jsx(dn,{id:`table-${_.name}`,checked:M,onCheckedChange:()=>S(_),onClick:R=>R.stopPropagation(),disabled:g}),c.jsxs(ce,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[_.name,_.dbObjectType==="view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),_.dbObjectType==="materialized view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},_.name)})})]}),c.jsxs(Gn,{value:"datamodels",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search data models...",value:l,onChange:_=>u(_.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(Ow,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):D.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):D.map(_=>{const M=n.some(R=>R.name===_.name&&R.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(_),children:[c.jsx(dn,{id:`dataModel-${_.name}`,checked:M,onCheckedChange:()=>C(_),onClick:R=>R.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer",children:_.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:_.description})]})]},_.name)})})]})]})})})]})]})]})}function mQe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var S;const[l,u]=N.useState(""),d=N.useCallback(C=>{const j={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:C};t({...j})},[e,t]);N.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:p}=iQe(),m=o?f.filter(C=>s.includes(C.id)):f,{datasets:g,isPending:b,error:x}=aQe(e==null?void 0:e.semanticDomainId),y=C=>{const j=r||[],D=j.some(_=>_.id===C.id&&_.type==="dataset");let k;if(D)k=j.filter(_=>!(_.id===C.id&&_.type==="dataset"));else{const _={id:C.id,datasetType:C.type,name:C.name||C.table,label:C.label,domainId:C.domainId,description:C.description,database:C.database,schema:C.schema,type:"dataset",connectionId:C.connectionId,connectionType:C.connectionType,dialect:C.dialect,datamodelId:C.datamodelId,sql:C.sql};k=[...j,_]}n==null||n(k)},v=g.filter(C=>C.name.toLowerCase().includes(l.toLowerCase())),w=N.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const C=r||[],D=v.filter(_=>!C.some(M=>M.id===_.id&&M.type==="dataset")).map(_=>({id:_.id,datasetType:_.type,name:_.name||_.table,label:_.label,domainId:_.domainId,description:_.description,database:_.database,schema:_.schema,type:"dataset",connectionId:_.connectionId,connectionType:_.connectionType,dialect:_.dialect,datamodelId:_.datamodelId,sql:_.sql})),k=[...C,...D];n(k)},[v,r,e==null?void 0:e.semanticDomainId,n]);return N.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(rt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((S=m.find(C=>C.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:S.label)||"Select semantic domain"})}),c.jsx(et,{children:m.map(C=>c.jsx(pe,{className:"hover:bg-muted",value:C.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:C.label}),c.jsx("span",{className:"text-xs",children:C.description})]})},C.id))})]}),p&&c.jsx(Ow,{title:"Error loading semantic models",message:p.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search datasets...",value:l,onChange:C=>u(C.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(Ow,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(C=>{const j=r.some(D=>D.id===C.id&&D.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(C),children:[c.jsx(dn,{id:`dataset-${C.id}`,checked:j,onCheckedChange:()=>y(C),onClick:D=>D.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer font-medium",children:C.label||C.name}),c.jsx("span",{className:"text-xs text-gray-500",children:C.description})]})]},C.label||C.name)})})]})]})]})}function _I({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=qe(),{allowedSemanticDomains:i}=o,[a,l]=N.useState([]),{updateDataSource:u}=ur(),d=ee(M=>M.isVisualEditing),f=ee(M=>M.dashboard.aiContext),{setAiContext:h}=Yt(),p=N.useRef(null),[m,g]=N.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=N.useCallback(M=>{const R=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:R,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...R!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=N.useCallback(M=>{u({...n,...M})},[n,u]);N.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),N.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),N.useEffect(()=>{e?l(s||[]):(p.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const S=M=>{const R=a.filter(O=>!(O.name===M.name&&O.type===M.type));l(R)},C=()=>{l([])},j=N.useCallback(M=>{l(M)},[]),D=N.useCallback(()=>{p.current&&p.current()},[]),k=N.useCallback(M=>{p.current=M,g(!0)},[]);function _(){var M,R;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const O=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,T=(R=a==null?void 0:a[0])==null?void 0:R.connectionType;u({...n,connectionId:O,connectionType:T,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsx(Vr,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Hr,{className:"flex-shrink-0",children:[c.jsx(Ur,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(Rs,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(cs,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(Wr,{className:"grid w-full grid-cols-2",children:[c.jsx(Ht,{value:"database",children:"Direct Source"}),c.jsx(Ht,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(mQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:k}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(pQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:k})]})}),c.jsx(oQe,{selectedEntities:a,onDeselectEntity:S}),c.jsx(Ts,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(oe,{variant:"outline",onClick:D,disabled:!m,children:"Select All"}),c.jsx(oe,{variant:"outline",onClick:C,disabled:a.length===0,children:"Clear All"}),c.jsxs(oe,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(vt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(oe,{onClick:_,children:[c.jsx(Rr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function gQe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=N.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=$a-n;if(l.length>u){Le.error(`You can only attach ${$a} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=HQ(l);if(f.forEach(({file:h,error:p})=>{Le.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>mI(p)));e(h)}catch(h){console.error("Failed to process files:",h),Le.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>=$a}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=$a,title:n>=$a?`Maximum ${$a} files allowed`:"Attach files",children:c.jsx(Q_,{className:"h-4 w-4 text-muted-foreground"})})]})}function bQe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=N.useState(!1),a=N.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=N.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),p=f.clientX,m=f.clientY;(p<h.left||p>=h.right||m<h.top||m>=h.bottom)&&i(!1)},[]),u=N.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=N.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const p=$a-r;if(h.length>p){Le.error(`You can only attach ${$a} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=HQ(h);if(g.forEach(({file:b,error:x})=>{Le.error(`${b.name}: ${x}`)}),m.length>0)try{const b=await Promise.all(m.map(x=>mI(x)));t(b),Le.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),Le.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:J("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(aD,{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:[$a-r," slot(s) available"]})]})})]})}const DI=N.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=N.useState(!1),[h,p]=N.useState(!1),[m,g]=N.useState(!1),b=N.useRef(null),x=Ip();SNe(),wNe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:S}=H1(),{queueMessage:C}=Ap(),{addFileAttachment:j,removeFileAttachment:D,clearFileAttachments:k,getFileAttachments:_}=YM(),M=qM(l),R=_e(H=>H.card.dataSource),O=ee(H=>H.dashboard.aiContext),T=ee(H=>{var q;return(q=H.dashboard.aiContext)==null?void 0:q.selectedEntities});N.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=N.useCallback(()=>{const H=b.current;if(H){if(!e||e.length===0){H.style.height="10px";return}H.style.height="auto";const q=Math.min(Math.max(H.scrollHeight,10),200);H.style.height=`${q}px`}},[e]);N.useEffect(()=>{I()},[I]),N.useEffect(()=>{const H=setTimeout(()=>{I()},0);return()=>clearTimeout(H)},[I]);const F=()=>{const H=e.trim();!H&&M.length===0||(a!=="ready"?(C(l,H,M),t(""),k(l)):r({preventDefault:()=>{}}))},z=H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),F()),H.key==="@"&&(K(),f(!0))},B=N.useCallback(H=>{const q=TWe(H.nativeEvent);q.length>0&&(H.preventDefault(),q.forEach(async X=>{const Z=await mI(X);j(l,Z)}))},[j,l]),$=N.useCallback(H=>{H.forEach(q=>{j(l,q)})},[j,l]),P=N.useCallback(H=>{H.forEach(q=>{j(l,q)})},[j,l]),V=N.useCallback(H=>{D(l,H)},[D,l]),L=H=>{if(x.selectedEntities.some(X=>X.id&&X.id===H.id||X.name===H.name)){const X=x.selectedEntities.filter(Z=>!(Z.id&&Z.id===H.id||Z.name===H.name));y({selectedEntities:X})}else{const X=[...x.selectedEntities,H];y({selectedEntities:X})}},A=H=>{L(H)},W=H=>{var Z;if(!x.selectedEntities.some(G=>G.id&&G.id===H.id||G.name===H.name)){const G=[...x.selectedEntities,H];y({selectedEntities:G})}const X="label"in H?H.label:H.name;t(e+`@${X} `),f(!1),(Z=b.current)==null||Z.focus()},U=H=>{const q=x.selectedEntities.filter(G=>!(G.id&&G.id===H.id||G.name===H.name));y({selectedEntities:q});const Z=`@${"label"in H?H.label:H.name}`;e.includes(Z)&&t(e.replace(Z,"").trim())},Y=H=>{const q=new Set(H.map(G=>G.id||G.name)),X=x.selectedEntities.filter(G=>!q.has(G.id||G.name));y({selectedEntities:X});let Z=e;H.forEach(G=>{const ne=`@${"label"in G?G.label:G.name}`;Z=Z.replace(ne,"").trim()}),t(Z)},K=N.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})},[x.selectedEntities.length,O==null?void 0:O.selectedEntities,y]);return c.jsxs(bQe,{onFilesDropped:$,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(rQe,{entities:x.selectedEntities,availableEntities:T||[],onRemoveEntity:U,onRemoveEntities:Y}),M.length>0&&c.jsx(RWe,{files:M,onRemove:V,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:z,onPaste:B,onFocus:()=>{I(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(Ns,{open:d,onOpenChange:H=>{H&&K(),f(H)},children:[c.jsx(js,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(sae,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(ks,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:H=>H.preventDefault(),children:c.jsx(tQe,{isOpen:!0,onSelect:L,onDeselect:A,onClose:()=>{var H;f(!1),(H=b.current)==null||H.focus()},availableEntities:T||[],selectedEntities:x.selectedEntities,onTabComplete:W,onSelectAll:()=>{T&&y({selectedEntities:T})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),p(!0)}})})]}),c.jsx(gQe,{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:F,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(O8,{className:"size-4"})})]})]})]}),c.jsx(_I,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:p,dataSource:R||XS,dialogMode:"aiContext"})]})});DI.displayName="ChatInputWithContext";function lee({assistantType:e,className:t}){const n=MW(e),{removeFromQueue:r}=Ap();return n.length===0?null:c.jsxs("div",{className:J("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(dl,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>c.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(vt,{className:"h-3 w-3"})})]})},s.id))})]})}function cee({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=MW(e),{dequeueMessage:o}=Ap();N.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function uee(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=N.useRef(null),[a,l]=N.useState(!0),[u,d]=N.useState(!0),[f,h]=N.useState(!1),[p,m]=N.useState(0),g=N.useRef(0),b=N.useRef(!1),x=N.useRef(0),y=N.useRef(a),v=N.useRef(),w=N.useRef({key:null,count:0,length:0}),S=N.useCallback(()=>{const k=i.current;return k?k.scrollHeight-k.scrollTop-k.clientHeight:0},[]),C=N.useCallback((k={})=>{if(!i.current)return;const{force:M=!1,instant:R=!1}=k;if(!M&&!y.current||!a&&!M)return;const O=R||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!M&&!y.current){b.current=!1,v.current=void 0;return}const T=i.current;if(!T){b.current=!1,v.current=void 0;return}const I=T.scrollHeight;O==="smooth"&&"scrollTo"in T?T.scrollTo({top:I,behavior:O}):T.scrollTop=I,g.current=T.scrollTop,d(!0),l(!0),y.current=!0,h(!1),m(0),b.current=!1,v.current=void 0})},[r,a]),j=N.useCallback(()=>{const k=i.current;if(!k)return;const _=g.current,M=k.scrollTop,R=M-_;if(g.current=M,R<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const O=S()<=n;d(O),l(O),y.current=O,O&&(h(!1),m(0))},[S,n]),D=N.useCallback(()=>{m(0),h(!1)},[]);return N.useEffect(()=>{y.current=a},[a]),N.useEffect(()=>{const k=i.current;if(!k||!e||e.length===0){h(!1),m(0),w.current={key:null,count:0,length:0},g.current=k?k.scrollTop:0,x.current=k?k.scrollHeight:0;return}g.current=k.scrollTop,x.current=k.scrollHeight;const _=w.current,M=e[e.length-1],R=(M==null?void 0:M.id)??(M==null?void 0:M.messageId)??(M==null?void 0:M.createdAt)??(M==null?void 0:M.timestamp)??e.length,O=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce(($,P)=>P?typeof P=="string"?$+P.length:typeof P.text=="string"?$+P.text.length:typeof P.content=="string"?$+P.content.length:typeof P.value=="string"?$+P.value.length:$:$,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,T=e.length>_.count,I=R!==_.key,F=O>_.length,z=s&&(M==null?void 0:M.role)==="assistant"&&!T&&(I||F),B=o||z;if(w.current={key:R,count:e.length,length:O},a&&(T||I||F||B)){C({force:!1,instant:B});return}if(!a&&T){const $=e.length-_.count;$>0&&(h(!0),m(P=>P+$))}else!a&&F&&(h(!0),m($=>$>0?$:1))},[e,C,a,s,o]),N.useEffect(()=>{C({instant:!0})},[C]),N.useEffect(()=>{if(typeof ResizeObserver>"u")return;const k=i.current;if(!k)return;x.current=k.scrollHeight;const _=new ResizeObserver(()=>{const M=i.current;if(!M)return;const R=x.current,O=M.scrollHeight;x.current=O,!b.current&&y.current&&O>R&&C({force:!1,instant:!0})});return _.observe(k),()=>{_.disconnect()}},[C]),N.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:p,scrollToBottom:C,handleScroll:j,resetNewMessageCount:D}}function dee(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=N.useState(r),a=N.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=N.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=N.useCallback(()=>{i(r)},[r]);return N.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function fee(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:UQ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const xQe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function yQe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=N.useState(!1),[a,l]=N.useState(Ww),[u,d]=N.useState(!1),[f,h]=N.useState(!1),[p,m]=N.useState(!1),g=n??p,{isLocalDev:b,isConsoleMode:x}=dp(),y=N.useRef(null);ee(Ve=>Ve.dashboard.aiScopeTables),ee(Ve=>Ve.isDashboardEditing);const v=ee(Ve=>Ve.selectedSheetId),{setDataSource:w}=ur(),{addFrame:S,setSelectedFrameId:C,setIsDashboardEditing:j}=Yt(),D=Ip(),{setCurrentAIContext:k,updateSelectedEntities:_,setReasoningEffort:M,setShowReasoning:R}=H1(),{clearQueue:O}=Ap(),{clearFileAttachments:T,getFileAttachments:I}=YM(),F=qM("dashboard"),z=ee(Ve=>Ve.dashboard.aiContext),B=_e(Ve=>Ve.card.dataSource),{assistantProfile:$}=ree(),P=ee(Ve=>Ve.handleOpenAssistantProfile),{sendMessage:V,isLoading:L,messages:A,setMessages:W,status:U,stop:Y,errorMessage:K,clearError:H}=eQe(),q=N.useCallback(Ve=>{r==null||r(Ve),n===void 0&&m(Ve)},[n,r]),X=N.useCallback(()=>{q(!g)},[g,q]);N.useEffect(()=>{if(!g)return;function Ve(Ue){Ue.key==="Escape"&&q(!1)}return window.addEventListener("keydown",Ve),()=>{window.removeEventListener("keydown",Ve)}},[g,q]);const[Z,G]=N.useState(""),Q=Ve=>{G(Ve.target.value)};function ne({sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ze,python:ve,cardConfig:ke,dataSource:Te}){if(console.log("handleAddNewFrame",{sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ze,python:ve,cardConfig:ke,dataSource:Te}),!v)return;const ze={id:Mr(),title:ht||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ze==="horizontalBar"?"y":"x"}},type:Ze,sql:Ve,python:ve,dataSource:Te,config:ke,connectionId:He},nt={id:Mr(),cards:[ze],activeCardId:ze.id};j(!0),S(v,nt,"end"),C(nt.id)}const ae=Ve=>{Ve.preventDefault();const Ue=Z.trim();if(!Ue&&F.length===0)return;const ht=[];Ue&&ht.push({type:"text",text:Ue}),F.forEach(He=>{He.data&&ht.push({type:"file",mediaType:He.type,filename:He.name,url:`data:${He.type};base64,${He.data}`})}),V({role:"user",parts:ht}),G(""),T("dashboard"),se({force:!0})};N.useEffect(()=>{var Ve;e&&((Ve=y.current)==null||Ve.focus())},[e]),cee({assistantType:"dashboard",status:U,isLoading:L,sendMessage:V});const{hasActiveTools:ie}=fee(A),{visibleMessages:fe,hasMoreMessages:xe,totalMessageCount:Ce,loadMoreMessages:je,resetMessageWindow:de}=dee(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Re,isAtBottom:Oe,hasNewMessages:mt,newMessageCount:be,scrollToBottom:se,handleScroll:ue,resetNewMessageCount:we}=uee(fe,{threshold:50,behavior:"smooth",isStreaming:L});function Se(Ve){Ke();const Ue={role:"user",parts:[{type:"text",text:Ve.title+" "+Ve.subtitle}]};V(Ue)}function Pe(Ve){Ke(),V({role:"user",parts:[{type:"text",text:Ve}]})}function Qe(Ve){Ke(),V({role:"user",parts:[{type:"text",text:Ve}]}),se({force:!0})}const Nt=N.useCallback(async()=>{const Ve=JSON.stringify(A??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Ve),Le.success("Conversation copied")}catch(Ue){console.error("Failed to copy conversation",Ue),Le.error("Unable to copy conversation")}},[A]);function Ke(){D.selectedEntities.length===0&&k({selectedEntities:(z==null?void 0:z.selectedEntities)||[]})}const $t=(Z==null?void 0:Z.length)===0&&(A==null?void 0:A.filter(Ve=>Ve.role==="user").length)===0;function Ne(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Dt(){return c.jsxs(cp,{children:[c.jsx(up,{asChild:!0,children:c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(ep,{className:"size-3.5"})})}),c.jsxs(Ud,{align:"end",children:[c.jsx(Kf,{children:"Options"}),c.jsx(bd,{}),c.jsx(Gm,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Gm,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Gm,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const hn=c.jsxs("div",{"data-role":"dashboard-assistant",className:J("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ne(),P&&c.jsx(oe,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:P,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&Dt(),a&&c.jsx(oe,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Nt,children:"Copy Conversation"}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:X,children:g?c.jsx(X_,{className:"size-4"}):c.jsx(s1,{className:"size-4"})}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),O("dashboard"),H(),de()},children:c.jsx(o1,{className:"size-4"})}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(vt,{className:"size-4"})})]})]}),c.jsxs(yl,{"data-role":"dashboard-assistant-scroll-area",ref:Re,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:ue,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[xe&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:je,className:"text-xs",children:["Load ",Math.min(5,Ce-fe.length)," ","more messages (",Ce-fe.length," ","hidden)"]})}),c.jsx(qQ,{showTools:a,showSystemMessage:u,messages:fe,onAddToDashboard:ne,onQuickReply:Qe,disableQuickReplies:L}),!ie&&c.jsx(WQ,{status:U,errorMessage:K})]}),c.jsx(Zo,{orientation:"horizontal"})]}),e&&!Oe&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{se({force:!0}),we()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(Ys,{className:"h-4 w-4"}),mt&&be>0&&c.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:be>9?"9+":be})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&$t&&c.jsx(YQ,{onClick:Se,placeholders:xQe}),c.jsx("div",{children:$t&&$&&c.jsx(see,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Pe})}),c.jsx(lee,{assistantType:"dashboard",className:"mb-3"}),c.jsx(DI,{ref:y,setInput:G,stop:Y,input:Z,handleInputChange:Q,handleSubmit:Ve=>{Ke(),ae(Ve),se({force:!0})},isLoading:L,status:U,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(_I,{incomingSelectedEntities:(z==null?void 0:z.selectedEntities)||[],open:f,onOpenChange:h,dataSource:B||XS,dialogMode:"aiContext"})]});return g&&s?In.createPortal(c.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:c.jsx("div",{className:"flex h-full w-full",children:hn})}),s):hn}function vQe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Yt(),o=ee(d=>d.dashboard.sheets),a=ee(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=ee(d=>d.isDashboardEditing),u=ee(d=>d.isVisualEditing);N.useEffect(()=>{if(!l||u)return;async function d(p){const m=p.ctrlKey||p.metaKey;m&&p.key==="c"?(await f(),Le.success("Card copied to clipboard"),p.preventDefault()):m&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText();try{const m=JSON.parse(p);if(m!=null&&m.id){const g=tR(m),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),Le.success("Card pasted from clipboard")}}catch(m){console.error("Failed to parse clipboard contents: ",m)}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function wQe(e,t){switch(e.interactionMode){case"drillToDetail":SQe(e,t);break;case"drillThrough":CQe(e,t);break;case"drillToURL":NQe(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 SQe(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 CQe(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 NQe(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 jQe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsxs(Vr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Hr,{children:[c.jsx(Ur,{children:i||"Insight Detail"}),c.jsx(Rs,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(oZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(aZ,{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 kQe(){const e=Lt(w=>w.interactionStates),t=Lt(w=>w.setInteractionState),n=Lt(w=>w.clearLastInteractionEvent),r=Lt(w=>w.replaceCardWithInsight),s=Lt(w=>w.setPendingDrillThrough),o=Lt(w=>w.pendingDrillThrough),i=Lt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Yt(),{selectDashboard:u}=Rb(),d=ee(w=>w.dashboard),f=ee(w=>w.filterValues),{data:h,isLoading:p}=Ffe((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[m,g]=N.useState({open:!1,insightId:""}),b=lZ(m.insightId,{enabled:m.open&&!!m.insightId}),x=N.useRef(new Set),y=N.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:S,contextMode:C})=>{g({open:!0,insightId:w,filters:S,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:C})},replaceCardContent:({cardId:w,insightId:S,filters:C,contextMode:j})=>{r(w,S,C,j)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:D})=>{const _={sourceCardId:ra,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...Ao(),appliedClickFilters:[_],contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:D};t(ra,M)}}),[a,r,f,l,d,s,t]);N.useEffect(()=>{Object.entries(e).forEach(([w,S])=>{if(S!=null&&S.lastInteractionEvent){const C=S.lastInteractionEvent,j=`${w}-${C.interactionMode}-${C.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{wQe(C,y)}catch(D){console.error("Error executing interaction event:",D)}finally{n(w),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),N.useEffect(()=>{if(!(!o||!h||p))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,p,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(jQe,{open:m.open,onOpenChange:v,insightId:m.insightId,filters:m.filters,filterDefinitions:m.filterDefinitions,contextMode:m.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&p&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(On,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function EQe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=_Qe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function _Qe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function DQe(e){return e?`Back to ${e}`:"Back"}function MQe(){var x,y,v,w,S;const e=Lt(C=>C.interactionStates[ra]),t=ee(C=>C.actions.goBackFromDrill),n=ee(C=>C.actions.clearDrillContext),{selectDashboard:r}=Rb(),[s,o]=N.useState({x:16,y:16}),[i,a]=N.useState(!1),l=N.useRef({x:0,y:0});N.useEffect(()=>{if(!i)return;const C=D=>{o({x:D.clientX-l.current.x,y:D.clientY-l.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",C),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:w.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((S=e.appliedClickFilters)!=null&&S.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(C){console.error("[DrillBack] Error during back navigation:",C)}},m=()=>{n()},g=C=>{C.target.closest("button")||(a(!0),l.current={x:C.clientX-s.x,y:C.clientY-s.y})};EQe(f);const b=DQe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((C,j)=>{const D=C.field.label||C.field.name,k=String(C.value);return c.jsxs(Fe,{variant:"secondary",className:"pointer-events-none text-xs",children:[D," = ",k]},j)})})]}),c.jsx(oe,{variant:"ghost",size:"sm",onClick:m,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(vt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(oe,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(o8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function hee(){var G;const{showAssistant:e,tokenProps:t}=qe(),{preferences:n,isConsoleMode:r}=dp(),s=((G=n==null?void 0:n.cardDisplay)==null?void 0:G.mode)==="print",o=N.useRef(null),i=N.useRef(null),[a,l]=N.useState(!1),u=nd(Q=>Q.setFullscreen),d=nd(Q=>Q.setPanelOpen),f=nd(Q=>Q.setContainer),h=kW("dashboard"),p=EW(),m=_W("dashboard"),g=h.isOpen,b=p==="dashboard",x=ee(Q=>Q.isVisualEditing),y=ee(Q=>Q.themeStyle),v=ee(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.sheets}),w=ee(Q=>Q.isDashboardEditing),S=ee(Q=>Q.selectedSheetId),C=ee(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.id}),j=ee(Q=>Q.isDashboardPanelOpen),D=ee(Q=>Q.actions.setIsDashboardPanelOpen),{getDefaultSheetId:k,setDefaultSheetId:_,clearDefaultSheetId:M}=L6(C),[R,O]=N.useState(null);v1(At.DASHBOARD);const{setSelectedSheetId:T,setSheetTitle:I,addSheet:F,setSheets:z}=Yt();vQe(i);const{setActiveAssistantType:B}=H1();N.useEffect(()=>{if(C){const Q=k();O(Q)}},[C,k]),N.useEffect(()=>{g?B("dashboard"):p==="dashboard"&&u(null)},[g,B,p,u]);function $(Q){var ne,ae;Q?((ne=o.current)==null||ne.resize(40),d("dashboard",!0),B("dashboard")):(d("dashboard",!1),u(null),(ae=o.current)==null||ae.resize(0),B(null))}function P(){const Q={id:Mr(),title:"New Sheet"};F(Q),T(Q.id)}function V(Q,ne){if(!C)return;R===Q?(M(),O(null),Le.success("Default sheet cleared")):(_(Q),O(Q),Le.success(`"${ne}" set as default sheet`))}function L(Q){Q<1?(d("dashboard",!1),u(null),B(null)):(g||d("dashboard",!0),B("dashboard"))}function A(){return(y==null?void 0:y.canvasTheme)==="muted"||!(y!=null&&y.canvasTheme)?"hsl(var(--semaphor-muted))":(y==null?void 0:y.canvasTheme)==="clear"?"":y==null?void 0:y.canvasTheme}const W=(Q,ne)=>{Q.dataTransfer.setData("tabIndex",ne.toString())},U=Q=>{Q.preventDefault()},Y=(Q,ne)=>{const ae=Q.dataTransfer.getData("tabIndex");if(ae===ne.toString())return;const ie=Array.from(v||[]),[fe]=ie.splice(parseInt(ae),1);ie.splice(ne,0,fe),z(ie)},K=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail;function H(){var Q,ne;if(v&&v.length>1||w)return c.jsxs(Wr,{role:"tab-list",className:"flex h-11 items-center justify-start gap-2 rounded-none border-b border-b-muted bg-transparent px-2.5 py-3",children:[r&&K&&c.jsx(oe,{variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{D(!j)},className:"h-8 p-2",children:j?c.jsx(b8,{className:"h-4 w-4"}):c.jsx(x8,{className:"h-4 w-4"})}),v==null?void 0:v.map((ae,ie)=>{const fe=S===ae.id,xe=R===ae.id;return c.jsxs(Ht,{draggable:!0,onDragStart:Ce=>W(Ce,ie),onDragOver:U,onDrop:Ce=>Y(Ce,ie),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>T(ae.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:ae.id,children:[c.jsx(Jg,{enabled:w&&fe,text:ae.title,onSave:Ce=>I(ae.id,Ce),children:ae.title},ae.id),!w&&fe&&c.jsx("div",{title:xe?"Clear default sheet":"Set as default sheet",children:c.jsx(nD,{className:J("ml-1 size-3 cursor-pointer transition-all",xe?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:Ce=>{Ce.stopPropagation(),V(ae.id,ae.title||"Sheet")}})}),w&&fe&&v.length>1&&c.jsx(vt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},ae.id)}),w&&c.jsx("div",{style:{borderRadius:(ne=(Q=y==null?void 0:y.chart)==null?void 0:Q.options)==null?void 0:ne.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:P,children:c.jsx(jr,{className:"size-3"})})]})}function q(){return c.jsx("div",{ref:i,style:{},className:"grow",children:v==null?void 0:v.map(Q=>c.jsx(Gn,{style:{backgroundColor:A()},className:J("mt-0",{}),value:Q.id,children:c.jsx(q6e,{sheet:Q})},Q.id))})}function X(){var Q;return c.jsxs(cs,{"data-role":"dashboard-tabs-container",className:J("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:ne=>{T(ne)},value:S||((Q=v==null?void 0:v[0])==null?void 0:Q.id),children:[H(),c.jsx(yl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:q()}),c.jsx(j8e,{open:a,setOpen:l})]})}const Z=N.useCallback(Q=>{f("dashboard",Q)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(kQe,{}),c.jsx(MQe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(_X,{className:J("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(BE,{children:X()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(N8e,{open:g,onTabClick:$,withHandle:!0}),c.jsx(BE,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:L,defaultSize:g?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(yQe,{open:g,setOpen:$,isFullscreen:b,onFullscreenChange:Q=>u(Q?"dashboard":null),fullscreenContainer:m})})})]})]}),c.jsx("div",{ref:Z,className:J("absolute inset-0",!b&&"pointer-events-none")}),e===!0&&!s&&!g&&!x&&c.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:c.jsx(oe,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>$(!0),title:"Open Assistant",children:c.jsx(tD,{className:"h-5 w-5"})})})]})]}):null}function MI({children:e}){return c.jsx(wa,{style:{height:"100%",width:"100%"},children:c.jsx(ise,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(Yn,{delayDuration:0,children:e})})})}function pee({children:e,preferences:t}){const{currentUser:n}=Ms(),r=N.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return c.jsx(D9.Provider,{value:r,children:c.jsx(SR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function mee(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(wl,{FallbackComponent:dS,children:c.jsx(L_,{dashboardProps:e,children:c.jsx(MI,{children:c.jsx(pee,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(GM,{...e,type:"dashboard",children:c.jsx(hee,{})})})})})})})}function TI(e){const{tokenProps:t,authToken:n}=qe(),r=t==null?void 0:t.apiServiceUrl;return un({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return Vn(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function gee(e,t,n){if(t==="source")return{isValid:!0};const r=Ks(e.dataType);if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function bee(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 xee=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=TI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=ur(),h=_e(T=>T.card.type),p=e==null?void 0:e.id,m=N.useCallback(T=>{if(!(e!=null&&e.config))return[];switch(T){case"groupBy":return(e.config.groupByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,dateFormat:I.dateFormat,customFormat:I.customFormat,granularity:I.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,direction:I.direction}));case"source":return[];default:return[]}},[e]),g=N.useCallback((T,I)=>{if(p)switch(T){case"groupBy":{r(p,{groupByColumns:I});break}case"metrics":{r(p,{metricColumns:I});break}case"pivotBy":{r(p,{pivotByColumns:I});break}case"sortBy":{r(p,{sortByColumns:I});break}}},[p,r]),b=N.useCallback((T,I,F)=>{if(!p)return;const B=m(T)[I];if(B)switch(T){case"groupBy":s(p,B.id,{label:F});break;case"metrics":o(p,B.id,{label:F});break;case"pivotBy":i(p,B.id,{label:F});break;case"sortBy":a(p,B.id,{label:F});break}},[p,m,s,o,i,a]),x=N.useCallback((T,I)=>{if(!p)return;const z=m("metrics")[T];z&&o(p,z.id,{aggregate:I,label:sU(z.name,I)})},[p,m,o]),y=N.useCallback((T,I,F)=>{if(!p)return;const B=m("groupBy")[T];if(!B)return;const $={dateFormat:I};I==="custom"&&F?$.customFormat=F:$.customFormat=void 0,s(p,B.id,$)},[p,m,s]),v=N.useCallback((T,I)=>{if(!p)return;const z=m("groupBy")[T];z&&s(p,z.id,{granularity:I})},[p,m,s]),w=N.useCallback((T,I)=>{if(!p)return;const z=m("metrics")[T];z&&o(p,z.id,{aliasTemplate:I})},[p,m,o]),S=N.useCallback((T,I)=>{if(console.log("handleValueAliasesChange",T,I),!p)return;console.log("handleValueAliasesChange",T,I);const z=m("metrics")[T];z&&(console.log("handleValueAliasesChange",I),o(p,z.id,{valueAliases:I}))},[p,m,o]),C=N.useCallback(T=>{if(!p)return;if(m("metrics").length===0){Le.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:T})},[p,r,m]),j=N.useCallback(T=>{p&&r(p,{showTrendline:T})},[p,r]),D=N.useCallback(T=>{p&&r(p,{trendlineWindow:T})},[p,r]),k=N.useCallback(T=>{p&&r(p,{trendlineGranularity:T})},[p,r]),_=N.useCallback(T=>{p&&r(p,{targetValue:T})},[p,r]),M=N.useCallback(T=>{var V;if(!p)return;const I=[...m("groupBy"),...m("pivotBy"),...m("metrics"),...m("sortBy")],F=qSe(T,I,{joinPlan:(V=e==null?void 0:e.config)==null?void 0:V.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!F.isValid){F.showError&&tU();return}const z=KSe(T,I,h);if(!z){Le.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const B=gee(T,z,h);if(!B.isValid){Le.error("Invalid Field Type",{description:B.reason,position:"top-center",duration:3e3});return}const $=m(z);if(nU(T,$))return;const P=oU(T,z,$);if(P){const L=[...$,P];g(z,L),z==="metrics"&&bee(h,e==null?void 0:e.config,r,p,L)}},[p,e==null?void 0:e.config,m,g,t,n,h,r]),R=N.useCallback((T,I)=>{if(!p)return;const z=m(T)[I];if(z){if(T!=="sortBy"){const B=m("sortBy"),$=B.filter(P=>!(P.name===z.name&&P.qualifiedEntityName===z.qualifiedEntityName));$.length!==B.length&&r(p,{sortByColumns:$})}switch(T){case"groupBy":l(p,z.id);break;case"metrics":u(p,z.id);break;case"pivotBy":d(p,z.id);break;case"sortBy":f(p,z.id);break}}},[p,m,l,u,d,f,r]);return{getFieldsForContainer:m,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:S,removeField:R,handleFieldClick:M,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:j,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:_,cardType:h}};function Px(e,t){var Pe,Qe,Nt,Ke,$t;const{tokenProps:n}=qe(),r=Zs(),s=qe().authToken||e,o=_e(Ne=>Ne.selectedConnectionId),i=_e(Ne=>Ne.card),{queryKey:a}=zpe(i),l=_e(Ne=>Ne.selectedDatamodelId),u=_e(Ne=>Ne.isDevMode),d=_e(Ne=>Ne.selectedDatabaseName),f=_e(Ne=>Ne.selectedSchemaName),h=_e(Ne=>Ne.selectedTableName),p=_e(Ne=>Ne.actions.setSelectedConnectionId),m=_e(Ne=>Ne.actions.setSelectedDatamodelId),g=_e(Ne=>Ne.actions.setSelectedDatabaseName),b=_e(Ne=>Ne.actions.setSelectedSchemaName),x=_e(Ne=>Ne.actions.setSelectedTableName);_e(Ne=>Ne.actions.setCardSql);const{setQueryConfig:y}=ur();function v(Ne){var hn;return o&&Ne==="API"?!1:o&&Ne==="S3"?!0:!(!o||!d||d==="NA"||((hn=k==null?void 0:k.capabilities)==null?void 0:hn.path.includes("schema"))&&!f)}function w(Ne){return o&&Ne?!(Ne==="API"||Ne==="S3"):!1}const{refetchConnections:S,connectionsData:C,isConnectionsLoading:j,isConnectionsError:D,selectedConnection:k}=Ai(e),{refetch:_,data:M,isLoading:R,isError:O}=un({queryKey:["models",o],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),T=k==null?void 0:k.type,I=(k==null?void 0:k.type)==="API"||(k==null?void 0:k.type)==="S3",{data:F,isLoading:z,isFetching:B,isError:$,refetch:P}=un({queryKey:["databases",o],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(T)}),{data:V,isLoading:L,isFetching:A,isError:W,refetch:U}=un({queryKey:["schemas",o,d],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!I&&d!=="NA"}),{data:Y,isLoading:K,isFetching:H,isError:q,refetch:X}=un({queryKey:["tables",o,d,f],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(T)}),{columns:Z,isColumnsLoading:G,isColumnsFetching:Q,isColumnsError:ne,refetchColumns:ae}=iU(e);N.useEffect(()=>{(T==="S3"||T==="API")&&(g(""),b(""),m(""),T==="API"&&x("api"))},[T,x,g,b,m]);const ie=(k==null?void 0:k.type)==="API"?(Pe=k==null?void 0:k.type)==null?void 0:Pe.toLowerCase():h||"",fe=I?"":f||"";function xe(Ne){x(Ne),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Ce(Ne){b(Ne),x("")}function je(Ne){g(Ne==="none"?"":Ne),b(""),x(""),Ne!=="none"&&Ne!==""&&m("")}function de(Ne){p(Ne)}function Re(Ne){m(Ne==="none"?"":Ne),Ne!=="none"&&Ne!==""&&g("")}F&&((Qe=F==null?void 0:F.databases)==null?void 0:Qe.length)>0,V&&((Nt=V==null?void 0:V.schemas)==null?void 0:Nt.length)>0;const Oe=C==null?void 0:C.connections.map(Ne=>({id:Ne.id,name:Ne.name,type:Ne.type})),mt=(Ke=M==null?void 0:M.datamodels)==null?void 0:Ke.map(Ne=>({id:Ne.id,name:Ne.name})),be=F==null?void 0:F.databases.map(Ne=>({id:Ne.database_name,name:Ne.database_name})),se=V==null?void 0:V.schemas.map(Ne=>({id:Ne.schema_name,name:Ne.schema_name})),ue=Y==null?void 0:Y.tables.map(Ne=>({id:Ne.table_name,name:Ne.table_name})),we=($t=M==null?void 0:M.datamodels.find(Ne=>Ne.id===l))==null?void 0:$t.name,Se=Ky({schemaName:fe,tableName:ie,modelName:we,connectionType:T,databaseName:d||""});return{connectionItems:Oe,selectedConnectionId:o,selectedConnection:k,isConnectionsLoading:j,isConnectionsError:D,modelItems:mt,selectedDatamodelId:l,selectedDatamodelName:we,isModelsLoading:R,isModelsError:O,selectedDatabaseName:d,databaseItems:be,isDatabasesLoadingOrFetching:z||B,isDatabaseError:$,schemaItems:se,selectedSchemaName:f,isSchemaLoadingOrFetching:L||A,isSchemaError:W,tableItems:ue,selectedTableName:h,isTableLoadingOrFetching:K||H,isTableError:q,columns:Z,isColumnsLoadingOrFetching:G||Q,isColumnsError:ne,isNonDbConnection:I,connectionType:T,tableName:ie,formattedTableName:Se,schemaName:fe,refetchConnections:S,refetchModels:_,refetchDatabases:P,refetchSchemas:U,refetchTables:X,refetchColumns:ae,handleConnectionChange:de,handleDatamodelChange:Re,handleDatabaseChange:je,handleSchemaChange:Ce,handleTableChange:xe}}function py(e){return`${e}-${Mr()}`}function vL(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 TQe(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 RI(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 yee(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function vee(){const e=_e(C=>C.sqlGen),t=_e(C=>C.isDevMode),n=_e(C=>C.card.dataSource),r=_e(C=>{var j,D;return(D=(j=C.card)==null?void 0:j.queryConfig)==null?void 0:D.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=RI(n),a=yee(n),l=_e(C=>C.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:m}=ur(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Px(),y=C=>({column_name:C.name,data_type:C.dataType,label:C.label,description:C.description});return{handleDevModeFieldClick:C=>{var D;if(!t)return;const j=y(C);if(t&&a&&s){const k=M_(j,e);p(k);const _=(D=b==null?void 0:b.find(R=>R.id===l))==null?void 0:D.name,M=D_(k,fi(o||""),fi(s),_||"",g,i||"");M&&(f(M),h(!0))}else if(!t){if(Mb(j.data_type))if(r&&r.length>0){const k={...j,role:"groupby",id:py(j.column_name),name:j.column_name,type:j.data_type};d(k)}else{const k={...j,role:"metric",id:py(j.column_name),name:j.column_name,label:vL(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(k)}if(Lc(j.data_type)){const k={...j,role:"groupby",id:py(j.column_name),name:j.column_name,type:j.data_type,label:TQe(j.column_name,"month"),granularity:"month"};d(k)}if(Vo(j.data_type)){const k={...j,role:"metric",id:py(j.column_name),name:j.column_name,label:vL(j.column_name,"SUM"),type:j.data_type,aggregate:"SUM"};u(k)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Ky({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});m(!1);const j=g==="MSSQL"?`SELECT top 10 * FROM ${C}`:`SELECT * FROM ${C} LIMIT 10`;f(j),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Ky({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${C}`),h(!0)},isNumberField:C=>Vo(C.dataType)}}function wee(){const e=_e(m=>m.selectedConnectionId),t=_e(m=>m.selectedDatamodelId),n=_e(m=>m.selectedDatabaseName),r=_e(m=>m.selectedSchemaName),s=_e(m=>m.selectedTableName),o=ee(m=>m.dashboard.filters)||[],i=ee(m=>m.selectedSheetId),a=ee(m=>m.actions.addFilter),l=ee(m=>m.actions.removeFilter),{removeFilterValues:u}=Yt(),{modelItems:d,tableName:f,connectionType:h}=Px();function p(m,g="sheet",b){var k;const x=fi(m.column_name),y=fi(n||""),v=fi(r||""),w=fi(f);let S=qw({schemaName:v,tableName:w,connectionType:h,databaseName:y}),C=`${S}.${x}`;const j=(k=d==null?void 0:d.find(_=>_.id===t))==null?void 0:k.name;t&&t!=="none"&&(C=`${Cg}.${j}.${x}`,S=`${Cg}.${j}`),b!=null&&b.qualifiedFieldName&&(C=b.qualifiedFieldName,S=b.qualifiedFieldName.split(".").slice(0,-1).join(".")),b!=null&&b.entityName;let D;if(g==="sheet"&&i?D=Nke(o,C,w,n||"",y,i):D=o==null?void 0:o.find(_=>_.column===C&&_.table===w&&(_.database===y||_.database===n)),D)u(D.id),l(D.id);else{const _=Mr(),M=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:_,column:C,title:m.label||m.column_name,dataType:m.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:M,sql:V4(m.data_type,S,x)}),_):(a({id:_,location:g,column:C,title:m.label||m.column_name,dataType:m.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:M,sql:V4(m.data_type,S,(b==null?void 0:b.qualifiedFieldName)||x)}),_)}}return{assignFilter:p}}function RQe({column:e}){const[t,n]=N.useState(!1),r=_e(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=RI(r),a=_e(x=>x.selectedDatamodelId),l=_e(x=>x.sqlGen),{modelItems:u,connectionType:d}=Px(),f=_e(x=>x.actions.setSqlGen),h=_e(x=>x.actions.setCardSql),p=_e(x=>x.actions.setRunSql),m=yee(r);function g(x,y){var C;if(!m||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=M_(x,l,y),w=(C=u==null?void 0:u.find(j=>j.id===a))==null?void 0:C.name;f(v);const S=D_(v,fi(o||""),fi(s),w||"",d,i||"");S&&(h(S),p(!0)),n(!1)}function b(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>g(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>g(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>g(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>g(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>g(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return m?c.jsxs(Mp,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(Tp,{asChild:!0,children:c.jsx(ep,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(Xd,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function IQe({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 AQe({field:e,context:t="editor",fieldState:n}){const r=_e(L=>L.isDevMode),s=t==="filter",o=r||s||(n==null?void 0:n.state)==="unreachable"&&!s,i=ee(L=>L.dashboard.filters),a=ee(L=>L.selectedSheetId),l=ee(L=>L.actions.removeFilter),{removeFilterValues:u}=Yt(),{assignFilter:d}=wee(),f=s?Zc(i,a):i,h=s?f==null?void 0:f.find(L=>{var A;return L.title===e.name||((A=L.column)==null?void 0:A.includes(e.name))}):void 0,p=!!h,m=h&&s?i==null?void 0:i.find(L=>L.id===h.id):void 0,g=m&&(m.applyToSheetIds&&m.applyToSheetIds.length>1||m.excludeSheetIds&&m.excludeSheetIds.length>0||!m.applyToSheetIds&&!m.excludeSheetIds&&!m.sheetId);s&&p&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:p,activeFilterOnSheet:h?{id:h.id,title:h.title,column:h.column,applyToSheetIds:h.applyToSheetIds,excludeSheetIds:h.excludeSheetIds}:null,activeFilterForField:m?{id:m.id,title:m.title,column:m.column,applyToSheetIds:m.applyToSheetIds,excludeSheetIds:m.excludeSheetIds}:null,isMultiSheetFilter:g,selectedSheetId:a});const[b,x]=N.useState(!1),[y,v]=N.useState(null),{attributes:w,listeners:S,setNodeRef:C,transform:j,transition:D,isDragging:k}=TS({id:e.id,disabled:o}),[_,M]=N.useState(!1),R=_e(L=>L.card),{handleFieldClick:O}=xee(R),{handleDevModeFieldClick:T,isNumberField:I}=vee(),F=()=>{m&&(console.log("[SourceField] Removing multi-sheet filter:",m.id),u(m.id),l(m.id)),v(null),x(!1)},z=()=>{if(s){const L={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};p&&g?(v({column:L,field:e}),x(!0)):d(L,"sheet",e)}else r?T(e):O(e)},B={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},$={transform:_i.Transform.toString(j),transition:D},V=(()=>{if(!n||s)return{};const A={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...A},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...A},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...A}}[n.state]||A})();return c.jsxs("div",{ref:C,style:$,...o?{}:w,...o?{}:S,className:J("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",k&&"scale-95 opacity-50",!k&&"border",V.borderColor||"border-transparent",V.bgColor||"",V.hoverBorderColor,V.hoverBgColor||"hover:bg-muted",V.opacity,V.cursor,p&&"border-accent-foreground/20 bg-accent",{"cursor-pointer":r||s,"cursor-grab active:cursor-grabbing":!o&&!r&&!s}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:z,children:[sb(e.dataType),c.jsx(Yn,{children:c.jsxs(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${_?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(Cn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(IQe,{field:e,fieldState:n})})]})}),r&&!s&&I(e)&&c.jsx("div",{onClick:L=>L.stopPropagation(),children:c.jsx(RQe,{column:B})})]}),_&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(xo,{className:"",children:c.jsxs(Si,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(F8,{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(jae,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Fe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx(Hb,{open:b,onOpenChange:x,children:c.jsxs(fp,{children:[c.jsxs(hp,{children:[c.jsx(mp,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(gp,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(pp,{children:[c.jsx(xp,{children:"Cancel"}),c.jsx(bp,{onClick:F,children:"Remove Filter"})]})]})})]})}const PQe="SEMAPHOR_CALCULATED_FIELD",OQe=["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 See(e){return!!e.expression}function FQe(e){return!!e.expression}function $Qe(e){return!!e.expression}var Cee=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(Cee||{}),jl="Accordion",LQe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[II,zQe,BQe]=i1(jl),[tC]=Er(jl,[BQe,fZ]),AI=fZ(),Nee=N.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(II.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(WQe,{...o,ref:t}):c.jsx(UQe,{...s,ref:t})})});Nee.displayName=jl;var[jee,VQe]=tC(jl),[kee,HQe]=tC(jl,{collapsible:!1}),UQe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=$r({prop:n,defaultProp:r,onChange:s});return c.jsx(jee,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:N.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(kee,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(Eee,{...i,ref:t})})})}),WQe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i=[],a]=$r({prop:n,defaultProp:r,onChange:s}),l=N.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=N.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(jee,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(kee,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(Eee,{...o,ref:t})})})}),[qQe,nC]=tC(jl),Eee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=N.useRef(null),l=ft(a,t),u=zQe(n),f=zd(s)==="ltr",h=Ee(e.onKeyDown,p=>{var D;if(!LQe.includes(p.key))return;const m=p.target,g=u().filter(k=>{var _;return!((_=k.ref.current)!=null&&_.disabled)}),b=g.findIndex(k=>k.ref.current===m),x=g.length;if(b===-1)return;p.preventDefault();let y=b;const v=0,w=x-1,S=()=>{y=b+1,y>w&&(y=v)},C=()=>{y=b-1,y<v&&(y=w)};switch(p.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?S():C());break;case"ArrowDown":o==="vertical"&&S();break;case"ArrowLeft":o==="horizontal"&&(f?C():S());break;case"ArrowUp":o==="vertical"&&C();break}const j=y%x;(D=g[j].ref.current)==null||D.focus()});return c.jsx(qQe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(II.Slot,{scope:n,children:c.jsx(Be.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Fw="AccordionItem",[YQe,PI]=tC(Fw),_ee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=nC(Fw,n),i=VQe(Fw,n),a=AI(n),l=nr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(YQe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(mZ,{"data-orientation":o.orientation,"data-state":Aee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});_ee.displayName=Fw;var Dee="AccordionHeader",Mee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=nC(jl,n),o=PI(Dee,n);return c.jsx(Be.h3,{"data-orientation":s.orientation,"data-state":Aee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Mee.displayName=Dee;var d_="AccordionTrigger",Tee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=nC(jl,n),o=PI(d_,n),i=HQe(d_,n),a=AI(n);return c.jsx(II.ItemSlot,{scope:n,children:c.jsx(K3e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Tee.displayName=d_;var Ree="AccordionContent",Iee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=nC(jl,n),o=PI(Ree,n),i=AI(n);return c.jsx(Z3e,{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}})});Iee.displayName=Ree;function Aee(e){return e?"open":"closed"}var GQe=Nee,KQe=_ee,ZQe=Mee,Pee=Tee,Oee=Iee;const Fee=GQe,OI=E.forwardRef(({className:e,...t},n)=>c.jsx(KQe,{ref:n,className:J("border-b",e),...t}));OI.displayName="AccordionItem";const FI=E.forwardRef(({className:e,children:t,...n},r)=>c.jsx(ZQe,{className:"flex",children:c.jsxs(Pee,{ref:r,className:J("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,c.jsx(Ys,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));FI.displayName=Pee.displayName;const $I=E.forwardRef(({className:e,children:t,...n},r)=>c.jsx(Oee,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:J("pb-4 pt-0",e),children:t})}));$I.displayName=Oee.displayName;function XQe({context:e="editor"}={}){var _,M,R,O;const[t,n]=N.useState(""),[r,s]=N.useState("all");_e(T=>T.isDevMode);const o=_e(T=>T.card.dataSource),i=_e(T=>T.card.config),a=_e(T=>T.card),{autoJoinMetadata:l}=ha(a),{columns:u=[],columnGroups:d=[],isLoading:f,error:h}=MM(),p=(o==null?void 0:o.mode)==="semanticDomain"?o.semanticDomainId:void 0,{data:m}=TI(p),g=[...(i==null?void 0:i.groupByColumns)||[],...(i==null?void 0:i.metricColumns)||[]];(M=(_=i==null?void 0:i.joinPlan)==null?void 0:_.baseEntity)==null||M.name,(O=(R=l==null?void 0:l.resolvedJoinPlan)==null?void 0:R.baseEntity)==null||O.name,vee();const b=u.filter(T=>T.name.toLowerCase().includes(t.toLowerCase())||T.dataType.toLowerCase().includes(t.toLowerCase())||T.label&&T.label.toLowerCase().includes(t.toLowerCase())||T.qualifiedEntityName&&T.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),x=T=>{if(T.role==="metric"&&See(T)||T.role==="groupby"&&T.expression)return"calculated";if(T.dataType==="number"||T.dataType==="integer"||T.dataType==="float"||T.dataType==="decimal"||T.dataType==="currency")return"metrics";const I=Ks(T.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},v=(r==="all"?b:b.filter(T=>x(T)===r)).reduce((T,I)=>{const F=I.qualifiedEntityName||"Other Fields";return T[F]||(T[F]={label:R_(I.entityName),fields:[]}),T[F].fields.push(I),T},{}),S=Object.keys(v),C=b.filter(T=>x(T)==="dimensions").length,j=b.filter(T=>x(T)==="metrics").length,D=b.filter(T=>x(T)==="calculated").length,k=b.length>0;return f?c.jsx("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:c.jsx(_c,{size:"md",color:"muted","aria-label":"Loading data"})}):h?c.jsxs("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:[c.jsx(sl,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:h.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?c.jsx(Ds,{className:"h-[calc(100vh-200px)] w-[290px]",children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx(sl,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:e==="filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]})}):c.jsxs("div",{className:"mt-2 flex h-full w-full grow flex-col gap-2 px-6 pb-6",children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[u.length>0&&c.jsxs("div",{className:"relative mb-4",children:[c.jsx(xa,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(Bn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:t,onChange:T=>n(T.target.value)}),t&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:c.jsx(vt,{className:"size-3.5"})})]}),k&&c.jsx(cs,{defaultValue:"all",value:r,onValueChange:T=>s(T),className:"mb-4",children:c.jsxs(Wr,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(Ht,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:b.length})]}),c.jsxs(Ht,{value:"dimensions",className:"text-xs",children:[c.jsx(r1,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]}),c.jsxs(Ht,{value:"metrics",className:"text-xs",children:[c.jsx(Jh,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),c.jsxs(Ht,{value:"calculated",className:"text-xs",children:[c.jsx(q_,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:D})]})]})})]}),c.jsxs(yl,{className:"py-2",children:[c.jsx(Fee,{type:"multiple",defaultValue:S,className:"space-y-2",children:Object.entries(v).map(([T,I])=>{const F=d.find(z=>z.entityName===T)||{entityName:T,label:I.label};return c.jsxs(OI,{value:T,className:"border-none",children:[c.jsx(FI,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:F.label||F.entityName,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:F.label||F.entityName}),c.jsx(Fe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:I.fields.length})]})}),c.jsx($I,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:I.fields.map(z=>{const B=TM(z,{joinabilityMap:(m==null?void 0:m.joinabilityMap)||null,selectedFields:g,cardConfig:i,autoJoinMetadata:l});return c.jsx(AQe,{field:z,context:e,fieldState:B},z.id)})})})]},T)})}),Object.keys(v).length===0&&u.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:e==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(v).length===0&&u.length>0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(Zo,{orientation:"horizontal"}),c.jsx(Zo,{orientation:"vertical"})]})]})}function $ee({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(XQe,{context:e})," "]})}function Lee(){const e=_e(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=ur();N.useEffect(()=>{var p;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=RI(e),d=(p=e.selectedEntities)==null?void 0:p[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function QQe(){Lee();const e=ee(l=>l.selectedSheetId),t=ee(l=>l.selectedFrameId),n=ee(l=>l.dashboard),r=ee(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Yt(),{setCard:o}=ur(),i=_e(l=>l.card.dataSource);return N.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function JQe(){const e=ee(n=>n.actions.setShowFilters),{hasEntities:t}=QQe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(ce,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsx(oe,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(uZ,{})})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(sl,{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(DS,{collisionDetection:jS,children:c.jsx(MS,{items:[],strategy:FR,children:c.jsx($ee,{context:"filter"})})})})]})}function eJe(){const e=ee(r=>r.dashboard.filters),t=ee(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:J("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(NR,{filter:r}),c.jsx(wS,{filter:r})]},r.id))}):null}function tJe(){const e=ee(r=>r.showFilters),t=ee(r=>r.isVisualEditing),n=ee(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:J("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[c.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&c.jsx(eJe,{}),c.jsx(hee,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(JQe,{})})]})}const nJe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-BfjTgw7o.js"))),rJe=N.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-B783wHIy.js"))),sJe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-D6wa6YoM.js"))),oJe=N.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-C9DAKT2s.js")).then(e=>({default:e.ResourceManagementPanel})));function iJe({showControls:e=!1,showFooter:t=!0,...n}){const r=ee(l=>l.isDashboardPanelOpen),s=ee(l=>l.isVisualEditing),o=ee(l=>l.showDashboardJSON),i=ee(l=>l.actions.setIsDashboardPanelOpen),{preferences:a}=n;return c.jsx(wl,{FallbackComponent:dS,children:c.jsxs(L_,{dashboardProps:n,children:[c.jsx(Jde,{}),c.jsx(MI,{children:c.jsxs(pee,{preferences:a,children:[o&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(sJe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(nJe,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(N.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(GM,{...n,type:"dashboard",children:[s&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(rJe,{})}),c.jsx(tJe,{})]})})]})]})]})})]})})}var aJe=Object.defineProperty,lJe=(e,t,n)=>t in e?aJe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,my=(e,t,n)=>lJe(e,typeof t!="symbol"?t+"":t,n);const cJe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},uJe={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}},dJe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},fJe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},hJe={stringify:e=>e,parse:e=>e},Q2={string:hJe,number:fJe,boolean:cJe,function:uJe,json:dJe};function pJe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const gy=Symbol.for("r2wc.render"),by=Symbol.for("r2wc.connected"),gu=Symbol.for("r2wc.context"),Ta=Symbol.for("r2wc.props");function mJe(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const p of i){l[p]=Array.isArray(t.props)?"string":t.props[p];const m=pJe(p);d[p]=m,f[m]=p}for(const p of a)u[p]=Array.isArray(t.events)?{}:t.events[p];class h extends HTMLElement{constructor(){super(),my(this,o,!0),my(this,s),my(this,r,{}),my(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Ta].container=this.container;for(const m of i){const g=d[m],b=this.getAttribute(g),x=l[m],y=x?Q2[x]:null;y!=null&&y.parse&&b&&(this[Ta][m]=y.parse(b,g,this))}for(const m of a)this[Ta][m]=g=>{const b=m.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[m]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[by]=!0,this[gy]()}disconnectedCallback(){this[by]=!1,this[gu]&&n.unmount(this[gu]),delete this[gu]}attributeChangedCallback(m,g,b){const x=f[m],y=l[x],v=y?Q2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[Ta][x]=v.parse(b,m,this),this[gy]())}[(o=by,s=gu,r=Ta,gy)](){this[by]&&(this[gu]?n.update(this[gu],this[Ta]):this[gu]=n.mount(this.container,e,this[Ta]))}}for(const p of i){const m=d[p],g=l[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[Ta][p]},set(b){this[Ta][p]=b;const x=g?Q2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,m,this);this.getAttribute(m)!==y&&this.setAttribute(m,y)}else this[gy]()}})}return h}function gJe(e,t,n){const r=dj(e),s=N.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function bJe({root:e,ReactComponent:t},n){const r=N.createElement(t,n);e.render(r)}function xJe({root:e}){e.unmount()}function yJe(e,t={}){return mJe(e,t,{mount:gJe,update:bJe,unmount:xJe})}const vJe={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"},wJe=yJe(mee,{props:vJe});function SJe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function wL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function SL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?wL(Object(n),!0).forEach(function(r){SJe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):wL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function CJe(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 NJe(e,t){if(e==null)return{};var n=CJe(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 jJe(e,t){return kJe(e)||EJe(e,t)||_Je(e,t)||DJe()}function kJe(e){if(Array.isArray(e))return e}function EJe(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 _Je(e,t){if(e){if(typeof e=="string")return CL(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 CL(e,t)}}function CL(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 DJe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1067
1067
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function MJe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function NL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function jL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?NL(Object(n),!0).forEach(function(r){MJe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):NL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function TJe(){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 Wm(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 $w(e){return{}.toString.call(e).includes("Object")}function RJe(e){return!Object.keys(e).length}function vb(e){return typeof e=="function"}function IJe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function AJe(e,t){return $w(t)||mc("changeType"),Object.keys(t).some(function(n){return!IJe(e,n)})&&mc("changeField"),t}function PJe(e){vb(e)||mc("selectorType")}function OJe(e){vb(e)||$w(e)||mc("handlerType"),$w(e)&&Object.values(e).some(function(t){return!vb(t)})&&mc("handlersType")}function FJe(e){e||mc("initialIsRequired"),$w(e)||mc("initialType"),RJe(e)&&mc("initialContent")}function $Je(e,t){throw new Error(e[t]||e.default)}var LJe={initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"},mc=Wm($Je)(LJe),xy={changes:AJe,selector:PJe,handler:OJe,initial:FJe};function zJe(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};xy.initial(e),xy.handler(t);var n={current:e},r=Wm(HJe)(n,t),s=Wm(VJe)(n),o=Wm(xy.changes)(e),i=Wm(BJe)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return xy.selector(u),u(n.current)}function l(u){TJe(r,s,o,i)(u)}return[a,l]}function BJe(e,t){return vb(t)?t(e.current):t}function VJe(e,t){return e.current=jL(jL({},e.current),t),t}function HJe(e,t,n){return vb(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 UJe={create:zJe},WJe={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs"}};function qJe(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 YJe(e){return{}.toString.call(e).includes("Object")}function GJe(e){return e||kL("configIsRequired"),YJe(e)||kL("configType"),e.urls?(KJe(),{paths:{vs:e.urls.monacoBase}}):e}function KJe(){console.warn(zee.deprecation)}function ZJe(e,t){throw new Error(e[t]||e.default)}var zee={configIsRequired:"the configuration object is required",configType:"the configuration object should be an object",default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
1068
1068
  You are using deprecated way of configuration.
1069
1069