react-semaphor 0.1.124 → 0.1.125
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{dashboard-controls-j6VncHyG.js → dashboard-controls-Bx-ySdim.js} +3 -3
- package/dist/chunks/{dashboard-controls-C_kxUkyD.js → dashboard-controls-CZkFeNrk.js} +1 -1
- package/dist/chunks/{dashboard-json-BCOS2K2w.js → dashboard-json-BlEVRs4V.js} +1 -1
- package/dist/chunks/{dashboard-json-QdBRgDPb.js → dashboard-json-Cn2IxIvK.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-C-EPVOe8.js → edit-dashboard-visual-CHqS0-RO.js} +3 -3
- package/dist/chunks/{edit-dashboard-visual-E4AXmvCQ.js → edit-dashboard-visual-Cm5Mc4Um.js} +1 -1
- package/dist/chunks/{editor-action-buttons-Derg0Fka.js → editor-action-buttons-BjVPDqso.js} +2 -2
- package/dist/chunks/{editor-action-buttons-C_UBbFu6.js → editor-action-buttons-j0OdQL7Y.js} +1 -1
- package/dist/chunks/{index-C_K3WRIV.js → index-BQPGBZP4.js} +5 -5
- package/dist/chunks/{index-3qBZw0dE.js → index-CZGIYFfM.js} +2 -2
- package/dist/chunks/{resource-management-panel-y71osNXf.js → resource-management-panel-BD6pGiUl.js} +2 -2
- package/dist/chunks/{resource-management-panel-C4CDYpm_.js → resource-management-panel-CaktfbhQ.js} +1 -1
- package/dist/chunks/{schedule-dashboard-C79ka7qZ.js → schedule-dashboard-BQ5u1NRe.js} +3 -3
- package/dist/chunks/{schedule-dashboard-B-z6gEwK.js → schedule-dashboard-Cul4sDBY.js} +1 -1
- package/dist/chunks/{use-visual-utils-zPL0RdVw.js → use-visual-utils-Dhcu2Fn4.js} +1 -1
- package/dist/chunks/{use-visual-utils-BBZxgwfD.js → use-visual-utils-uElEhCM9.js} +1 -1
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +4 -4
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
|
@@ -961,7 +961,7 @@ ${(e*100).toLocaleString()}%`}}},scales:{_index_:{display:!1,padding:10,grid:{di
|
|
|
961
961
|
* https://chartjs-chart-matrix.pages.dev/
|
|
962
962
|
* (c) 2025 Jukka Kurkela
|
|
963
963
|
* Released under the MIT license
|
|
964
|
-
*/var pRe="0.0.0-development";class ax extends Gs{initialize(){this.enableOptionSharing=!0,super.initialize()}update(t){const n=this._cachedMeta;this.updateElements(n.data,0,n.data.length,t)}updateElements(t,n,r,s){const o=s==="reset",{xScale:i,yScale:a}=this._cachedMeta,l=this.resolveDataElementOptions(n,s),u=this.getSharedOptions(l);for(let d=n;d<n+r;d++){const f=!o&&this.getParsed(d),h=o?i.getBasePixel():i.getPixelForValue(f.x),p=o?a.getBasePixel():a.getPixelForValue(f.y),m=this.resolveDataElementOptions(d,s),{width:g,height:b,anchorX:x,anchorY:y}=m,v={x:mRe(x,h,g),y:gRe(y,p,b),width:g,height:b,options:m};this.updateElement(t[d],d,v,s)}this.updateSharedOptions(u,s,l)}draw(){const t=this.chart.ctx,n=this.getMeta().data||[];let r,s;for(r=0,s=n.length;r<s;++r)n[r].draw(t)}}ax.id="matrix";ax.version=pRe;ax.defaults={dataElementType:"matrix",animations:{numbers:{type:"number",properties:["x","y","width","height"]}}};ax.overrides={interaction:{mode:"nearest",intersect:!0},scales:{x:{type:"linear",offset:!0},y:{type:"linear",reverse:!0}}};function mRe(e,t,n){return e==="left"||e==="start"?t:e==="right"||e==="end"?t-n:t-n/2}function gRe(e,t,n){return e==="top"||e==="start"?t:e==="bottom"||e==="end"?t-n:t-n/2}function dG(e,t){const{x:n,y:r,width:s,height:o}=e.getProps(["x","y","width","height"],t);return{left:n,top:r,right:n+s,bottom:r+o}}function ty(e,t,n){return Math.max(Math.min(e,n),t)}function bRe(e,t,n){const r=e.borderWidth;let s,o,i,a;return _t(r)?(s=+r.top||0,o=+r.right||0,i=+r.bottom||0,a=+r.left||0):s=o=i=a=+r||0,{t:ty(s,0,n),r:ty(o,0,t),b:ty(i,0,n),l:ty(a,0,t)}}function xRe(e){const t=dG(e,!1),n=t.right-t.left,r=t.bottom-t.top,s=bRe(e.options,n/2,r/2);return{outer:{x:t.left,y:t.top,w:n,h:r},inner:{x:t.left+s.l,y:t.top+s.t,w:n-s.l-s.r,h:r-s.t-s.b}}}function c2(e,t,n,r){const s=t===null,o=n===null,i=!e||s&&o?!1:dG(e,r);return i&&(s||t>=i.left&&t<=i.right)&&(o||n>=i.top&&n<=i.bottom)}class nR extends Qo{draw(t){const n=this.options,{inner:r,outer:s}=xRe(this),o=il(n.borderRadius);t.save(),s.w!==r.w||s.h!==r.h?(t.beginPath(),ol(t,{x:s.x,y:s.y,w:s.w,h:s.h,radius:o}),ol(t,{x:r.x,y:r.y,w:r.w,h:r.h,radius:o}),t.fillStyle=n.backgroundColor,t.fill(),t.fillStyle=n.borderColor,t.fill("evenodd")):(t.beginPath(),ol(t,{x:r.x,y:r.y,w:r.w,h:r.h,radius:o}),t.fillStyle=n.backgroundColor,t.fill()),t.restore()}inRange(t,n,r){return c2(this,t,n,r)}inXRange(t,n){return c2(this,t,null,n)}inYRange(t,n){return c2(this,null,t,n)}getCenterPoint(t){const{x:n,y:r,width:s,height:o}=this.getProps(["x","y","width","height"],t);return{x:n+s/2,y:r+o/2}}tooltipPosition(){return this.getCenterPoint()}getRange(t){return t==="x"?this.width/2:this.height/2}constructor(t){super(),t&&Object.assign(this,t)}}nR.id="matrix";nR.defaults={backgroundColor:void 0,borderColor:void 0,borderWidth:void 0,borderRadius:0,anchorX:"center",anchorY:"center",width:20,height:20};Kt.register(kDe);Kt.register(nd);Kt.register(kp);Kt.register(Ep);Kt.register(pl);Kt.register(Qd);Kt.register(Ec);Kt.register(_c);Kt.register(zg);Kt.register(QV);Kt.register(Up);Kt.register(Hp);Kt.register(wl);Kt.register(ix);Kt.register(ax);Kt.register(nR);function lx({cfg:e,onDatapointClick:t,onChartClick:n}){var p;const[r,s]=N.useState(""),o=ee(m=>m.selectedLensId),i=N.useRef(null),[a,l]=N.useState(),u=ee(m=>m.themeStyle);N.useEffect(()=>{if(i.current){const m=window.getComputedStyle(i.current);s(m.fontFamily)}},[]),N.useEffect(()=>{var x,y,v,w;if(!r)return;(y=(x=u==null?void 0:u.chart)==null?void 0:x.font)!=null&&y.family&&(Kt.defaults.font={...Kt.defaults.font,...(v=u==null?void 0:u.chart)==null?void 0:v.font,family:r});const m=Eg(e);m.options={...e.options,responsive:!0,maintainAspectRatio:!1};const g=(w=i==null?void 0:i.current)==null?void 0:w.getContext("2d");if(!g)return;let b;try{const S=KSe(m,g);b=new Kt(g,S),l(b)}catch(S){console.log("error creating chart",S)}return()=>{b&&b.destroy()}},[(p=u==null?void 0:u.chart)==null?void 0:p.font,o,r,e]);function d(m){console.log("handleRightClick",m),a&&(n==null||n(m,a,i))}function f(m){var b,x;if(!a)return;n==null||n(m,a,i);const g=a==null?void 0:a.getElementsAtEventForMode(m.nativeEvent,"nearest",{intersect:!0},!0);if(g&&g.length>0){const y=g[0].datasetIndex,v=g[0].index,w=(x=(b=g[0].element)==null?void 0:b.$context)==null?void 0:x.raw;t==null||t(a,y,v,w)}}const h=e.type==="doughnut"||e.type==="pie";return c.jsx("div",{onClick:f,onContextMenu:d,className:J("relative h-[99%] min-w-0 grow",{"mx-14":h}),children:c.jsx("canvas",{ref:i})})}async function yRe(e,t){if(!e||e.trim()==="")throw new Error("URL is required to load component");const r=`${e.endsWith("/")?e:`${e}/`}index.js`;return{default:(await new Function("url","return import(url)")(r))[t]}}async function vRe(e){try{const t=await import(e),n=Object.keys(t),r=[];return n.forEach(s=>{typeof t[s]=="function"&&(s==null?void 0:s[0])===(s==null?void 0:s[0].toUpperCase())&&r.push({name:s,component:s})}),r}catch(t){return console.error("Error loading the library:",t),[]}}async function fG(e){try{const t=e.endsWith("/")?e:`${e}/`,n=await fetch(`${t}manifest.json`);if(!n.ok)throw new Error(`Failed to fetch manifest: ${n.statusText}`);return await n.json()}catch(t){throw console.error("Error loading manifest:",t),t}}function hG(){const[e,t]=N.useState(!1);return N.useEffect(()=>{if(window.React&&window.ReactDOM){t(!0);return}window.React=N,window.ReactDOM=In,window.React.jsx=nA.jsx,window.React.jsxs=nA.jsxs,t(!0)},[]),e}const rR=e=>{const[t,n]=N.useState([]),[r,s]=N.useState(null),o=hG();N.useEffect(()=>{e&&e.trim()!==""&&o?fG(e).then(l=>{n(l.visuals),s(l)}).catch(()=>{vRe(e).then(l=>{n(l)}).catch(l=>{console.error("Error loading manifest:",l)})}):(n([]),s(null))},[e,o]);const i=N.useMemo(()=>!e||e.trim()===""||t.length===0?[]:(t==null?void 0:t.map(l=>{const{name:u,component:d,dataInputs:f,chartType:h}=l;return{name:u,chartType:h,componentName:d,Component:N.lazy(()=>yRe(e,d)),type:f&&f.length>1?"multiple":"single"}}))||[],[t,e]);return{getCard:N.useCallback(l=>{const u=i==null?void 0:i.find(d=>d.name===l);return u?u.Component:null},[i]),components:i,manifest:r}};function pG({onLoadingStatus:e,onDataChange:t,card:n}){const{isFetching:r,isLoading:s,data:o,queryKey:i}=fa(n),a=JSON.stringify(i);return N.useEffect(()=>{e==null||e(s)},[r,s,e]),N.useEffect(()=>{t(n.id,(o==null?void 0:o.records)||[])},[o==null?void 0:o.records,n.id,a,t]),c.jsx(c.Fragment,{})}function wRe({card:e,frame:t}){var O,T,I,F,z,B,$,P,V,L,A,W;const[n,r]=N.useState([]),{theme:s}=Xw(),{authToken:o}=qe(),i=v6(o==null?void 0:o.accessToken),a=ee(U=>U.themeStyle),l={colors:((T=(O=a==null?void 0:a.chart)==null?void 0:O.dataset)==null?void 0:T.backgroundColor)||[],mode:s||"system"},[u,d]=N.useState(!1),{getCard:f}=rR(((I=e.customCardPreferences)==null?void 0:I.url)||""),h=((F=e.customCardPreferences)==null?void 0:F.visualType)||"single",p=(z=e.customCardPreferences)==null?void 0:z.componentName,{data:m}=fa(e),g=It(U=>U.interactionStates),b=ee(U=>{var Y;return(Y=U.dashboard)==null?void 0:Y.id}),x=ee(U=>U.dashboard.filters),y=ee(U=>U.filterValues),v=ee(U=>U.selectedSheetId),{cardFilters:w,cardFilterValues:S,shouldApplyDashboardFilters:C,contextMode:j}=N.useMemo(()=>XD({card:e,interactionStates:g,currentDashboardId:b,filters:x,filterValues:y,selectedSheetId:v}),[e,g,b,x,y,v]),D=N.useCallback((U,Y)=>{r(K=>({...K,[U]:Y}))},[]);if(!p)return null;const k=f(p),_=Object.keys(((B=e.customCardPreferences)==null?void 0:B.dataInputCardIds)||{}).map(U=>{var H,q,X;const Y=(q=(H=e.customCardPreferences)==null?void 0:H.dataInputCardIds)==null?void 0:q[U].cardId,K=(X=t==null?void 0:t.cards)==null?void 0:X.find(Z=>Z.id===Y);return K||null});function M(U){d(U)}const R=((P=($=e.preferences)==null?void 0:$.displayOptions)==null?void 0:P.allowScroll)??!0;return c.jsx("div",{className:J("semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2",R?"overflow-y-auto":"h-full overflow-hidden"),children:c.jsxs(N.Suspense,{fallback:c.jsx(c.Fragment,{}),children:[k&&h==="single"&&c.jsx(k,{params:i,theme:l,chartSettings:(V=e.customCardPreferences)==null?void 0:V.settings,settings:(L=e.customCardPreferences)==null?void 0:L.settings,onDataChange:D,data:(m==null?void 0:m.records)||[],filters:w,filterValues:S}),k&&h==="multiple"&&c.jsxs("div",{children:[Object.keys(((A=e.customCardPreferences)==null?void 0:A.dataInputCardIds)||{}).map(U=>{var H,q,X;const Y=(q=(H=e.customCardPreferences)==null?void 0:H.dataInputCardIds)==null?void 0:q[U].cardId,K=(X=t==null?void 0:t.cards)==null?void 0:X.find(Z=>Z.id===Y);if(K)return c.jsx(pG,{onLoadingStatus:M,onDataChange:D,dataInputIndex:U,card:K},K.id+U)}),h==="multiple"&&c.jsx("div",{className:J("flex flex-col gap-2",{"opacity-50":u}),children:c.jsx(k,{params:i,theme:l,onDataChange:D,chartSettings:(W=e.customCardPreferences)==null?void 0:W.settings,settings:_.map(U=>{var Y;return(Y=U==null?void 0:U.customCardPreferences)==null?void 0:Y.settings}),data:_.map(U=>U!=null&&U.id?n==null?void 0:n[U.id]:[]),filters:w,filterValues:S})})]})]},e.id)})}const sR=N.memo(wRe,(e,t)=>{var n,r,s,o;return e.card.id===t.card.id&&e.frame.id===t.frame.id&&((n=e.card.customCardPreferences)==null?void 0:n.url)===((r=t.card.customCardPreferences)==null?void 0:r.url)&&((s=e.card.customCardPreferences)==null?void 0:s.componentName)===((o=t.card.customCardPreferences)==null?void 0:o.componentName)});function fS({customerFacingMessage:e,error:t,resetErrorBoundary:n}){return c.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center rounded-lg border border-dashed border-muted-foreground/25 bg-muted/30 p-6 text-center",children:[c.jsx("div",{className:"mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:c.jsx("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"})})}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"Chart Unavailable"}),c.jsx("p",{className:"mb-4 text-xs text-muted-foreground",children:e||"Couldn't display this chart right now. Please try refreshing or check your data configuration."}),c.jsxs("button",{onClick:n,className:"inline-flex items-center justify-center rounded-md bg-primary px-3 py-2 text-xs font-medium text-primary-foreground shadow-sm transition-colors hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",children:[c.jsx("svg",{className:"mr-1.5 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Try Again"]}),Yw]})}function hS({error:e}){return c.jsx("div",{className:"flex flex-col items-center justify-center",role:"alert",style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",width:"100%"},children:c.jsxs("div",{style:{backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",boxShadow:"0 2px 6px rgba(0, 0, 0, 0.08)",color:"#b91c1c",fontFamily:"sans-serif",padding:"16px",textAlign:"center",flexDirection:"column",whiteSpace:"pre-wrap",position:"relative"},className:"flex flex-col justify-center space-y-1 rounded-md bg-muted p-10",children:[c.jsx("p",{className:"text-sm",children:"Something went wrong:"}),c.jsx("pre",{className:"text-xs",children:e.message})]})})}function SRe({error:e,frame:t}){return c.jsxs("div",{className:"flex h-full flex-col items-center justify-center border",role:"alert",children:[c.jsx(uK,{frame:t,isHovered:!1}),c.jsx("div",{className:"flex flex-col justify-center space-y-2 rounded-md p-10"}),c.jsxs("div",{className:"flex flex-col justify-center space-y-2 rounded-md p-10",children:[c.jsx("p",{className:"text-lg font-semibold",children:"Oops! Looks like we tripped on a loose wire!"}),c.jsx("p",{className:"text-sm",children:"Something went wrong:"}),c.jsx("pre",{className:"text-xs",children:e.message})]})]})}const CRe=N.createContext(null),u2={didCatch:!1,error:null};class Sl extends N.Component{constructor(t){super(t),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=u2}static getDerivedStateFromError(t){return{didCatch:!0,error:t}}resetErrorBoundary(){const{error:t}=this.state;if(t!==null){for(var n,r,s=arguments.length,o=new Array(s),i=0;i<s;i++)o[i]=arguments[i];(n=(r=this.props).onReset)===null||n===void 0||n.call(r,{args:o,reason:"imperative-api"}),this.setState(u2)}}componentDidCatch(t,n){var r,s;(r=(s=this.props).onError)===null||r===void 0||r.call(s,t,n)}componentDidUpdate(t,n){const{didCatch:r}=this.state,{resetKeys:s}=this.props;if(r&&n.error!==null&&NRe(t.resetKeys,s)){var o,i;(o=(i=this.props).onReset)===null||o===void 0||o.call(i,{next:s,prev:t.resetKeys,reason:"keys"}),this.setState(u2)}}render(){const{children:t,fallbackRender:n,FallbackComponent:r,fallback:s}=this.props,{didCatch:o,error:i}=this.state;let a=t;if(o){const l={error:i,resetErrorBoundary:this.resetErrorBoundary};if(typeof n=="function")a=n(l);else if(r)a=N.createElement(r,l);else if(s!==void 0)a=s;else throw i}return N.createElement(CRe.Provider,{value:{didCatch:o,error:i,resetErrorBoundary:this.resetErrorBoundary}},a)}}function NRe(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];return e.length!==t.length||e.some((n,r)=>!Object.is(n,t[r]))}function jRe(e={},t){const{displayPreferences:n,shouldShowElement:r}=Hc(),s=n.mode==="table-print",o=e.enabled??!0,i=e.serverSide??!1,a=s?Number.MAX_SAFE_INTEGER:e.pageSize||50,l=e.currentPage!==void 0,[u,d]=N.useState(0),[f,h]=N.useState(a),p=l?(e.currentPage||1)-1:u,m=l?e.pageSize||a:f,g=N.useMemo(()=>o&&r("showPagination")&&!s,[o,r,s]),b=N.useMemo(()=>i?e.pageCount:Math.ceil(t/m),[i,e.pageCount,t,m]),x=N.useMemo(()=>i?e.totalCount||0:t,[i,e.totalCount,t]),y=N.useMemo(()=>i?(e.currentPage||1)>1:p>0,[i,e.currentPage,p]),v=N.useMemo(()=>i?(e.currentPage||1)<(e.pageCount||1):p<(b||1)-1,[i,e.currentPage,e.pageCount,p,b]);return{pageIndex:p,pageSize:m,isServerSidePagination:i,showPagination:g,paginationEnabled:o,isTablePrintDisplayMode:s,setPageIndex:D=>{var k;l?(k=e.onPageChange)==null||k.call(e,D+1,m):d(D)},setPageSize:D=>{var k;l?(k=e.onPageChange)==null||k.call(e,1,D):(d(0),h(D))},canPreviousPage:y,canNextPage:v,previousPage:()=>{var k;if(!y)return;const D=p-1;l?(k=e.onPageChange)==null||k.call(e,D+1,m):d(D)},nextPage:()=>{var k;if(!v)return;const D=p+1;l?(k=e.onPageChange)==null||k.call(e,D+1,m):d(D)},pageCount:b,totalCount:x}}function kRe(e,t,n){var l;if(!t.length)return e;const r=t[0].id,s=t[0].desc?-1:1,o=((l=n.groupByColumns)==null?void 0:l.length)||0,i=r.startsWith("rowLevel"),a=i?parseInt(r.replace("rowLevel","")):-1;return i?ERe(e,a,s):_Re(e,r,s,o,n)}function ERe(e,t,n){const r=[...e],s=new Map,o=[];r.forEach(l=>{if(l.isGrandTotal)return;const u=t>0?l.fieldValues.slice(0,t).join("|||"):"root";s.has(u)||(s.set(u,[]),o.push(u)),s.get(u).push(l)});const i=[];o.forEach(l=>{const u=s.get(l),d=u.filter(h=>!h.isSubtotal),f=u.filter(h=>h.isSubtotal);d.sort((h,p)=>{const m=h.fieldValues[t],g=p.fieldValues[t];return m===g?0:m==null?1:g==null?-1:String(m).localeCompare(String(g))*n}),i.push(...d),i.push(...f)});const a=e.find(l=>l.isGrandTotal);return a&&i.push(a),i}function _Re(e,t,n,r,s){const o={rows:[],children:new Map};let i;e.forEach(f=>{if(f.isGrandTotal){i=f;return}if(f.isSubtotal){let h=o;for(let p=0;p<r-1;p++){const m=f.fieldValues[p];h.children.has(m)||h.children.set(m,{rows:[],children:new Map}),h=h.children.get(m)}h.subtotal=f}else{let h=o;for(let p=0;p<r-1;p++){const m=f.fieldValues[p];h.children.has(m)||h.children.set(m,{rows:[],children:new Map}),h=h.children.get(m)}h.rows.push(f)}});function a(f){var h;return t==="rowTotal"?s.columnHeaders.reduce((p,m)=>{var b;const g=(b=f.cells[m])==null?void 0:b.value;return p+(typeof g=="number"?g:0)},0):(h=f.cells[t])==null?void 0:h.value}function l(f){let h=0;return f.rows.forEach(p=>{const m=a(p);typeof m=="number"&&(h+=m)}),f.children.forEach(p=>{if(p.subtotal){const m=a(p.subtotal);typeof m=="number"&&(h+=m)}else h+=l(p)}),h}function u(f){const h=[],p=[...f.rows].sort((g,b)=>{const x=a(g),y=a(b);return x===y?0:x==null?1:y==null?-1:x>y?n:-n});return h.push(...p),Array.from(f.children.entries()).sort(([,g],[,b])=>{const x=g.subtotal?a(g.subtotal):l(g),y=b.subtotal?a(b.subtotal):l(b);return x===y?0:x==null?1:y==null?-1:x>y?n:-n}).forEach(([,g])=>{h.push(...u(g))}),f.subtotal&&h.push(f.subtotal),h}const d=u(o);return i&&d.push(i),d}function DRe(e,t){const[n,r]=N.useState([]),s=N.useMemo(()=>kRe(e,n,t),[e,n,t]),o=N.useCallback(l=>{r(u=>{const d=u.find(f=>f.id===l);return d?d.desc?[]:[{id:l,desc:!0}]:[{id:l,desc:!1}]})},[]),i=N.useCallback(()=>{r([])},[]),a=N.useCallback(l=>{const u=n.find(d=>d.id===l);return u?u.desc?"desc":"asc":!1},[n]);return{sorting:n,setSorting:r,sortedTableData:s,toggleColumnSort:o,clearSorting:i,getSortDirection:a}}function Qg(e,t,n,r){if(t){const s=Xa(e,t,n,r),o=Hke(e,t);return s==="-"||s===0?c.jsx("div",{className:"flex justify-end",children:c.jsx(ku,{className:"h-3 w-3 text-muted-foreground"})}):o?c.jsx("span",{style:{backgroundColor:o.backgroundColor,color:o.color,padding:"0.125rem 0.25rem",borderRadius:"0.25rem"},children:s}):s}return typeof e=="object"&&(e==null?void 0:e.formattedValue)!==void 0?e.formattedValue==="-"||e.formattedValue===0?c.jsx("div",{className:"flex justify-end",children:c.jsx(ku,{className:"h-3 w-3 text-muted-foreground"})}):e.formattedValue:typeof e=="number"?e===0||e===null?c.jsx("div",{className:"flex justify-end",children:c.jsx(ku,{className:"h-3 w-3 text-muted-foreground"})}):e.toLocaleString():e==null?c.jsx("div",{className:"flex justify-end",children:c.jsx(ku,{className:"h-3 w-3 text-muted-foreground"})}):(e==null?void 0:e.toString())||c.jsx("div",{className:"flex justify-end",children:c.jsx(ku,{className:"h-3 w-3 text-muted-foreground"})})}function MRe(e){return(e==null?void 0:e.includes("_SUM_"))||(e==null?void 0:e.includes("_AVG_"))||(e==null?void 0:e.includes("_COUNT_"))||(e==null?void 0:e.includes("_MIN_"))||(e==null?void 0:e.includes("_MAX_"))}function TRe(e,t){const n=(e==null?void 0:e.includes("_SUM_ALL"))||(e==null?void 0:e.includes("_AVG_ALL"))||(e==null?void 0:e.includes("_COUNT_ALL"))||(e==null?void 0:e.includes("_MIN_ALL"))||(e==null?void 0:e.includes("_MAX_ALL")),r=(t==null?void 0:t.some(s=>s.columnName===e&&(s.subtotalLevel==="grandTotal"||s.subtotalLevel==="ALL")))??!1;return n||r}function RRe({data:e,card:t,table:n,sorting:r,setSorting:s,showRowTotals:o,onAggregationChange:i,onOpenColumnSettings:a}){const[l,u]=N.useState(null),d=ee(p=>p.isVisualEditing),f=N.useCallback(p=>{var m;return(m=n.getHeaderGroups()[0])==null?void 0:m.headers.find(g=>g.column.id===p)},[n]);return{buildColumnHeaderRows:N.useCallback(()=>{var j,D;const p=((j=t.config)==null?void 0:j.pivotByColumns)||[],m=p.length,g=((D=e.groupByColumns)==null?void 0:D.length)||1,b=e.columnHeaders.length;function x(k,_,M,R=[]){k.forEach((O,T)=>{var F,z,B;const I=O.level;if(I<m){const $=O.columnKey||`${I}-${R.join("-")}-${O.name}-${T}`,P=O.children?1:m-I,V=`pivot-${$}`,L=l===V;if(M[I].push(c.jsx(oo,{colSpan:O.colspan,rowSpan:P,className:"h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-center text-xs font-medium",children:c.jsxs("div",{className:"group/pivot-header relative flex items-center justify-center",children:[i&&c.jsx("div",{className:J("absolute left-0 overflow-hidden transition-all duration-200",L?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/pivot-header:h-6 group-hover/pivot-header:w-6 group-hover/pivot-header:opacity-100"),children:c.jsx(zm,{columnName:O.name,groupByFields:e.groupByColumns||[],pivotByFields:((F=t.config)==null?void 0:F.pivotByColumns)||[],currentAggregation:{rowAggregates:(z=t.config)==null?void 0:z.rowAggregates,columnAggregates:(B=t.config)==null?void 0:B.columnAggregates},onAggregationChange:i,onOpenChange:A=>u(A?V:null)})}),c.jsx("span",{className:"whitespace-nowrap",children:O.name})]})},$)),O.children){const A=[...R,O.name];x(O.children,I+1,M,A)}}})}function y(k,_=[]){const M=[];return k.forEach((R,O)=>{var T,I,F,z,B;if(R.columnKey){const $=R.columnKey||`metric-${_.join("-")}-${R.name}-${O}`,P=MRe(R.columnKey),V=TRe(R.columnKey,e.columnSubtotalMeta),L=n.getColumn(R.columnKey),A=f(R.columnKey);M.push(c.jsx(oo,{"data-column-id":R.columnKey,className:J("group/header h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-right text-xs last:border-r-0",V?"bg-muted font-semibold":P?"bg-muted/70 font-medium":""),style:{width:A==null?void 0:A.getSize(),minWidth:A==null?void 0:A.getSize(),maxWidth:A==null?void 0:A.getSize(),position:"relative",transition:"none"},children:L?c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs(oe,{variant:"ghost",className:"h-auto flex-shrink-0 p-0 hover:bg-transparent",onClick:()=>{const W=L.getIsSorted();s(W?W==="asc"?[{id:L.id,desc:!0}]:[]:[{id:L.id,desc:!1}])},"aria-label":`Sort ${((T=e.columnDisplayNames)==null?void 0:T[R.columnKey])||R.name||"Metric"}`,children:[c.jsx(Oo,{className:J("mr-1 h-3 w-3",L.getIsSorted()==="asc"?"hidden group-hover/header:block":"hidden")}),c.jsx(Qi,{className:J("mr-1 h-3 w-3",L.getIsSorted()==="desc"?"hidden group-hover/header:block":"hidden")}),c.jsx(ju,{className:J("mr-1 h-3 w-3",L.getIsSorted()?"hidden":"hidden group-hover/header:block")})]}),c.jsx("span",{className:"min-w-0 truncate text-xs font-medium",title:((I=e.columnDisplayNames)==null?void 0:I[R.columnKey])||R.name||"Metric",children:((F=e.columnDisplayNames)==null?void 0:F[R.columnKey])||R.name||"Metric"}),d&&a&&c.jsx(oe,{variant:"ghost",size:"icon",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover/header:opacity-100",onClick:W=>{W.stopPropagation(),a(R.columnKey)},children:c.jsx(Qu,{className:"h-3 w-3"})}),A&&c.jsx(_u,{header:A,isResizing:A.column.getIsResizing()})]}):c.jsx("span",{className:"block truncate px-2",title:((z=e.columnDisplayNames)==null?void 0:z[R.columnKey])||R.name||"Metric",children:((B=e.columnDisplayNames)==null?void 0:B[R.columnKey])||R.name||"Metric"})},$))}else if(R.children){const $=[..._,R.name];M.push(...y(R.children,$))}}),M}const v=c.jsxs(lr,{"data-header-type":"pivot-hierarchy","data-header-row-index":"0","data-repeat-header":"true",children:[e.groupByColumns&&e.groupByColumns.length>0?e.groupByColumns.map((k,_)=>{var I,F,z,B,$;const M=(I=n.getHeaderGroups()[0])==null?void 0:I.headers.find(P=>P.column.id===`rowLevel${_}`),R=M==null?void 0:M.getSize(),O=`row-header-${_}`,T=l===O;return c.jsx(oo,{rowSpan:m+2,"data-column-id":`rowLevel${_}`,className:"group/rowheader h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-left align-bottom text-xs font-medium",style:{width:R,minWidth:R,maxWidth:R,position:"relative",transition:"none"},children:c.jsxs("div",{className:"flex h-full min-w-0 items-end justify-between pb-1",children:[c.jsxs("div",{className:"relative flex min-w-0 items-center",children:[i&&c.jsx("div",{className:J("absolute left-0 top-1/2 -translate-y-1/2 overflow-hidden transition-all duration-200",T?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/rowheader:h-6 group-hover/rowheader:w-6 group-hover/rowheader:opacity-100"),children:c.jsx(zm,{columnName:k.label||k.name,groupByFields:e.groupByColumns||[],pivotByFields:p,currentAggregation:{rowAggregates:(F=t.config)==null?void 0:F.rowAggregates,columnAggregates:(z=t.config)==null?void 0:z.columnAggregates},onAggregationChange:i,onOpenChange:P=>u(P?O:null)})}),c.jsxs(oe,{variant:"ghost",className:J("flex h-auto min-w-0 items-center gap-1 p-0 transition-all duration-200 hover:bg-transparent",i&&(T?"pl-7":"group-hover/rowheader:pl-7")),onClick:P=>{P.stopPropagation(),P.preventDefault(),s(V=>{const L=V.find(A=>A.id===`rowLevel${_}`);return L?L.desc?[]:[{id:`rowLevel${_}`,desc:!0}]:[{id:`rowLevel${_}`,desc:!1}]})},children:[c.jsx("span",{className:"truncate text-xs font-medium",title:k.label||k.name,children:k.label||k.name}),c.jsx(Oo,{className:J("h-3 w-3 flex-shrink-0",((B=r.find(P=>P.id===`rowLevel${_}`))==null?void 0:B.desc)===!1?"hidden group-hover/rowheader:block":"hidden")}),c.jsx(Qi,{className:J("h-3 w-3 flex-shrink-0",(($=r.find(P=>P.id===`rowLevel${_}`))==null?void 0:$.desc)===!0?"hidden group-hover/rowheader:block":"hidden")}),c.jsx(ju,{className:J("h-3 w-3 flex-shrink-0",r.find(P=>P.id===`rowLevel${_}`)?"hidden":"hidden group-hover/rowheader:block")})]})]}),M&&c.jsx(_u,{header:M,isResizing:M.column.getIsResizing()})]})},`row-header-corner-${_}`)}):c.jsx(oo,{colSpan:g,rowSpan:m+2,className:"h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-xs",children:""}),c.jsx(oo,{colSpan:b,className:"h-8 whitespace-nowrap border-b bg-muted px-3 py-1 text-xs font-bold",children:c.jsxs("div",{className:"group/pivot-main relative flex items-center",children:[i&&(()=>{var M,R;const k="pivot-main",_=l===k;return c.jsx("div",{className:J("absolute left-0 top-1/2 -translate-y-1/2 overflow-hidden transition-all duration-200",_?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/pivot-main:h-6 group-hover/pivot-main:w-6 group-hover/pivot-main:opacity-100"),children:c.jsx(zm,{columnName:"Pivot Columns",groupByFields:e.groupByColumns||[],pivotByFields:p,currentAggregation:{rowAggregates:(M=t.config)==null?void 0:M.rowAggregates,columnAggregates:(R=t.config)==null?void 0:R.columnAggregates},onAggregationChange:i,onOpenChange:O=>u(O?k:null)})})})(),c.jsx("div",{className:J("transition-all duration-200",i&&(l==="pivot-main"?"pl-7":"group-hover/pivot-main:pl-7")),children:p.map((k,_)=>c.jsxs("span",{className:"inline-flex items-center",children:[k.label,_<p.length-1&&c.jsx(Ci,{className:"mx-1 inline-block h-4 w-4 text-muted-foreground"})]},k.id))})]})},"pivot-hierarchy"),o&&(()=>{var M;const k=(M=n.getHeaderGroups()[0])==null?void 0:M.headers.find(R=>R.column.id==="rowTotal"),_=k==null?void 0:k.getSize();return c.jsx(oo,{"data-column-id":"rowTotal",className:"group/total h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-center text-xs",rowSpan:m+2,style:{width:_,minWidth:_,maxWidth:_,position:"relative",transition:"none"},children:(()=>{const R=n.getColumn("rowTotal");return R?c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs(oe,{variant:"ghost",className:"h-auto flex-shrink-0 p-0 hover:bg-transparent",onClick:()=>{const O=R.getIsSorted();s(O?O==="asc"?[{id:R.id,desc:!0}]:[]:[{id:R.id,desc:!1}])},"aria-label":"Sort Total",children:[c.jsx(Oo,{className:J("mr-1 h-3 w-3",R.getIsSorted()==="asc"?"hidden group-hover/total:block":"hidden")}),c.jsx(Qi,{className:J("mr-1 h-3 w-3",R.getIsSorted()==="desc"?"hidden group-hover/total:block":"hidden")}),c.jsx(ju,{className:J("mr-1 h-3 w-3",R.getIsSorted()?"hidden":"hidden group-hover/total:block")})]}),c.jsx("span",{className:"truncate text-xs font-medium",title:"Total",children:"Total"}),k&&c.jsx(_u,{header:k,isResizing:k.column.getIsResizing()})]}):"Total"})()},"pivot-hierarchy-total")})()]},"pivot-hierarchy"),w=[];if(e.columnGroups&&e.columnGroups.length>0){const k=Array.from({length:m},()=>[]);x(e.columnGroups,0,k,[]);for(let _=0;_<m;_++)w.push(c.jsx(lr,{"data-header-type":"pivot-values","data-header-row-index":_+1,"data-repeat-header":"true",children:k[_]},`pivot-row-${_}`))}let S=[];e.columnGroups&&e.columnGroups.length>0?S=y(e.columnGroups,[]):e.columnHeaders.forEach(k=>{var R,O,T,I,F,z;const _=n.getColumn(k),M=(R=n.getHeaderGroups()[0])==null?void 0:R.headers.find(B=>B.column.id===k);S.push(c.jsx(oo,{"data-column-id":k,className:"group/colheader h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-right text-xs last:border-r-0",style:{width:M==null?void 0:M.getSize(),minWidth:M==null?void 0:M.getSize(),maxWidth:M==null?void 0:M.getSize(),position:"relative",transition:"none"},children:_?c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs(oe,{variant:"ghost",className:"h-auto flex-shrink-0 p-0 hover:bg-transparent",onClick:()=>{const B=_.getIsSorted();s(B?B==="asc"?[{id:_.id,desc:!0}]:[]:[{id:_.id,desc:!1}])},"aria-label":`Sort ${((O=e.columnDisplayNames)==null?void 0:O[k])||k}`,children:[c.jsx(Oo,{className:J("mr-1 h-3 w-3",_.getIsSorted()==="asc"?"hidden group-hover/colheader:block":"hidden")}),c.jsx(Qi,{className:J("mr-1 h-3 w-3",_.getIsSorted()==="desc"?"hidden group-hover/colheader:block":"hidden")}),c.jsx(ju,{className:J("mr-1 h-3 w-3",_.getIsSorted()?"hidden":"hidden group-hover/colheader:block")})]}),c.jsx("span",{className:"min-w-0 truncate text-xs font-medium",title:((T=e.columnDisplayNames)==null?void 0:T[k])||k,children:((I=e.columnDisplayNames)==null?void 0:I[k])||k}),d&&a&&c.jsx(oe,{variant:"ghost",size:"icon",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover/colheader:opacity-100",onClick:B=>{B.stopPropagation(),a(k)},children:c.jsx(Qu,{className:"h-3 w-3"})}),M&&c.jsx(_u,{header:M,isResizing:M.column.getIsResizing()})]}):c.jsx("span",{className:"block truncate px-2",title:((F=e.columnDisplayNames)==null?void 0:F[k])||k,children:((z=e.columnDisplayNames)==null?void 0:z[k])||k})},k))});const C=c.jsxs(lr,{"data-header-type":"metrics","data-header-row-index":m>0?m+1:0,"data-repeat-header":"true",children:[m===0&&(e.groupByColumns&&e.groupByColumns.length>0?e.groupByColumns.map((k,_)=>{var I,F,z,B;const M=(I=n.getHeaderGroups()[0])==null?void 0:I.headers.find($=>$.column.id===`rowLevel${_}`),R=M==null?void 0:M.getSize(),O=`metric-row-${_}`,T=l===O;return c.jsx(oo,{"data-column-id":`rowLevel${_}`,className:"group/metricrow h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-left text-xs font-medium",style:{width:R,minWidth:R,maxWidth:R,position:"relative",transition:"none"},children:c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs("div",{className:"relative flex min-w-0 items-center",children:[i&&c.jsx("div",{className:J("absolute left-0 top-1/2 -translate-y-1/2 overflow-hidden transition-all duration-200",T?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/metricrow:h-6 group-hover/metricrow:w-6 group-hover/metricrow:opacity-100"),children:c.jsx(zm,{columnName:k.label||k.name,groupByFields:e.groupByColumns||[],pivotByFields:((F=t.config)==null?void 0:F.pivotByColumns)||[],currentAggregation:{rowAggregates:(z=t.config)==null?void 0:z.rowAggregates,columnAggregates:(B=t.config)==null?void 0:B.columnAggregates},onAggregationChange:i,onOpenChange:$=>u($?O:null)})}),c.jsxs(oe,{variant:"ghost",className:J("flex h-auto min-w-0 items-center gap-1 p-0 transition-all duration-200 hover:bg-transparent",i&&(T?"pl-7":"group-hover/metricrow:pl-7")),onClick:()=>{s($=>{const P=$.find(V=>V.id===`rowLevel${_}`);return P?P.desc===!1?[{id:`rowLevel${_}`,desc:!0}]:[]:[{id:`rowLevel${_}`,desc:!1}]})},children:[c.jsx("span",{className:"truncate text-xs font-medium",title:k.label||k.name,children:k.label||k.name}),(()=>{const $=r.find(P=>P.id===`rowLevel${_}`);return c.jsxs(c.Fragment,{children:[c.jsx(ju,{className:J("h-3 w-3 flex-shrink-0",$?"hidden":"hidden group-hover/metricrow:block")}),c.jsx(Qi,{className:J("h-3 w-3 flex-shrink-0",($==null?void 0:$.desc)===!0?"hidden group-hover/metricrow:block":"hidden")}),c.jsx(Oo,{className:J("h-3 w-3 flex-shrink-0",($==null?void 0:$.desc)===!1?"hidden group-hover/metricrow:block":"hidden")})]})})()]})]}),M&&c.jsx(_u,{header:M,isResizing:M.column.getIsResizing()})]})},`row-header-title-${_}`)}):Array.from({length:g}).map((k,_)=>c.jsx(oo,{className:"h-8 whitespace-nowrap border-b border-r bg-muted py-1 text-left text-xs font-medium",children:`Level ${_+1}`},`empty-header-metric-${_}`))),S]},"metric-row");return m>0?[v,...w,C]:[C]},[e,t,n,r,s,o,i,f,l,u,d,a])}}function IRe(e,t,n){var v,w;const r=ee(S=>S.isVisualEditing);ee(S=>S.isDashboardEditing),ee(S=>S.selectedSheetId);const{updateCurrentDashboardCard:s,updateFrame:o}=Yt(),i=ke(S=>{var C;return(C=S.actions)==null?void 0:C.setCardPreferences}),a=ke(S=>S.card),l=N.useMemo(()=>{var S,C;return((C=(S=e==null?void 0:e.preferences)==null?void 0:S.tablePrefs)==null?void 0:C.columnSettingsMap)||{}},[(w=(v=e==null?void 0:e.preferences)==null?void 0:v.tablePrefs)==null?void 0:w.columnSettingsMap]),[u,d]=N.useState(!1),[f,h]=N.useState(null),[p,m]=N.useState(zo()),g=N.useCallback(S=>{h(S);let C=l[S];if(!C){const j=t==null?void 0:t.map(D=>{var k,_;return{[S]:(_=(k=D.cells)==null?void 0:k[S])==null?void 0:_.value}});C=j&&j.length>0?Kg(S,j,n):zo()}m(C),d(!0)},[l,t,n]),b=N.useCallback(()=>{var S,C;if(f&&p){const j={...l,[f]:p};if(r&&i){const D={...a.preferences,tablePrefs:{...(S=a.preferences)==null?void 0:S.tablePrefs,columnSettingsMap:j}};i(D)}else if(s){const D={...e,preferences:{...e.preferences,tablePrefs:{...(C=e.preferences)==null?void 0:C.tablePrefs,columnSettingsMap:j}}};s(D)}}d(!1)},[f,p,l,r,i,a,s,e]),x=N.useCallback(()=>{f&&m(zo())},[f]),y=N.useCallback(()=>{var S,C;if(r&&i){const j={...a.preferences,tablePrefs:{...(S=a.preferences)==null?void 0:S.tablePrefs,columnSettingsMap:{}}};i(j)}else if(s){const j={...e,preferences:{...e.preferences,tablePrefs:{...(C=e.preferences)==null?void 0:C.tablePrefs,columnSettingsMap:{}}}};s(j)}d(!1)},[r,i,a,s,e]);return{columnSettings:l,columnSettingsOpen:u,activeColumnId:f,tempColumnSettings:p,isVisualEditing:r,openColumnSettings:g,applyColumnSettings:b,resetColumnSettings:x,resetAllColumnSettings:y,setColumnSettingsOpen:d,setTempColumnSettings:m}}function ARe({table:e,data:t,columns:n,subtotalColumnKeys:r,grandTotalColumnKeys:s,isTablePrintDisplayMode:o=!1,columnSettings:i,shouldVirtualizeRows:a=!1,virtualRows:l,paddingTop:u=0,paddingBottom:d=0,measureElement:f}){var x;const h=e.getRowModel().rows,p=((x=t.groupByColumns)==null?void 0:x.length)||1,g=a&&l&&l.length>0?l:h,b=n.length||1;return h!=null&&h.length?c.jsxs(c.Fragment,{children:[a&&u>0&&c.jsx(lr,{"aria-hidden":!0,className:"pointer-events-none border-none",children:c.jsx(gn,{colSpan:b,style:{height:u,padding:0,border:"none"}})}),g.map((y,v)=>{const w=a?y.index:v,S=a?h[w]:y;if(!S)return null;const C=S.original,j=e.getRowModel().rows,D=w===j.length-1;return c.jsx(lr,{ref:a&&f?k=>f(k):void 0,className:J("h-8 border-b-0",C.isSubtotal&&"border-t border-t-border/50 bg-muted/70 font-medium"),"data-row-type":C.isSubtotal?"subtotal":"data","data-row-index":w,...C.isSubtotal&&{"data-subtotal-level":C.subtotalLevel},children:S.getVisibleCells().map(k=>{var O;const _=k.column.id;if(_.startsWith("rowLevel")){const T=parseInt(_.replace("rowLevel",""));if(C.isSubtotal&&C.subtotalLevel){const F=((O=t.groupByColumns)==null?void 0:O.findIndex(z=>(z.alias||z.name)===C.subtotalLevel))??-1;return T===F?c.jsx(gn,{colSpan:o?1:p-T,className:J("h-8 whitespace-nowrap border-r px-3 py-1 text-xs font-medium",!D&&"border-b"),children:qs(k.column.columnDef.cell,k.getContext())},k.id):T<F?c.jsx(gn,{className:J("h-8 whitespace-nowrap border-r px-3 py-1 text-xs font-medium",!D&&"border-b"),children:qs(k.column.columnDef.cell,k.getContext())},k.id):o?c.jsx(gn,{className:J("h-8 whitespace-nowrap border-r px-3 py-1 text-xs",!D&&"border-b")},k.id):null}if(!a&&!o&&w>0)for(let F=w-1;F>=0;F--){const z=j[F].original;if(z.isSubtotal||z.isGrandTotal)break;let B=!0;for(let $=0;$<=T;$++)if(C.fieldValues[$]!==z.fieldValues[$]){B=!1;break}if(B)return null}let I=1;if(!a&&!o)for(let F=w+1;F<j.length;F++){const z=j[F].original;if(z.isSubtotal||z.isGrandTotal)break;let B=!0;for(let $=0;$<=T;$++)if(C.fieldValues[$]!==z.fieldValues[$]){B=!1;break}if(B)I++;else break}return c.jsx(gn,{rowSpan:a?void 0:I,className:J("h-8 whitespace-nowrap border-r px-3 py-1 text-xs",!D&&"border-b"),children:qs(k.column.columnDef.cell,k.getContext())},k.id)}const M=s.has(_),R=r.has(_);return c.jsx(gn,{"data-column-id":_,className:J("h-8 border-r px-3 py-1 text-xs last:border-r-0",!D&&"border-b",M?"bg-muted/50":R?"bg-muted/30":void 0),style:{width:k.column.getSize(),minWidth:k.column.getSize(),maxWidth:k.column.getSize(),transition:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:C.isSubtotal&&(i!=null&&i[_])?Qg(k.getValue(),i[_]):qs(k.column.columnDef.cell,k.getContext())},k.id)})},S.id)}),a&&d>0&&c.jsx(lr,{"aria-hidden":!0,className:"pointer-events-none border-none",children:c.jsx(gn,{colSpan:b,style:{height:d,padding:0,border:"none"}})})]}):c.jsx(lr,{className:"h-8",children:c.jsx(gn,{colSpan:n.length,className:"text-center",children:"No results."})})}function qo({value:e,displayTitle:t=!0,onSave:n,placeholder:r,inputClassName:s,displayClassName:o,isEditable:i=!0,isPending:a=!1}){const[l,u]=N.useState(!1),[d,f]=N.useState(e||""),h=()=>{u(!1),d!==e&&n(d)},p=m=>{m.key==="Enter"?(u(!1),n(d)):m.key==="Escape"&&(u(!1),f(e||""))};return l?c.jsx("div",{className:"flex",children:c.jsx("input",{type:"text",value:d,onChange:m=>f(m.target.value),onBlur:h,onKeyDown:p,onMouseDown:m=>m.stopPropagation(),className:J("w-full border-b border-dashed focus:border-primary focus:outline-none",s),autoFocus:!0})}):c.jsxs("div",{className:J("relative cursor-pointer truncate",o,{"cursor-default":!i,"hover:text-primary":i}),onClick:()=>{!i||a||(u(!0),f(e||""))},title:t?e||r:void 0,children:[c.jsx("div",{className:"flex items-center justify-between gap-2",children:c.jsx("span",{className:J("truncate",{"text-muted-foreground":a}),children:e||c.jsx("span",{className:"text-muted-foreground",children:r})})}),a&&c.jsx("div",{className:"absolute inset-0 animate-pulse rounded bg-gradient-to-r from-transparent via-blue-100/30 to-transparent"})]})}function PRe({grandTotalRows:e,data:t,card:n,table:r,showRowTotals:s,columnSettings:o,onAggregationLabelChange:i}){return e.length===0?null:c.jsx(c.Fragment,{children:e.map((a,l)=>{var u;return c.jsxs(lr,{className:"h-8 font-semibold","data-row-type":"grandtotal","data-grandtotal":"true","data-grandtotal-index":l,children:[c.jsx(gn,{colSpan:((u=t.groupByColumns)==null?void 0:u.length)||1,className:"h-8 whitespace-nowrap border-r px-3 py-1 text-xs font-semibold",children:i?c.jsx(qo,{value:(()=>{var h,p,m;const d=a.aggregateFunction||"SUM";return((m=(p=(h=n.config)==null?void 0:h.rowAggregates)==null?void 0:p.find(g=>g.function===d&&g.groupLevel==="ALL"))==null?void 0:m.label)||a.fieldValues[0]})(),placeholder:a.fieldValues[0],onSave:d=>{const f=a.aggregateFunction||"SUM";i({type:"row",level:"ALL",function:f,label:d})},displayClassName:"text-right"}):a.fieldValues[0]}),t.columnHeaders.map(d=>{var h,p;const f=(h=r.getHeaderGroups()[0])==null?void 0:h.headers.find(m=>m.column.id===d);return c.jsx(gn,{"data-column-id":d,className:"h-8 border-r px-3 py-1 text-right text-xs last:border-r-0",style:{width:f==null?void 0:f.getSize(),minWidth:f==null?void 0:f.getSize(),maxWidth:f==null?void 0:f.getSize(),transition:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Qg((p=a.cells[d])==null?void 0:p.value,o==null?void 0:o[d])},d)}),s&&(()=>{var h;const d=(h=r.getHeaderGroups()[0])==null?void 0:h.headers.find(p=>p.column.id==="rowTotal"),f=d==null?void 0:d.getSize();return c.jsx(gn,{className:"h-8 px-3 py-1 text-right text-xs font-medium","data-column-id":"rowTotal",style:{width:f,minWidth:f,maxWidth:f,transition:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Qg(Fq(a,t.columnHeaders))})})()]},a.id)})})}function ORe({groupByColumns:e,numRowLevels:t,onAggregationLabelChange:n,isTablePrintDisplayMode:r=!1}){const s=[];return e&&e.length>0?e.forEach((o,i)=>{s.push({id:`rowLevel${i}`,header:()=>c.jsx("div",{className:"group border border-border px-3 py-1 text-left font-medium text-muted-foreground",children:c.jsx("div",{className:"flex items-center gap-1",children:c.jsx("span",{className:"whitespace-nowrap",children:o.label||o.name})})}),accessorFn:a=>a.fieldValues[i],cell:({row:a,table:l})=>{const u=a.original;if(u.isSubtotal&&u.subtotalLevel){const p=(e==null?void 0:e.findIndex(m=>(m.alias||m.name)===u.subtotalLevel))??-1;if(i===p){const m=u.fieldValues[i];return c.jsx("div",{className:"whitespace-nowrap px-3 py-1 align-top text-xs font-medium",style:{gridColumn:`span ${t-i}`},children:m.includes(" Total")&&n?c.jsx(qo,{value:m,placeholder:m,onSave:g=>{const b=u.aggregateFunction||"SUM";if(u.subtotalLevel&&e){const x=e.find(y=>(y.alias||y.name)===u.subtotalLevel);x&&n({type:"row",level:x.id,function:b,label:g})}},displayClassName:"text-left"}):m})}else if(i<p)return c.jsx("div",{className:"whitespace-nowrap px-3 py-1 align-top text-xs font-medium",children:u.fieldValues[i]});return r?c.jsx("div",{className:"whitespace-nowrap px-3 py-1 align-top text-xs"}):null}const d=l.getRowModel().rows,f=d.findIndex(p=>p.id===a.id);if(!r&&f>0)for(let p=f-1;p>=0;p--){const m=d[p].original;if(m.isSubtotal||m.isGrandTotal)break;let g=!0;for(let b=0;b<=i;b++)if(u.fieldValues[b]!==m.fieldValues[b]){g=!1;break}if(g)return null}let h=1;if(!r)for(let p=f+1;p<d.length;p++){const m=d[p].original;if(m.isSubtotal||m.isGrandTotal)break;let g=!0;for(let b=0;b<=i;b++)if(u.fieldValues[b]!==m.fieldValues[b]){g=!1;break}if(g)h++;else break}return c.jsx("div",{className:"whitespace-nowrap px-0 py-1 align-top text-xs",style:{gridRow:r?void 0:`span ${h}`},children:u.fieldValues[i]})}})}):s.push({id:"rowHeader",header:()=>c.jsx("div",{className:"px-3 py-1 text-left font-medium",children:"Row"}),accessorFn:o=>o.rowKey,cell:({getValue:o})=>c.jsx("div",{className:"min-w-[150px] max-w-[300px] border-x border-y border-border px-3 py-1",children:String(o())})}),s}function FRe({columnHeaders:e,columnDisplayNames:t,setSorting:n,columnSettings:r,contextTimezone:s,browserTimezone:o}){return e.map(i=>({id:i,accessorFn:a=>{var l;return(l=a.cells[i])==null?void 0:l.value},header:({column:a})=>{const l=(t==null?void 0:t[i])||i;return c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsx(oe,{variant:"ghost",className:"h-auto p-0 hover:bg-transparent",onClick:()=>{const u=a.getIsSorted();n(u?u==="asc"?[{id:a.id,desc:!0}]:[]:[{id:a.id,desc:!1}])},"aria-label":`Sort ${l}`,children:a.getIsSorted()==="asc"?c.jsx(Oo,{className:"mr-1 h-3 w-3"}):a.getIsSorted()==="desc"?c.jsx(Qi,{className:"mr-1 h-3 w-3"}):c.jsx(ju,{className:"mr-1 h-3 w-3 opacity-0 group-hover:opacity-100"})}),c.jsx("span",{className:"text-xs font-medium",children:l})]})},cell:({getValue:a})=>{const l=a(),u=r==null?void 0:r[i],d=(u==null?void 0:u.textAlign)||"right",f=d==="left"?"text-left":d==="center"?"text-center":"text-right";return c.jsx("div",{className:`text-xs ${f}`,children:Qg(l,u,s,o)})}}))}function $Re({columnHeaders:e,setSorting:t}){return{id:"rowTotal",header:({column:n})=>c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsx(oe,{variant:"ghost",className:"h-auto p-0 hover:bg-transparent",onClick:()=>{const r=n.getIsSorted();t(r?r==="asc"?[{id:n.id,desc:!0}]:[]:[{id:n.id,desc:!1}])},"aria-label":"Sort Total",children:n.getIsSorted()==="asc"?c.jsx(Oo,{className:"mr-1 h-3 w-3"}):n.getIsSorted()==="desc"?c.jsx(Qi,{className:"mr-1 h-3 w-3"}):c.jsx(ju,{className:"mr-1 h-3 w-3 opacity-0 group-hover:opacity-100"})}),c.jsx("span",{className:"text-xs font-medium",children:"Total"})]}),cell:({row:n})=>{const r=n.original,s=Fq(r,e);return c.jsx("div",{className:"text-right text-xs font-medium",children:Qg(s)})}}}function cx({data:e,card:t,options:n={},onAggregationChange:r,onAggregationLabelChange:s}){var K,H,q;const o=ee(X=>X.themeStyle),{displayPreferences:i,shouldShowElement:a}=Hc(),l=i.mode==="table-print",u=N.useRef(null),d=n.showRowTotals??!1,{columnSizing:f,onColumnSizingChange:h}=WT({card:t}),{subtotalColumnKeys:p,grandTotalColumnKeys:m}=N.useMemo(()=>$ke(e.columnSubtotalMeta),[e.columnSubtotalMeta]),{tableData:g,grandTotalRows:b}=N.useMemo(()=>MT(e),[e]),{sorting:x,setSorting:y,sortedTableData:v}=DRe(g,e),{columnSettings:w,columnSettingsOpen:S,activeColumnId:C,tempColumnSettings:j,openColumnSettings:D,applyColumnSettings:k,resetColumnSettings:_,resetAllColumnSettings:M,setColumnSettingsOpen:R,setTempColumnSettings:O}=IRe(t,v,e.columnMetadata),T={...n.pagination},I=jRe(T,v.length),F=N.useMemo(()=>{var ne;const X=[],Z=((ne=e.groupByColumns)==null?void 0:ne.length)||1,G=ORe({groupByColumns:e.groupByColumns,numRowLevels:Z,onAggregationLabelChange:s,isTablePrintDisplayMode:l});X.push(...G);const Q=FRe({columnHeaders:e.columnHeaders,columnDisplayNames:e.columnDisplayNames,setSorting:y,columnSettings:w,contextTimezone:void 0,browserTimezone:typeof window<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0});if(X.push(...Q),d){const ae=$Re({columnHeaders:e.columnHeaders,setSorting:y});X.push(ae)}return X},[e,d,s,y,l,w]),z=VT({data:v,columns:F,state:{sorting:x,columnSizing:f,pagination:{pageIndex:I.pageIndex,pageSize:I.pageSize}},onSortingChange:y,onPaginationChange:void 0,getCoreRowModel:zT(),getPaginationRowModel:!I.isServerSidePagination&&!I.isTablePrintDisplayMode?BT():void 0,manualPagination:I.isServerSidePagination||I.isTablePrintDisplayMode,manualSorting:!0,pageCount:I.pageCount,enableColumnResizing:!0,columnResizeMode:"onChange",onColumnSizingChange:h}),B=z.getRowModel().rows,P=!l&&B.length>75,V=qT({count:P?B.length:0,getScrollElement:()=>u.current,estimateSize:()=>32,overscan:10}),L=P?V.getVirtualItems():[],A=P&&L.length>0?L[0].start:0,W=P&&L.length>0?V.getTotalSize()-L[L.length-1].end:0,{buildColumnHeaderRows:U}=RRe({data:e,card:t,table:z,sorting:x,setSorting:y,showRowTotals:d,onAggregationChange:r,onOpenColumnSettings:D}),Y=U();return c.jsxs("div",{className:"flex h-full w-full flex-col gap-4",children:[c.jsxs(vl,{ref:u,style:{borderRadius:o==null?void 0:o.cardBorderRadius},className:"relative h-full rounded-none border",onMouseDown:X=>X.stopPropagation(),children:[c.jsxs("table",{className:"w-full border-separate border-spacing-0 bg-background text-sm",onMouseDown:X=>X.stopPropagation(),"data-pivot-table":"true","data-row-levels":((K=e.groupByColumns)==null?void 0:K.length)||1,"data-pivot-levels":e.columnGroups&&((q=(H=t.config)==null?void 0:H.pivotByColumns)==null?void 0:q.length)||0,children:[c.jsx(sx,{className:"sticky top-0 z-20 bg-background",children:Y}),c.jsx(Wh,{children:c.jsx(ARe,{table:z,data:e,columns:F,subtotalColumnKeys:p,grandTotalColumnKeys:m,isTablePrintDisplayMode:l,columnSettings:w,shouldVirtualizeRows:P,virtualRows:L,paddingTop:A,paddingBottom:W,measureElement:P?V.measureElement:void 0})}),b.length>0&&c.jsx("tfoot",{className:"sticky bottom-0 z-10 border-t-2 border-t-border bg-muted","data-grandtotal":"true",children:c.jsx(PRe,{grandTotalRows:b,data:e,card:t,table:z,showRowTotals:d,columnSettings:w,onAggregationLabelChange:s})})]}),c.jsx(Zo,{orientation:"horizontal"}),c.jsx(Zo,{orientation:"vertical"})]}),I.showPagination&&c.jsx(HT,{totalColumns:F.length,pageCount:I.pageCount||z.getPageCount(),pageIndex:I.pageIndex,pageSize:I.pageSize,rowCount:I.totalCount,selectedRowCount:0,setPageIndex:I.setPageIndex,setPageSize:I.setPageSize,canPreviousPage:I.canPreviousPage,canNextPage:I.canNextPage,previousPage:I.previousPage,nextPage:I.nextPage,onClearSelection:()=>{}}),C&&c.jsx(UT,{column:z.getColumn(C)||null,settings:j,onSettingsChange:O,onApply:k,onReset:_,onResetAll:M,open:S,onOpenChange:R})]})}function LRe({isOpen:e,onClose:t,frame:n,card:r,data:s}){var D;const[o,i]=N.useState(!1),a=ee(k=>k.isDownloadingPdf),{isError:l,isLoading:u,isFetching:d,cfg:f,data:h,handleDatapointClick:p,pagination:m}=Xb(r),{customCards:g,placeholders:b}=qe(),x=$p(r,h),y=N.useMemo(()=>(h==null?void 0:h.records)||[],[h==null?void 0:h.records]),v=()=>{var _,M,R,O,T,I,F;const k=h||s;if(k!=null&&k.records&&k.records.length>0)if((r==null?void 0:r.type)==="aggregateTable"){const z=k.records.find(P=>P.isGrandTotal),B=k.records.filter(P=>!P.isGrandTotal),$=Iq(B,z,k.groupByColumns||[],k.pivotSchema||[],r,(M=(_=r==null?void 0:r.preferences)==null?void 0:_.tablePrefs)==null?void 0:M.columnSettingsMap);Jv($,`${(r==null?void 0:r.title)||"export"}.csv`)}else if((r==null?void 0:r.type)==="pivotTable"&&x)$q(x.data,r,`${(r==null?void 0:r.title)||"export"}.csv`,{includeHeaders:!0,includeSubtotals:!0,includeGrandTotal:!0,showRowTotals:(R=x.options)==null?void 0:R.showRowTotals});else if((r==null?void 0:r.type)==="table"){const z=((T=(O=r==null?void 0:r.preferences)==null?void 0:O.tablePrefs)==null?void 0:T.columnSettingsMap)||{},B=((F=(I=r==null?void 0:r.preferences)==null?void 0:I.tablePrefs)==null?void 0:F.columnVisibility)||{},P=Object.keys(k.records[0]||{}).filter(V=>B[V]!==!1);aEe(k.records,z,P,`${(r==null?void 0:r.title)||"export"}.csv`,void 0,Intl.DateTimeFormat().resolvedOptions().timeZone)}else{const z=[],B=Object.keys(k.records[0]);z.push(B.join(","));for(const P of k.records){const V=B.map(L=>`"${(""+P[L]).replace(/"/g,'""')}"`);z.push(V.join(","))}const $=z.join(`
|
|
964
|
+
*/var pRe="0.0.0-development";class ax extends Gs{initialize(){this.enableOptionSharing=!0,super.initialize()}update(t){const n=this._cachedMeta;this.updateElements(n.data,0,n.data.length,t)}updateElements(t,n,r,s){const o=s==="reset",{xScale:i,yScale:a}=this._cachedMeta,l=this.resolveDataElementOptions(n,s),u=this.getSharedOptions(l);for(let d=n;d<n+r;d++){const f=!o&&this.getParsed(d),h=o?i.getBasePixel():i.getPixelForValue(f.x),p=o?a.getBasePixel():a.getPixelForValue(f.y),m=this.resolveDataElementOptions(d,s),{width:g,height:b,anchorX:x,anchorY:y}=m,v={x:mRe(x,h,g),y:gRe(y,p,b),width:g,height:b,options:m};this.updateElement(t[d],d,v,s)}this.updateSharedOptions(u,s,l)}draw(){const t=this.chart.ctx,n=this.getMeta().data||[];let r,s;for(r=0,s=n.length;r<s;++r)n[r].draw(t)}}ax.id="matrix";ax.version=pRe;ax.defaults={dataElementType:"matrix",animations:{numbers:{type:"number",properties:["x","y","width","height"]}}};ax.overrides={interaction:{mode:"nearest",intersect:!0},scales:{x:{type:"linear",offset:!0},y:{type:"linear",reverse:!0}}};function mRe(e,t,n){return e==="left"||e==="start"?t:e==="right"||e==="end"?t-n:t-n/2}function gRe(e,t,n){return e==="top"||e==="start"?t:e==="bottom"||e==="end"?t-n:t-n/2}function dG(e,t){const{x:n,y:r,width:s,height:o}=e.getProps(["x","y","width","height"],t);return{left:n,top:r,right:n+s,bottom:r+o}}function ty(e,t,n){return Math.max(Math.min(e,n),t)}function bRe(e,t,n){const r=e.borderWidth;let s,o,i,a;return _t(r)?(s=+r.top||0,o=+r.right||0,i=+r.bottom||0,a=+r.left||0):s=o=i=a=+r||0,{t:ty(s,0,n),r:ty(o,0,t),b:ty(i,0,n),l:ty(a,0,t)}}function xRe(e){const t=dG(e,!1),n=t.right-t.left,r=t.bottom-t.top,s=bRe(e.options,n/2,r/2);return{outer:{x:t.left,y:t.top,w:n,h:r},inner:{x:t.left+s.l,y:t.top+s.t,w:n-s.l-s.r,h:r-s.t-s.b}}}function c2(e,t,n,r){const s=t===null,o=n===null,i=!e||s&&o?!1:dG(e,r);return i&&(s||t>=i.left&&t<=i.right)&&(o||n>=i.top&&n<=i.bottom)}class nR extends Qo{draw(t){const n=this.options,{inner:r,outer:s}=xRe(this),o=il(n.borderRadius);t.save(),s.w!==r.w||s.h!==r.h?(t.beginPath(),ol(t,{x:s.x,y:s.y,w:s.w,h:s.h,radius:o}),ol(t,{x:r.x,y:r.y,w:r.w,h:r.h,radius:o}),t.fillStyle=n.backgroundColor,t.fill(),t.fillStyle=n.borderColor,t.fill("evenodd")):(t.beginPath(),ol(t,{x:r.x,y:r.y,w:r.w,h:r.h,radius:o}),t.fillStyle=n.backgroundColor,t.fill()),t.restore()}inRange(t,n,r){return c2(this,t,n,r)}inXRange(t,n){return c2(this,t,null,n)}inYRange(t,n){return c2(this,null,t,n)}getCenterPoint(t){const{x:n,y:r,width:s,height:o}=this.getProps(["x","y","width","height"],t);return{x:n+s/2,y:r+o/2}}tooltipPosition(){return this.getCenterPoint()}getRange(t){return t==="x"?this.width/2:this.height/2}constructor(t){super(),t&&Object.assign(this,t)}}nR.id="matrix";nR.defaults={backgroundColor:void 0,borderColor:void 0,borderWidth:void 0,borderRadius:0,anchorX:"center",anchorY:"center",width:20,height:20};Kt.register(kDe);Kt.register(nd);Kt.register(kp);Kt.register(Ep);Kt.register(pl);Kt.register(Qd);Kt.register(Ec);Kt.register(_c);Kt.register(zg);Kt.register(QV);Kt.register(Up);Kt.register(Hp);Kt.register(wl);Kt.register(ix);Kt.register(ax);Kt.register(nR);function lx({cfg:e,onDatapointClick:t,onChartClick:n}){var p;const[r,s]=N.useState(""),o=ee(m=>m.selectedLensId),i=N.useRef(null),[a,l]=N.useState(),u=ee(m=>m.themeStyle);N.useEffect(()=>{if(i.current){const m=window.getComputedStyle(i.current);s(m.fontFamily)}},[]),N.useEffect(()=>{var x,y,v,w;if(!r)return;(y=(x=u==null?void 0:u.chart)==null?void 0:x.font)!=null&&y.family&&(Kt.defaults.font={...Kt.defaults.font,...(v=u==null?void 0:u.chart)==null?void 0:v.font,family:r});const m=Eg(e);m.options={...e.options,responsive:!0,maintainAspectRatio:!1};const g=(w=i==null?void 0:i.current)==null?void 0:w.getContext("2d");if(!g)return;let b;try{const S=KSe(m,g);b=new Kt(g,S),l(b)}catch(S){console.log("error creating chart",S)}return()=>{b&&b.destroy()}},[(p=u==null?void 0:u.chart)==null?void 0:p.font,o,r,e]);function d(m){console.log("handleRightClick",m),a&&(n==null||n(m,a,i))}function f(m){var b,x;if(!a)return;n==null||n(m,a,i);const g=a==null?void 0:a.getElementsAtEventForMode(m.nativeEvent,"nearest",{intersect:!0},!0);if(g&&g.length>0){const y=g[0].datasetIndex,v=g[0].index,w=(x=(b=g[0].element)==null?void 0:b.$context)==null?void 0:x.raw;t==null||t(a,y,v,w)}}const h=e.type==="doughnut"||e.type==="pie";return c.jsx("div",{onClick:f,onContextMenu:d,className:J("relative h-[99%] min-w-0 grow",{"mx-14":h}),children:c.jsx("canvas",{ref:i})})}async function yRe(e,t){if(!e||e.trim()==="")throw new Error("URL is required to load component");const r=`${e.endsWith("/")?e:`${e}/`}index.js`;return{default:(await new Function("url","return import(url)")(r))[t]}}async function vRe(e){try{const t=await import(e),n=Object.keys(t),r=[];return n.forEach(s=>{typeof t[s]=="function"&&(s==null?void 0:s[0])===(s==null?void 0:s[0].toUpperCase())&&r.push({name:s,component:s})}),r}catch(t){return console.error("Error loading the library:",t),[]}}async function fG(e){try{const t=e.endsWith("/")?e:`${e}/`,n=await fetch(`${t}manifest.json`);if(!n.ok)throw new Error(`Failed to fetch manifest: ${n.statusText}`);return await n.json()}catch(t){throw console.error("Error loading manifest:",t),t}}function hG(){const[e,t]=N.useState(!1);return N.useEffect(()=>{if(window.React&&window.ReactDOM){t(!0);return}window.React=N,window.ReactDOM=In,window.React.jsx=nA.jsx,window.React.jsxs=nA.jsxs,t(!0)},[]),e}const rR=e=>{const[t,n]=N.useState([]),[r,s]=N.useState(null),o=hG();N.useEffect(()=>{e&&e.trim()!==""&&o?fG(e).then(l=>{n(l.visuals),s(l)}).catch(()=>{vRe(e).then(l=>{n(l)}).catch(l=>{console.error("Error loading manifest:",l)})}):(n([]),s(null))},[e,o]);const i=N.useMemo(()=>!e||e.trim()===""||t.length===0?[]:(t==null?void 0:t.map(l=>{const{name:u,component:d,dataInputs:f,chartType:h}=l;return{name:u,chartType:h,componentName:d,Component:N.lazy(()=>yRe(e,d)),type:f&&f.length>1?"multiple":"single"}}))||[],[t,e]);return{getCard:N.useCallback(l=>{const u=i==null?void 0:i.find(d=>d.name===l);return u?u.Component:null},[i]),components:i,manifest:r}};function pG({onLoadingStatus:e,onDataChange:t,card:n}){const{isFetching:r,isLoading:s,data:o,queryKey:i}=fa(n),a=JSON.stringify(i);return N.useEffect(()=>{e==null||e(s)},[r,s,e]),N.useEffect(()=>{t(n.id,(o==null?void 0:o.records)||[])},[o==null?void 0:o.records,n.id,a,t]),c.jsx(c.Fragment,{})}function wRe({card:e,frame:t}){var O,T,I,F,z,B,$,P,V,L,A,W;const[n,r]=N.useState([]),{theme:s}=Xw(),{authToken:o}=qe(),i=v6(o==null?void 0:o.accessToken),a=ee(U=>U.themeStyle),l={colors:((T=(O=a==null?void 0:a.chart)==null?void 0:O.dataset)==null?void 0:T.backgroundColor)||[],mode:s||"system"},[u,d]=N.useState(!1),{getCard:f}=rR(((I=e.customCardPreferences)==null?void 0:I.url)||""),h=((F=e.customCardPreferences)==null?void 0:F.visualType)||"single",p=(z=e.customCardPreferences)==null?void 0:z.componentName,{data:m}=fa(e),g=It(U=>U.interactionStates),b=ee(U=>{var Y;return(Y=U.dashboard)==null?void 0:Y.id}),x=ee(U=>U.dashboard.filters),y=ee(U=>U.filterValues),v=ee(U=>U.selectedSheetId),{cardFilters:w,cardFilterValues:S,shouldApplyDashboardFilters:C,contextMode:j}=N.useMemo(()=>XD({card:e,interactionStates:g,currentDashboardId:b,filters:x,filterValues:y,selectedSheetId:v}),[e,g,b,x,y,v]),D=N.useCallback((U,Y)=>{r(K=>({...K,[U]:Y}))},[]);if(!p)return null;const k=f(p),_=Object.keys(((B=e.customCardPreferences)==null?void 0:B.dataInputCardIds)||{}).map(U=>{var H,q,X;const Y=(q=(H=e.customCardPreferences)==null?void 0:H.dataInputCardIds)==null?void 0:q[U].cardId,K=(X=t==null?void 0:t.cards)==null?void 0:X.find(Z=>Z.id===Y);return K||null});function M(U){d(U)}const R=((P=($=e.preferences)==null?void 0:$.displayOptions)==null?void 0:P.allowScroll)??!0;return c.jsx("div",{className:J("semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2",R?"overflow-y-auto":"h-full overflow-hidden"),children:c.jsxs(N.Suspense,{fallback:c.jsx(c.Fragment,{}),children:[k&&h==="single"&&c.jsx(k,{params:i,theme:l,chartSettings:(V=e.customCardPreferences)==null?void 0:V.settings,settings:(L=e.customCardPreferences)==null?void 0:L.settings,onDataChange:D,data:(m==null?void 0:m.records)||[],filters:w,filterValues:S}),k&&h==="multiple"&&c.jsxs("div",{children:[Object.keys(((A=e.customCardPreferences)==null?void 0:A.dataInputCardIds)||{}).map(U=>{var H,q,X;const Y=(q=(H=e.customCardPreferences)==null?void 0:H.dataInputCardIds)==null?void 0:q[U].cardId,K=(X=t==null?void 0:t.cards)==null?void 0:X.find(Z=>Z.id===Y);if(K)return c.jsx(pG,{onLoadingStatus:M,onDataChange:D,dataInputIndex:U,card:K},K.id+U)}),h==="multiple"&&c.jsx("div",{className:J("flex flex-col gap-2",{"opacity-50":u}),children:c.jsx(k,{params:i,theme:l,onDataChange:D,chartSettings:(W=e.customCardPreferences)==null?void 0:W.settings,settings:_.map(U=>{var Y;return(Y=U==null?void 0:U.customCardPreferences)==null?void 0:Y.settings}),data:_.map(U=>U!=null&&U.id?n==null?void 0:n[U.id]:[]),filters:w,filterValues:S})})]})]},e.id)})}const sR=N.memo(wRe,(e,t)=>{var n,r,s,o;return e.card.id===t.card.id&&e.frame.id===t.frame.id&&((n=e.card.customCardPreferences)==null?void 0:n.url)===((r=t.card.customCardPreferences)==null?void 0:r.url)&&((s=e.card.customCardPreferences)==null?void 0:s.componentName)===((o=t.card.customCardPreferences)==null?void 0:o.componentName)});function fS({customerFacingMessage:e,error:t,resetErrorBoundary:n}){return c.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center rounded-lg border border-dashed border-muted-foreground/25 bg-muted/30 p-6 text-center",children:[c.jsx("div",{className:"mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:c.jsx("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"})})}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"Chart Unavailable"}),c.jsx("p",{className:"mb-4 text-xs text-muted-foreground",children:e||"Couldn't display this chart right now. Please try refreshing or check your data configuration."}),c.jsxs("button",{onClick:n,className:"inline-flex items-center justify-center rounded-md bg-primary px-3 py-2 text-xs font-medium text-primary-foreground shadow-sm transition-colors hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",children:[c.jsx("svg",{className:"mr-1.5 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Try Again"]}),Yw]})}function hS({error:e}){return c.jsx("div",{className:"flex flex-col items-center justify-center",role:"alert",style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",width:"100%"},children:c.jsxs("div",{style:{backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",boxShadow:"0 2px 6px rgba(0, 0, 0, 0.08)",color:"#b91c1c",fontFamily:"sans-serif",padding:"16px",textAlign:"center",flexDirection:"column",whiteSpace:"pre-wrap",position:"relative"},className:"flex flex-col justify-center space-y-1 rounded-md bg-muted p-10",children:[c.jsx("p",{className:"text-sm",children:"Something went wrong:"}),c.jsx("pre",{className:"text-xs",children:e.message})]})})}function SRe({error:e,frame:t}){return c.jsxs("div",{className:"flex h-full flex-col items-center justify-center border",role:"alert",children:[c.jsx(uK,{frame:t,isHovered:!1}),c.jsx("div",{className:"flex flex-col justify-center space-y-2 rounded-md p-10"}),c.jsxs("div",{className:"flex flex-col justify-center space-y-2 rounded-md p-10",children:[c.jsx("p",{className:"text-lg font-semibold",children:"Oops! Looks like we tripped on a loose wire!"}),c.jsx("p",{className:"text-sm",children:"Something went wrong:"}),c.jsx("pre",{className:"text-xs",children:e.message})]})]})}const CRe=N.createContext(null),u2={didCatch:!1,error:null};class Sl extends N.Component{constructor(t){super(t),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=u2}static getDerivedStateFromError(t){return{didCatch:!0,error:t}}resetErrorBoundary(){const{error:t}=this.state;if(t!==null){for(var n,r,s=arguments.length,o=new Array(s),i=0;i<s;i++)o[i]=arguments[i];(n=(r=this.props).onReset)===null||n===void 0||n.call(r,{args:o,reason:"imperative-api"}),this.setState(u2)}}componentDidCatch(t,n){var r,s;(r=(s=this.props).onError)===null||r===void 0||r.call(s,t,n)}componentDidUpdate(t,n){const{didCatch:r}=this.state,{resetKeys:s}=this.props;if(r&&n.error!==null&&NRe(t.resetKeys,s)){var o,i;(o=(i=this.props).onReset)===null||o===void 0||o.call(i,{next:s,prev:t.resetKeys,reason:"keys"}),this.setState(u2)}}render(){const{children:t,fallbackRender:n,FallbackComponent:r,fallback:s}=this.props,{didCatch:o,error:i}=this.state;let a=t;if(o){const l={error:i,resetErrorBoundary:this.resetErrorBoundary};if(typeof n=="function")a=n(l);else if(r)a=N.createElement(r,l);else if(s!==void 0)a=s;else throw i}return N.createElement(CRe.Provider,{value:{didCatch:o,error:i,resetErrorBoundary:this.resetErrorBoundary}},a)}}function NRe(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];return e.length!==t.length||e.some((n,r)=>!Object.is(n,t[r]))}function jRe(e={},t){const{displayPreferences:n,shouldShowElement:r}=Hc(),s=n.mode==="table-print",o=e.enabled??!0,i=e.serverSide??!1,a=s?Number.MAX_SAFE_INTEGER:e.pageSize||50,l=e.currentPage!==void 0,[u,d]=N.useState(0),[f,h]=N.useState(a),p=l?(e.currentPage||1)-1:u,m=s?Number.MAX_SAFE_INTEGER:l?e.pageSize||a:f,g=N.useMemo(()=>o&&r("showPagination")&&!s,[o,r,s]),b=N.useMemo(()=>i?e.pageCount:Math.ceil(t/m),[i,e.pageCount,t,m]),x=N.useMemo(()=>i?e.totalCount||0:t,[i,e.totalCount,t]),y=N.useMemo(()=>i?(e.currentPage||1)>1:p>0,[i,e.currentPage,p]),v=N.useMemo(()=>i?(e.currentPage||1)<(e.pageCount||1):p<(b||1)-1,[i,e.currentPage,e.pageCount,p,b]);return{pageIndex:p,pageSize:m,isServerSidePagination:i,showPagination:g,paginationEnabled:o,isTablePrintDisplayMode:s,setPageIndex:D=>{var k;l?(k=e.onPageChange)==null||k.call(e,D+1,m):d(D)},setPageSize:D=>{var k;l?(k=e.onPageChange)==null||k.call(e,1,D):(d(0),h(D))},canPreviousPage:y,canNextPage:v,previousPage:()=>{var k;if(!y)return;const D=p-1;l?(k=e.onPageChange)==null||k.call(e,D+1,m):d(D)},nextPage:()=>{var k;if(!v)return;const D=p+1;l?(k=e.onPageChange)==null||k.call(e,D+1,m):d(D)},pageCount:b,totalCount:x}}function kRe(e,t,n){var l;if(!t.length)return e;const r=t[0].id,s=t[0].desc?-1:1,o=((l=n.groupByColumns)==null?void 0:l.length)||0,i=r.startsWith("rowLevel"),a=i?parseInt(r.replace("rowLevel","")):-1;return i?ERe(e,a,s):_Re(e,r,s,o,n)}function ERe(e,t,n){const r=[...e],s=new Map,o=[];r.forEach(l=>{if(l.isGrandTotal)return;const u=t>0?l.fieldValues.slice(0,t).join("|||"):"root";s.has(u)||(s.set(u,[]),o.push(u)),s.get(u).push(l)});const i=[];o.forEach(l=>{const u=s.get(l),d=u.filter(h=>!h.isSubtotal),f=u.filter(h=>h.isSubtotal);d.sort((h,p)=>{const m=h.fieldValues[t],g=p.fieldValues[t];return m===g?0:m==null?1:g==null?-1:String(m).localeCompare(String(g))*n}),i.push(...d),i.push(...f)});const a=e.find(l=>l.isGrandTotal);return a&&i.push(a),i}function _Re(e,t,n,r,s){const o={rows:[],children:new Map};let i;e.forEach(f=>{if(f.isGrandTotal){i=f;return}if(f.isSubtotal){let h=o;for(let p=0;p<r-1;p++){const m=f.fieldValues[p];h.children.has(m)||h.children.set(m,{rows:[],children:new Map}),h=h.children.get(m)}h.subtotal=f}else{let h=o;for(let p=0;p<r-1;p++){const m=f.fieldValues[p];h.children.has(m)||h.children.set(m,{rows:[],children:new Map}),h=h.children.get(m)}h.rows.push(f)}});function a(f){var h;return t==="rowTotal"?s.columnHeaders.reduce((p,m)=>{var b;const g=(b=f.cells[m])==null?void 0:b.value;return p+(typeof g=="number"?g:0)},0):(h=f.cells[t])==null?void 0:h.value}function l(f){let h=0;return f.rows.forEach(p=>{const m=a(p);typeof m=="number"&&(h+=m)}),f.children.forEach(p=>{if(p.subtotal){const m=a(p.subtotal);typeof m=="number"&&(h+=m)}else h+=l(p)}),h}function u(f){const h=[],p=[...f.rows].sort((g,b)=>{const x=a(g),y=a(b);return x===y?0:x==null?1:y==null?-1:x>y?n:-n});return h.push(...p),Array.from(f.children.entries()).sort(([,g],[,b])=>{const x=g.subtotal?a(g.subtotal):l(g),y=b.subtotal?a(b.subtotal):l(b);return x===y?0:x==null?1:y==null?-1:x>y?n:-n}).forEach(([,g])=>{h.push(...u(g))}),f.subtotal&&h.push(f.subtotal),h}const d=u(o);return i&&d.push(i),d}function DRe(e,t){const[n,r]=N.useState([]),s=N.useMemo(()=>kRe(e,n,t),[e,n,t]),o=N.useCallback(l=>{r(u=>{const d=u.find(f=>f.id===l);return d?d.desc?[]:[{id:l,desc:!0}]:[{id:l,desc:!1}]})},[]),i=N.useCallback(()=>{r([])},[]),a=N.useCallback(l=>{const u=n.find(d=>d.id===l);return u?u.desc?"desc":"asc":!1},[n]);return{sorting:n,setSorting:r,sortedTableData:s,toggleColumnSort:o,clearSorting:i,getSortDirection:a}}function Qg(e,t,n,r){if(t){const s=Xa(e,t,n,r),o=Hke(e,t);return s==="-"||s===0?c.jsx("div",{className:"flex justify-end",children:c.jsx(ku,{className:"h-3 w-3 text-muted-foreground"})}):o?c.jsx("span",{style:{backgroundColor:o.backgroundColor,color:o.color,padding:"0.125rem 0.25rem",borderRadius:"0.25rem"},children:s}):s}return typeof e=="object"&&(e==null?void 0:e.formattedValue)!==void 0?e.formattedValue==="-"||e.formattedValue===0?c.jsx("div",{className:"flex justify-end",children:c.jsx(ku,{className:"h-3 w-3 text-muted-foreground"})}):e.formattedValue:typeof e=="number"?e===0||e===null?c.jsx("div",{className:"flex justify-end",children:c.jsx(ku,{className:"h-3 w-3 text-muted-foreground"})}):e.toLocaleString():e==null?c.jsx("div",{className:"flex justify-end",children:c.jsx(ku,{className:"h-3 w-3 text-muted-foreground"})}):(e==null?void 0:e.toString())||c.jsx("div",{className:"flex justify-end",children:c.jsx(ku,{className:"h-3 w-3 text-muted-foreground"})})}function MRe(e){return(e==null?void 0:e.includes("_SUM_"))||(e==null?void 0:e.includes("_AVG_"))||(e==null?void 0:e.includes("_COUNT_"))||(e==null?void 0:e.includes("_MIN_"))||(e==null?void 0:e.includes("_MAX_"))}function TRe(e,t){const n=(e==null?void 0:e.includes("_SUM_ALL"))||(e==null?void 0:e.includes("_AVG_ALL"))||(e==null?void 0:e.includes("_COUNT_ALL"))||(e==null?void 0:e.includes("_MIN_ALL"))||(e==null?void 0:e.includes("_MAX_ALL")),r=(t==null?void 0:t.some(s=>s.columnName===e&&(s.subtotalLevel==="grandTotal"||s.subtotalLevel==="ALL")))??!1;return n||r}function RRe({data:e,card:t,table:n,sorting:r,setSorting:s,showRowTotals:o,onAggregationChange:i,onOpenColumnSettings:a}){const[l,u]=N.useState(null),d=ee(p=>p.isVisualEditing),f=N.useCallback(p=>{var m;return(m=n.getHeaderGroups()[0])==null?void 0:m.headers.find(g=>g.column.id===p)},[n]);return{buildColumnHeaderRows:N.useCallback(()=>{var j,D;const p=((j=t.config)==null?void 0:j.pivotByColumns)||[],m=p.length,g=((D=e.groupByColumns)==null?void 0:D.length)||1,b=e.columnHeaders.length;function x(k,_,M,R=[]){k.forEach((O,T)=>{var F,z,B;const I=O.level;if(I<m){const $=O.columnKey||`${I}-${R.join("-")}-${O.name}-${T}`,P=O.children?1:m-I,V=`pivot-${$}`,L=l===V;if(M[I].push(c.jsx(oo,{colSpan:O.colspan,rowSpan:P,className:"h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-center text-xs font-medium",children:c.jsxs("div",{className:"group/pivot-header relative flex items-center justify-center",children:[i&&c.jsx("div",{className:J("absolute left-0 overflow-hidden transition-all duration-200",L?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/pivot-header:h-6 group-hover/pivot-header:w-6 group-hover/pivot-header:opacity-100"),children:c.jsx(zm,{columnName:O.name,groupByFields:e.groupByColumns||[],pivotByFields:((F=t.config)==null?void 0:F.pivotByColumns)||[],currentAggregation:{rowAggregates:(z=t.config)==null?void 0:z.rowAggregates,columnAggregates:(B=t.config)==null?void 0:B.columnAggregates},onAggregationChange:i,onOpenChange:A=>u(A?V:null)})}),c.jsx("span",{className:"whitespace-nowrap",children:O.name})]})},$)),O.children){const A=[...R,O.name];x(O.children,I+1,M,A)}}})}function y(k,_=[]){const M=[];return k.forEach((R,O)=>{var T,I,F,z,B;if(R.columnKey){const $=R.columnKey||`metric-${_.join("-")}-${R.name}-${O}`,P=MRe(R.columnKey),V=TRe(R.columnKey,e.columnSubtotalMeta),L=n.getColumn(R.columnKey),A=f(R.columnKey);M.push(c.jsx(oo,{"data-column-id":R.columnKey,className:J("group/header h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-right text-xs last:border-r-0",V?"bg-muted font-semibold":P?"bg-muted/70 font-medium":""),style:{width:A==null?void 0:A.getSize(),minWidth:A==null?void 0:A.getSize(),maxWidth:A==null?void 0:A.getSize(),position:"relative",transition:"none"},children:L?c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs(oe,{variant:"ghost",className:"h-auto flex-shrink-0 p-0 hover:bg-transparent",onClick:()=>{const W=L.getIsSorted();s(W?W==="asc"?[{id:L.id,desc:!0}]:[]:[{id:L.id,desc:!1}])},"aria-label":`Sort ${((T=e.columnDisplayNames)==null?void 0:T[R.columnKey])||R.name||"Metric"}`,children:[c.jsx(Oo,{className:J("mr-1 h-3 w-3",L.getIsSorted()==="asc"?"hidden group-hover/header:block":"hidden")}),c.jsx(Qi,{className:J("mr-1 h-3 w-3",L.getIsSorted()==="desc"?"hidden group-hover/header:block":"hidden")}),c.jsx(ju,{className:J("mr-1 h-3 w-3",L.getIsSorted()?"hidden":"hidden group-hover/header:block")})]}),c.jsx("span",{className:"min-w-0 truncate text-xs font-medium",title:((I=e.columnDisplayNames)==null?void 0:I[R.columnKey])||R.name||"Metric",children:((F=e.columnDisplayNames)==null?void 0:F[R.columnKey])||R.name||"Metric"}),d&&a&&c.jsx(oe,{variant:"ghost",size:"icon",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover/header:opacity-100",onClick:W=>{W.stopPropagation(),a(R.columnKey)},children:c.jsx(Qu,{className:"h-3 w-3"})}),A&&c.jsx(_u,{header:A,isResizing:A.column.getIsResizing()})]}):c.jsx("span",{className:"block truncate px-2",title:((z=e.columnDisplayNames)==null?void 0:z[R.columnKey])||R.name||"Metric",children:((B=e.columnDisplayNames)==null?void 0:B[R.columnKey])||R.name||"Metric"})},$))}else if(R.children){const $=[..._,R.name];M.push(...y(R.children,$))}}),M}const v=c.jsxs(lr,{"data-header-type":"pivot-hierarchy","data-header-row-index":"0","data-repeat-header":"true",children:[e.groupByColumns&&e.groupByColumns.length>0?e.groupByColumns.map((k,_)=>{var I,F,z,B,$;const M=(I=n.getHeaderGroups()[0])==null?void 0:I.headers.find(P=>P.column.id===`rowLevel${_}`),R=M==null?void 0:M.getSize(),O=`row-header-${_}`,T=l===O;return c.jsx(oo,{rowSpan:m+2,"data-column-id":`rowLevel${_}`,className:"group/rowheader h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-left align-bottom text-xs font-medium",style:{width:R,minWidth:R,maxWidth:R,position:"relative",transition:"none"},children:c.jsxs("div",{className:"flex h-full min-w-0 items-end justify-between pb-1",children:[c.jsxs("div",{className:"relative flex min-w-0 items-center",children:[i&&c.jsx("div",{className:J("absolute left-0 top-1/2 -translate-y-1/2 overflow-hidden transition-all duration-200",T?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/rowheader:h-6 group-hover/rowheader:w-6 group-hover/rowheader:opacity-100"),children:c.jsx(zm,{columnName:k.label||k.name,groupByFields:e.groupByColumns||[],pivotByFields:p,currentAggregation:{rowAggregates:(F=t.config)==null?void 0:F.rowAggregates,columnAggregates:(z=t.config)==null?void 0:z.columnAggregates},onAggregationChange:i,onOpenChange:P=>u(P?O:null)})}),c.jsxs(oe,{variant:"ghost",className:J("flex h-auto min-w-0 items-center gap-1 p-0 transition-all duration-200 hover:bg-transparent",i&&(T?"pl-7":"group-hover/rowheader:pl-7")),onClick:P=>{P.stopPropagation(),P.preventDefault(),s(V=>{const L=V.find(A=>A.id===`rowLevel${_}`);return L?L.desc?[]:[{id:`rowLevel${_}`,desc:!0}]:[{id:`rowLevel${_}`,desc:!1}]})},children:[c.jsx("span",{className:"truncate text-xs font-medium",title:k.label||k.name,children:k.label||k.name}),c.jsx(Oo,{className:J("h-3 w-3 flex-shrink-0",((B=r.find(P=>P.id===`rowLevel${_}`))==null?void 0:B.desc)===!1?"hidden group-hover/rowheader:block":"hidden")}),c.jsx(Qi,{className:J("h-3 w-3 flex-shrink-0",(($=r.find(P=>P.id===`rowLevel${_}`))==null?void 0:$.desc)===!0?"hidden group-hover/rowheader:block":"hidden")}),c.jsx(ju,{className:J("h-3 w-3 flex-shrink-0",r.find(P=>P.id===`rowLevel${_}`)?"hidden":"hidden group-hover/rowheader:block")})]})]}),M&&c.jsx(_u,{header:M,isResizing:M.column.getIsResizing()})]})},`row-header-corner-${_}`)}):c.jsx(oo,{colSpan:g,rowSpan:m+2,className:"h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-xs",children:""}),c.jsx(oo,{colSpan:b,className:"h-8 whitespace-nowrap border-b bg-muted px-3 py-1 text-xs font-bold",children:c.jsxs("div",{className:"group/pivot-main relative flex items-center",children:[i&&(()=>{var M,R;const k="pivot-main",_=l===k;return c.jsx("div",{className:J("absolute left-0 top-1/2 -translate-y-1/2 overflow-hidden transition-all duration-200",_?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/pivot-main:h-6 group-hover/pivot-main:w-6 group-hover/pivot-main:opacity-100"),children:c.jsx(zm,{columnName:"Pivot Columns",groupByFields:e.groupByColumns||[],pivotByFields:p,currentAggregation:{rowAggregates:(M=t.config)==null?void 0:M.rowAggregates,columnAggregates:(R=t.config)==null?void 0:R.columnAggregates},onAggregationChange:i,onOpenChange:O=>u(O?k:null)})})})(),c.jsx("div",{className:J("transition-all duration-200",i&&(l==="pivot-main"?"pl-7":"group-hover/pivot-main:pl-7")),children:p.map((k,_)=>c.jsxs("span",{className:"inline-flex items-center",children:[k.label,_<p.length-1&&c.jsx(Ci,{className:"mx-1 inline-block h-4 w-4 text-muted-foreground"})]},k.id))})]})},"pivot-hierarchy"),o&&(()=>{var M;const k=(M=n.getHeaderGroups()[0])==null?void 0:M.headers.find(R=>R.column.id==="rowTotal"),_=k==null?void 0:k.getSize();return c.jsx(oo,{"data-column-id":"rowTotal",className:"group/total h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-center text-xs",rowSpan:m+2,style:{width:_,minWidth:_,maxWidth:_,position:"relative",transition:"none"},children:(()=>{const R=n.getColumn("rowTotal");return R?c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs(oe,{variant:"ghost",className:"h-auto flex-shrink-0 p-0 hover:bg-transparent",onClick:()=>{const O=R.getIsSorted();s(O?O==="asc"?[{id:R.id,desc:!0}]:[]:[{id:R.id,desc:!1}])},"aria-label":"Sort Total",children:[c.jsx(Oo,{className:J("mr-1 h-3 w-3",R.getIsSorted()==="asc"?"hidden group-hover/total:block":"hidden")}),c.jsx(Qi,{className:J("mr-1 h-3 w-3",R.getIsSorted()==="desc"?"hidden group-hover/total:block":"hidden")}),c.jsx(ju,{className:J("mr-1 h-3 w-3",R.getIsSorted()?"hidden":"hidden group-hover/total:block")})]}),c.jsx("span",{className:"truncate text-xs font-medium",title:"Total",children:"Total"}),k&&c.jsx(_u,{header:k,isResizing:k.column.getIsResizing()})]}):"Total"})()},"pivot-hierarchy-total")})()]},"pivot-hierarchy"),w=[];if(e.columnGroups&&e.columnGroups.length>0){const k=Array.from({length:m},()=>[]);x(e.columnGroups,0,k,[]);for(let _=0;_<m;_++)w.push(c.jsx(lr,{"data-header-type":"pivot-values","data-header-row-index":_+1,"data-repeat-header":"true",children:k[_]},`pivot-row-${_}`))}let S=[];e.columnGroups&&e.columnGroups.length>0?S=y(e.columnGroups,[]):e.columnHeaders.forEach(k=>{var R,O,T,I,F,z;const _=n.getColumn(k),M=(R=n.getHeaderGroups()[0])==null?void 0:R.headers.find(B=>B.column.id===k);S.push(c.jsx(oo,{"data-column-id":k,className:"group/colheader h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-right text-xs last:border-r-0",style:{width:M==null?void 0:M.getSize(),minWidth:M==null?void 0:M.getSize(),maxWidth:M==null?void 0:M.getSize(),position:"relative",transition:"none"},children:_?c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs(oe,{variant:"ghost",className:"h-auto flex-shrink-0 p-0 hover:bg-transparent",onClick:()=>{const B=_.getIsSorted();s(B?B==="asc"?[{id:_.id,desc:!0}]:[]:[{id:_.id,desc:!1}])},"aria-label":`Sort ${((O=e.columnDisplayNames)==null?void 0:O[k])||k}`,children:[c.jsx(Oo,{className:J("mr-1 h-3 w-3",_.getIsSorted()==="asc"?"hidden group-hover/colheader:block":"hidden")}),c.jsx(Qi,{className:J("mr-1 h-3 w-3",_.getIsSorted()==="desc"?"hidden group-hover/colheader:block":"hidden")}),c.jsx(ju,{className:J("mr-1 h-3 w-3",_.getIsSorted()?"hidden":"hidden group-hover/colheader:block")})]}),c.jsx("span",{className:"min-w-0 truncate text-xs font-medium",title:((T=e.columnDisplayNames)==null?void 0:T[k])||k,children:((I=e.columnDisplayNames)==null?void 0:I[k])||k}),d&&a&&c.jsx(oe,{variant:"ghost",size:"icon",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover/colheader:opacity-100",onClick:B=>{B.stopPropagation(),a(k)},children:c.jsx(Qu,{className:"h-3 w-3"})}),M&&c.jsx(_u,{header:M,isResizing:M.column.getIsResizing()})]}):c.jsx("span",{className:"block truncate px-2",title:((F=e.columnDisplayNames)==null?void 0:F[k])||k,children:((z=e.columnDisplayNames)==null?void 0:z[k])||k})},k))});const C=c.jsxs(lr,{"data-header-type":"metrics","data-header-row-index":m>0?m+1:0,"data-repeat-header":"true",children:[m===0&&(e.groupByColumns&&e.groupByColumns.length>0?e.groupByColumns.map((k,_)=>{var I,F,z,B;const M=(I=n.getHeaderGroups()[0])==null?void 0:I.headers.find($=>$.column.id===`rowLevel${_}`),R=M==null?void 0:M.getSize(),O=`metric-row-${_}`,T=l===O;return c.jsx(oo,{"data-column-id":`rowLevel${_}`,className:"group/metricrow h-8 whitespace-nowrap border-b border-r bg-muted px-3 py-1 text-left text-xs font-medium",style:{width:R,minWidth:R,maxWidth:R,position:"relative",transition:"none"},children:c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsxs("div",{className:"relative flex min-w-0 items-center",children:[i&&c.jsx("div",{className:J("absolute left-0 top-1/2 -translate-y-1/2 overflow-hidden transition-all duration-200",T?"h-6 w-6 opacity-100":"h-0 w-0 opacity-0 group-hover/metricrow:h-6 group-hover/metricrow:w-6 group-hover/metricrow:opacity-100"),children:c.jsx(zm,{columnName:k.label||k.name,groupByFields:e.groupByColumns||[],pivotByFields:((F=t.config)==null?void 0:F.pivotByColumns)||[],currentAggregation:{rowAggregates:(z=t.config)==null?void 0:z.rowAggregates,columnAggregates:(B=t.config)==null?void 0:B.columnAggregates},onAggregationChange:i,onOpenChange:$=>u($?O:null)})}),c.jsxs(oe,{variant:"ghost",className:J("flex h-auto min-w-0 items-center gap-1 p-0 transition-all duration-200 hover:bg-transparent",i&&(T?"pl-7":"group-hover/metricrow:pl-7")),onClick:()=>{s($=>{const P=$.find(V=>V.id===`rowLevel${_}`);return P?P.desc===!1?[{id:`rowLevel${_}`,desc:!0}]:[]:[{id:`rowLevel${_}`,desc:!1}]})},children:[c.jsx("span",{className:"truncate text-xs font-medium",title:k.label||k.name,children:k.label||k.name}),(()=>{const $=r.find(P=>P.id===`rowLevel${_}`);return c.jsxs(c.Fragment,{children:[c.jsx(ju,{className:J("h-3 w-3 flex-shrink-0",$?"hidden":"hidden group-hover/metricrow:block")}),c.jsx(Qi,{className:J("h-3 w-3 flex-shrink-0",($==null?void 0:$.desc)===!0?"hidden group-hover/metricrow:block":"hidden")}),c.jsx(Oo,{className:J("h-3 w-3 flex-shrink-0",($==null?void 0:$.desc)===!1?"hidden group-hover/metricrow:block":"hidden")})]})})()]})]}),M&&c.jsx(_u,{header:M,isResizing:M.column.getIsResizing()})]})},`row-header-title-${_}`)}):Array.from({length:g}).map((k,_)=>c.jsx(oo,{className:"h-8 whitespace-nowrap border-b border-r bg-muted py-1 text-left text-xs font-medium",children:`Level ${_+1}`},`empty-header-metric-${_}`))),S]},"metric-row");return m>0?[v,...w,C]:[C]},[e,t,n,r,s,o,i,f,l,u,d,a])}}function IRe(e,t,n){var v,w;const r=ee(S=>S.isVisualEditing);ee(S=>S.isDashboardEditing),ee(S=>S.selectedSheetId);const{updateCurrentDashboardCard:s,updateFrame:o}=Yt(),i=ke(S=>{var C;return(C=S.actions)==null?void 0:C.setCardPreferences}),a=ke(S=>S.card),l=N.useMemo(()=>{var S,C;return((C=(S=e==null?void 0:e.preferences)==null?void 0:S.tablePrefs)==null?void 0:C.columnSettingsMap)||{}},[(w=(v=e==null?void 0:e.preferences)==null?void 0:v.tablePrefs)==null?void 0:w.columnSettingsMap]),[u,d]=N.useState(!1),[f,h]=N.useState(null),[p,m]=N.useState(zo()),g=N.useCallback(S=>{h(S);let C=l[S];if(!C){const j=t==null?void 0:t.map(D=>{var k,_;return{[S]:(_=(k=D.cells)==null?void 0:k[S])==null?void 0:_.value}});C=j&&j.length>0?Kg(S,j,n):zo()}m(C),d(!0)},[l,t,n]),b=N.useCallback(()=>{var S,C;if(f&&p){const j={...l,[f]:p};if(r&&i){const D={...a.preferences,tablePrefs:{...(S=a.preferences)==null?void 0:S.tablePrefs,columnSettingsMap:j}};i(D)}else if(s){const D={...e,preferences:{...e.preferences,tablePrefs:{...(C=e.preferences)==null?void 0:C.tablePrefs,columnSettingsMap:j}}};s(D)}}d(!1)},[f,p,l,r,i,a,s,e]),x=N.useCallback(()=>{f&&m(zo())},[f]),y=N.useCallback(()=>{var S,C;if(r&&i){const j={...a.preferences,tablePrefs:{...(S=a.preferences)==null?void 0:S.tablePrefs,columnSettingsMap:{}}};i(j)}else if(s){const j={...e,preferences:{...e.preferences,tablePrefs:{...(C=e.preferences)==null?void 0:C.tablePrefs,columnSettingsMap:{}}}};s(j)}d(!1)},[r,i,a,s,e]);return{columnSettings:l,columnSettingsOpen:u,activeColumnId:f,tempColumnSettings:p,isVisualEditing:r,openColumnSettings:g,applyColumnSettings:b,resetColumnSettings:x,resetAllColumnSettings:y,setColumnSettingsOpen:d,setTempColumnSettings:m}}function ARe({table:e,data:t,columns:n,subtotalColumnKeys:r,grandTotalColumnKeys:s,isTablePrintDisplayMode:o=!1,columnSettings:i,shouldVirtualizeRows:a=!1,virtualRows:l,paddingTop:u=0,paddingBottom:d=0,measureElement:f}){var x;const h=e.getRowModel().rows,p=((x=t.groupByColumns)==null?void 0:x.length)||1,g=a&&l&&l.length>0?l:h,b=n.length||1;return h!=null&&h.length?c.jsxs(c.Fragment,{children:[a&&u>0&&c.jsx(lr,{"aria-hidden":!0,className:"pointer-events-none border-none",children:c.jsx(gn,{colSpan:b,style:{height:u,padding:0,border:"none"}})}),g.map((y,v)=>{const w=a?y.index:v,S=a?h[w]:y;if(!S)return null;const C=S.original,j=e.getRowModel().rows,D=w===j.length-1;return c.jsx(lr,{ref:a&&f?k=>f(k):void 0,className:J("h-8 border-b-0",C.isSubtotal&&"border-t border-t-border/50 bg-muted/70 font-medium"),"data-row-type":C.isSubtotal?"subtotal":"data","data-row-index":w,...C.isSubtotal&&{"data-subtotal-level":C.subtotalLevel},children:S.getVisibleCells().map(k=>{var O;const _=k.column.id;if(_.startsWith("rowLevel")){const T=parseInt(_.replace("rowLevel",""));if(C.isSubtotal&&C.subtotalLevel){const F=((O=t.groupByColumns)==null?void 0:O.findIndex(z=>(z.alias||z.name)===C.subtotalLevel))??-1;return T===F?c.jsx(gn,{colSpan:o?1:p-T,className:J("h-8 whitespace-nowrap border-r px-3 py-1 text-xs font-medium",!D&&"border-b"),children:qs(k.column.columnDef.cell,k.getContext())},k.id):T<F?c.jsx(gn,{className:J("h-8 whitespace-nowrap border-r px-3 py-1 text-xs font-medium",!D&&"border-b"),children:qs(k.column.columnDef.cell,k.getContext())},k.id):o?c.jsx(gn,{className:J("h-8 whitespace-nowrap border-r px-3 py-1 text-xs",!D&&"border-b")},k.id):null}if(!a&&!o&&w>0)for(let F=w-1;F>=0;F--){const z=j[F].original;if(z.isSubtotal||z.isGrandTotal)break;let B=!0;for(let $=0;$<=T;$++)if(C.fieldValues[$]!==z.fieldValues[$]){B=!1;break}if(B)return null}let I=1;if(!a&&!o)for(let F=w+1;F<j.length;F++){const z=j[F].original;if(z.isSubtotal||z.isGrandTotal)break;let B=!0;for(let $=0;$<=T;$++)if(C.fieldValues[$]!==z.fieldValues[$]){B=!1;break}if(B)I++;else break}return c.jsx(gn,{rowSpan:a?void 0:I,className:J("h-8 whitespace-nowrap border-r px-3 py-1 text-xs",!D&&"border-b"),children:qs(k.column.columnDef.cell,k.getContext())},k.id)}const M=s.has(_),R=r.has(_);return c.jsx(gn,{"data-column-id":_,className:J("h-8 border-r px-3 py-1 text-xs last:border-r-0",!D&&"border-b",M?"bg-muted/50":R?"bg-muted/30":void 0),style:{width:k.column.getSize(),minWidth:k.column.getSize(),maxWidth:k.column.getSize(),transition:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:C.isSubtotal&&(i!=null&&i[_])?Qg(k.getValue(),i[_]):qs(k.column.columnDef.cell,k.getContext())},k.id)})},S.id)}),a&&d>0&&c.jsx(lr,{"aria-hidden":!0,className:"pointer-events-none border-none",children:c.jsx(gn,{colSpan:b,style:{height:d,padding:0,border:"none"}})})]}):c.jsx(lr,{className:"h-8",children:c.jsx(gn,{colSpan:n.length,className:"text-center",children:"No results."})})}function qo({value:e,displayTitle:t=!0,onSave:n,placeholder:r,inputClassName:s,displayClassName:o,isEditable:i=!0,isPending:a=!1}){const[l,u]=N.useState(!1),[d,f]=N.useState(e||""),h=()=>{u(!1),d!==e&&n(d)},p=m=>{m.key==="Enter"?(u(!1),n(d)):m.key==="Escape"&&(u(!1),f(e||""))};return l?c.jsx("div",{className:"flex",children:c.jsx("input",{type:"text",value:d,onChange:m=>f(m.target.value),onBlur:h,onKeyDown:p,onMouseDown:m=>m.stopPropagation(),className:J("w-full border-b border-dashed focus:border-primary focus:outline-none",s),autoFocus:!0})}):c.jsxs("div",{className:J("relative cursor-pointer truncate",o,{"cursor-default":!i,"hover:text-primary":i}),onClick:()=>{!i||a||(u(!0),f(e||""))},title:t?e||r:void 0,children:[c.jsx("div",{className:"flex items-center justify-between gap-2",children:c.jsx("span",{className:J("truncate",{"text-muted-foreground":a}),children:e||c.jsx("span",{className:"text-muted-foreground",children:r})})}),a&&c.jsx("div",{className:"absolute inset-0 animate-pulse rounded bg-gradient-to-r from-transparent via-blue-100/30 to-transparent"})]})}function PRe({grandTotalRows:e,data:t,card:n,table:r,showRowTotals:s,columnSettings:o,onAggregationLabelChange:i}){return e.length===0?null:c.jsx(c.Fragment,{children:e.map((a,l)=>{var u;return c.jsxs(lr,{className:"h-8 font-semibold","data-row-type":"grandtotal","data-grandtotal":"true","data-grandtotal-index":l,children:[c.jsx(gn,{colSpan:((u=t.groupByColumns)==null?void 0:u.length)||1,className:"h-8 whitespace-nowrap border-r px-3 py-1 text-xs font-semibold",children:i?c.jsx(qo,{value:(()=>{var h,p,m;const d=a.aggregateFunction||"SUM";return((m=(p=(h=n.config)==null?void 0:h.rowAggregates)==null?void 0:p.find(g=>g.function===d&&g.groupLevel==="ALL"))==null?void 0:m.label)||a.fieldValues[0]})(),placeholder:a.fieldValues[0],onSave:d=>{const f=a.aggregateFunction||"SUM";i({type:"row",level:"ALL",function:f,label:d})},displayClassName:"text-right"}):a.fieldValues[0]}),t.columnHeaders.map(d=>{var h,p;const f=(h=r.getHeaderGroups()[0])==null?void 0:h.headers.find(m=>m.column.id===d);return c.jsx(gn,{"data-column-id":d,className:"h-8 border-r px-3 py-1 text-right text-xs last:border-r-0",style:{width:f==null?void 0:f.getSize(),minWidth:f==null?void 0:f.getSize(),maxWidth:f==null?void 0:f.getSize(),transition:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Qg((p=a.cells[d])==null?void 0:p.value,o==null?void 0:o[d])},d)}),s&&(()=>{var h;const d=(h=r.getHeaderGroups()[0])==null?void 0:h.headers.find(p=>p.column.id==="rowTotal"),f=d==null?void 0:d.getSize();return c.jsx(gn,{className:"h-8 px-3 py-1 text-right text-xs font-medium","data-column-id":"rowTotal",style:{width:f,minWidth:f,maxWidth:f,transition:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Qg(Fq(a,t.columnHeaders))})})()]},a.id)})})}function ORe({groupByColumns:e,numRowLevels:t,onAggregationLabelChange:n,isTablePrintDisplayMode:r=!1}){const s=[];return e&&e.length>0?e.forEach((o,i)=>{s.push({id:`rowLevel${i}`,header:()=>c.jsx("div",{className:"group border border-border px-3 py-1 text-left font-medium text-muted-foreground",children:c.jsx("div",{className:"flex items-center gap-1",children:c.jsx("span",{className:"whitespace-nowrap",children:o.label||o.name})})}),accessorFn:a=>a.fieldValues[i],cell:({row:a,table:l})=>{const u=a.original;if(u.isSubtotal&&u.subtotalLevel){const p=(e==null?void 0:e.findIndex(m=>(m.alias||m.name)===u.subtotalLevel))??-1;if(i===p){const m=u.fieldValues[i];return c.jsx("div",{className:"whitespace-nowrap px-3 py-1 align-top text-xs font-medium",style:{gridColumn:`span ${t-i}`},children:m.includes(" Total")&&n?c.jsx(qo,{value:m,placeholder:m,onSave:g=>{const b=u.aggregateFunction||"SUM";if(u.subtotalLevel&&e){const x=e.find(y=>(y.alias||y.name)===u.subtotalLevel);x&&n({type:"row",level:x.id,function:b,label:g})}},displayClassName:"text-left"}):m})}else if(i<p)return c.jsx("div",{className:"whitespace-nowrap px-3 py-1 align-top text-xs font-medium",children:u.fieldValues[i]});return r?c.jsx("div",{className:"whitespace-nowrap px-3 py-1 align-top text-xs"}):null}const d=l.getRowModel().rows,f=d.findIndex(p=>p.id===a.id);if(!r&&f>0)for(let p=f-1;p>=0;p--){const m=d[p].original;if(m.isSubtotal||m.isGrandTotal)break;let g=!0;for(let b=0;b<=i;b++)if(u.fieldValues[b]!==m.fieldValues[b]){g=!1;break}if(g)return null}let h=1;if(!r)for(let p=f+1;p<d.length;p++){const m=d[p].original;if(m.isSubtotal||m.isGrandTotal)break;let g=!0;for(let b=0;b<=i;b++)if(u.fieldValues[b]!==m.fieldValues[b]){g=!1;break}if(g)h++;else break}return c.jsx("div",{className:"whitespace-nowrap px-0 py-1 align-top text-xs",style:{gridRow:r?void 0:`span ${h}`},children:u.fieldValues[i]})}})}):s.push({id:"rowHeader",header:()=>c.jsx("div",{className:"px-3 py-1 text-left font-medium",children:"Row"}),accessorFn:o=>o.rowKey,cell:({getValue:o})=>c.jsx("div",{className:"min-w-[150px] max-w-[300px] border-x border-y border-border px-3 py-1",children:String(o())})}),s}function FRe({columnHeaders:e,columnDisplayNames:t,setSorting:n,columnSettings:r,contextTimezone:s,browserTimezone:o}){return e.map(i=>({id:i,accessorFn:a=>{var l;return(l=a.cells[i])==null?void 0:l.value},header:({column:a})=>{const l=(t==null?void 0:t[i])||i;return c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsx(oe,{variant:"ghost",className:"h-auto p-0 hover:bg-transparent",onClick:()=>{const u=a.getIsSorted();n(u?u==="asc"?[{id:a.id,desc:!0}]:[]:[{id:a.id,desc:!1}])},"aria-label":`Sort ${l}`,children:a.getIsSorted()==="asc"?c.jsx(Oo,{className:"mr-1 h-3 w-3"}):a.getIsSorted()==="desc"?c.jsx(Qi,{className:"mr-1 h-3 w-3"}):c.jsx(ju,{className:"mr-1 h-3 w-3 opacity-0 group-hover:opacity-100"})}),c.jsx("span",{className:"text-xs font-medium",children:l})]})},cell:({getValue:a})=>{const l=a(),u=r==null?void 0:r[i],d=(u==null?void 0:u.textAlign)||"right",f=d==="left"?"text-left":d==="center"?"text-center":"text-right";return c.jsx("div",{className:`text-xs ${f}`,children:Qg(l,u,s,o)})}}))}function $Re({columnHeaders:e,setSorting:t}){return{id:"rowTotal",header:({column:n})=>c.jsxs("div",{className:"flex w-full items-center justify-between",children:[c.jsx(oe,{variant:"ghost",className:"h-auto p-0 hover:bg-transparent",onClick:()=>{const r=n.getIsSorted();t(r?r==="asc"?[{id:n.id,desc:!0}]:[]:[{id:n.id,desc:!1}])},"aria-label":"Sort Total",children:n.getIsSorted()==="asc"?c.jsx(Oo,{className:"mr-1 h-3 w-3"}):n.getIsSorted()==="desc"?c.jsx(Qi,{className:"mr-1 h-3 w-3"}):c.jsx(ju,{className:"mr-1 h-3 w-3 opacity-0 group-hover:opacity-100"})}),c.jsx("span",{className:"text-xs font-medium",children:"Total"})]}),cell:({row:n})=>{const r=n.original,s=Fq(r,e);return c.jsx("div",{className:"text-right text-xs font-medium",children:Qg(s)})}}}function cx({data:e,card:t,options:n={},onAggregationChange:r,onAggregationLabelChange:s}){var K,H,q;const o=ee(X=>X.themeStyle),{displayPreferences:i,shouldShowElement:a}=Hc(),l=i.mode==="table-print",u=N.useRef(null),d=n.showRowTotals??!1,{columnSizing:f,onColumnSizingChange:h}=WT({card:t}),{subtotalColumnKeys:p,grandTotalColumnKeys:m}=N.useMemo(()=>$ke(e.columnSubtotalMeta),[e.columnSubtotalMeta]),{tableData:g,grandTotalRows:b}=N.useMemo(()=>MT(e),[e]),{sorting:x,setSorting:y,sortedTableData:v}=DRe(g,e),{columnSettings:w,columnSettingsOpen:S,activeColumnId:C,tempColumnSettings:j,openColumnSettings:D,applyColumnSettings:k,resetColumnSettings:_,resetAllColumnSettings:M,setColumnSettingsOpen:R,setTempColumnSettings:O}=IRe(t,v,e.columnMetadata),T={...n.pagination},I=jRe(T,v.length),F=N.useMemo(()=>{var ne;const X=[],Z=((ne=e.groupByColumns)==null?void 0:ne.length)||1,G=ORe({groupByColumns:e.groupByColumns,numRowLevels:Z,onAggregationLabelChange:s,isTablePrintDisplayMode:l});X.push(...G);const Q=FRe({columnHeaders:e.columnHeaders,columnDisplayNames:e.columnDisplayNames,setSorting:y,columnSettings:w,contextTimezone:void 0,browserTimezone:typeof window<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0});if(X.push(...Q),d){const ae=$Re({columnHeaders:e.columnHeaders,setSorting:y});X.push(ae)}return X},[e,d,s,y,l,w]),z=VT({data:v,columns:F,state:{sorting:x,columnSizing:f,pagination:{pageIndex:I.pageIndex,pageSize:I.pageSize}},onSortingChange:y,onPaginationChange:void 0,getCoreRowModel:zT(),getPaginationRowModel:!I.isServerSidePagination&&!I.isTablePrintDisplayMode?BT():void 0,manualPagination:I.isServerSidePagination||I.isTablePrintDisplayMode,manualSorting:!0,pageCount:I.pageCount,enableColumnResizing:!0,columnResizeMode:"onChange",onColumnSizingChange:h}),B=z.getRowModel().rows,P=!l&&B.length>75,V=qT({count:P?B.length:0,getScrollElement:()=>u.current,estimateSize:()=>32,overscan:10}),L=P?V.getVirtualItems():[],A=P&&L.length>0?L[0].start:0,W=P&&L.length>0?V.getTotalSize()-L[L.length-1].end:0,{buildColumnHeaderRows:U}=RRe({data:e,card:t,table:z,sorting:x,setSorting:y,showRowTotals:d,onAggregationChange:r,onOpenColumnSettings:D}),Y=U();return c.jsxs("div",{className:"flex h-full w-full flex-col gap-4",children:[c.jsxs(vl,{ref:u,style:{borderRadius:o==null?void 0:o.cardBorderRadius},className:"relative h-full rounded-none border",onMouseDown:X=>X.stopPropagation(),children:[c.jsxs("table",{className:"w-full border-separate border-spacing-0 bg-background text-sm",onMouseDown:X=>X.stopPropagation(),"data-pivot-table":"true","data-row-levels":((K=e.groupByColumns)==null?void 0:K.length)||1,"data-pivot-levels":e.columnGroups&&((q=(H=t.config)==null?void 0:H.pivotByColumns)==null?void 0:q.length)||0,children:[c.jsx(sx,{className:"sticky top-0 z-20 bg-background",children:Y}),c.jsx(Wh,{children:c.jsx(ARe,{table:z,data:e,columns:F,subtotalColumnKeys:p,grandTotalColumnKeys:m,isTablePrintDisplayMode:l,columnSettings:w,shouldVirtualizeRows:P,virtualRows:L,paddingTop:A,paddingBottom:W,measureElement:P?V.measureElement:void 0})}),b.length>0&&c.jsx("tfoot",{className:"sticky bottom-0 z-10 border-t-2 border-t-border bg-muted","data-grandtotal":"true",children:c.jsx(PRe,{grandTotalRows:b,data:e,card:t,table:z,showRowTotals:d,columnSettings:w,onAggregationLabelChange:s})})]}),c.jsx(Zo,{orientation:"horizontal"}),c.jsx(Zo,{orientation:"vertical"})]}),I.showPagination&&c.jsx(HT,{totalColumns:F.length,pageCount:I.pageCount||z.getPageCount(),pageIndex:I.pageIndex,pageSize:I.pageSize,rowCount:I.totalCount,selectedRowCount:0,setPageIndex:I.setPageIndex,setPageSize:I.setPageSize,canPreviousPage:I.canPreviousPage,canNextPage:I.canNextPage,previousPage:I.previousPage,nextPage:I.nextPage,onClearSelection:()=>{}}),C&&c.jsx(UT,{column:z.getColumn(C)||null,settings:j,onSettingsChange:O,onApply:k,onReset:_,onResetAll:M,open:S,onOpenChange:R})]})}function LRe({isOpen:e,onClose:t,frame:n,card:r,data:s}){var D;const[o,i]=N.useState(!1),a=ee(k=>k.isDownloadingPdf),{isError:l,isLoading:u,isFetching:d,cfg:f,data:h,handleDatapointClick:p,pagination:m}=Xb(r),{customCards:g,placeholders:b}=qe(),x=$p(r,h),y=N.useMemo(()=>(h==null?void 0:h.records)||[],[h==null?void 0:h.records]),v=()=>{var _,M,R,O,T,I,F;const k=h||s;if(k!=null&&k.records&&k.records.length>0)if((r==null?void 0:r.type)==="aggregateTable"){const z=k.records.find(P=>P.isGrandTotal),B=k.records.filter(P=>!P.isGrandTotal),$=Iq(B,z,k.groupByColumns||[],k.pivotSchema||[],r,(M=(_=r==null?void 0:r.preferences)==null?void 0:_.tablePrefs)==null?void 0:M.columnSettingsMap);Jv($,`${(r==null?void 0:r.title)||"export"}.csv`)}else if((r==null?void 0:r.type)==="pivotTable"&&x)$q(x.data,r,`${(r==null?void 0:r.title)||"export"}.csv`,{includeHeaders:!0,includeSubtotals:!0,includeGrandTotal:!0,showRowTotals:(R=x.options)==null?void 0:R.showRowTotals});else if((r==null?void 0:r.type)==="table"){const z=((T=(O=r==null?void 0:r.preferences)==null?void 0:O.tablePrefs)==null?void 0:T.columnSettingsMap)||{},B=((F=(I=r==null?void 0:r.preferences)==null?void 0:I.tablePrefs)==null?void 0:F.columnVisibility)||{},P=Object.keys(k.records[0]||{}).filter(V=>B[V]!==!1);aEe(k.records,z,P,`${(r==null?void 0:r.title)||"export"}.csv`,void 0,Intl.DateTimeFormat().resolvedOptions().timeZone)}else{const z=[],B=Object.keys(k.records[0]);z.push(B.join(","));for(const P of k.records){const V=B.map(L=>`"${(""+P[L]).replace(/"/g,'""')}"`);z.push(V.join(","))}const $=z.join(`
|
|
965
965
|
`);Jv($,`${(r==null?void 0:r.title)||"export"}.csv`)}},w=()=>{i(!0)},S=(r==null?void 0:r.type)==="table"||(r==null?void 0:r.type)==="aggregateTable",C=((D=r==null?void 0:r.preferences)==null?void 0:D.allowDownload)!==!1,j=()=>{if(!r)return null;if(l)return c.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[c.jsx(sD,{className:"size-8 text-destructive"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Error fetching data. Check your card settings."})]});if(u||d)return c.jsx("div",{className:"flex h-full w-full items-center justify-center",children:c.jsx(Mc,{size:"md",color:"muted","aria-label":"Loading data"})});if(h!=null&&h.records&&(h==null?void 0:h.records.length)===0)return b!=null&&b.NoRecords?c.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:b.NoRecords}):c.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[c.jsx(lD,{className:"size-8 text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(r.type==="table")return c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(ox,{card:r,data:y,paginationMetadata:m,onPaginationChange:()=>{},isLoading:u||d})});if(r.type==="pivotTable"&&x)return c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(cx,{card:r,data:x.data,options:x.options,onAggregationChange:()=>{},onAggregationLabelChange:()=>{}})});if(r.type==="aggregateTable")return c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(cS,{card:r,data:(h==null?void 0:h.records)||[],groupByColumns:h==null?void 0:h.groupByColumns,pivotSchema:h==null?void 0:h.pivotSchema,paginationMetadata:m,onPaginationChange:()=>{},onAggregationChange:()=>{},isLoading:u||d})});if(r.type==="text")return c.jsx(Ds,{className:"overflow-y-auto break-words pr-2",children:c.jsx(qh,{isLoading:u||d,card:r,data:(h==null?void 0:h.records)||[]})});if(r.type==="custom")return c.jsx(Sl,{FallbackComponent:fS,children:c.jsx(sR,{frame:n,card:r})});if(f)return c.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:c.jsx(lx,{cfg:f,onChartClick:()=>{},onDatapointClick:p})});if(g&&g.length>0){const k=g.find(_=>_.cardId===r.id);if(k&&k.content){const _=k.content;return c.jsx(_,{card:r})}}return null};return c.jsxs(c.Fragment,{children:[c.jsx(ls,{open:e,onOpenChange:t,children:c.jsxs(Vr,{className:"flex h-[80vh] w-[80vw] max-w-[80vw] flex-col gap-0 p-0 [&>button]:hidden",children:[c.jsxs(Hr,{className:"shrink-0 border-b px-6 py-4",children:[c.jsx(Ur,{className:"text-lg font-semibold",children:(r==null?void 0:r.title)||"Visual"}),c.jsxs(Rs,{className:"sr-only",children:["Expanded view of ",(r==null?void 0:r.title)||"visual"," card showing detailed data and export options"]})]}),c.jsxs("div",{className:"flex items-center gap-2 border-b px-6 py-3",children:[C&&c.jsxs(oe,{variant:"ghost",size:"sm",onClick:v,title:"Download CSV",children:[c.jsx(Ni,{className:"mr-2 h-4 w-4"}),"CSV"]}),S&&c.jsxs(oe,{variant:"ghost",size:"sm",onClick:w,disabled:a,title:"Download PDF",children:[c.jsx(n1,{className:"mr-2 h-4 w-4"}),"PDF"]}),c.jsx(oe,{variant:"ghost",size:"icon",onClick:t,className:"ml-auto h-8 w-8",children:c.jsx(vt,{className:"h-4 w-4"})})]}),c.jsx("div",{className:"flex flex-1 overflow-hidden p-6",children:j()})]})}),o&&c.jsx(Wq,{isOpen:o,onClose:()=>i(!1),frame:n,card:r,data:h||s})]})}function oR(e){var o;const t=e.activeCardId,n=new Map,r=e.cards.map(i=>{const a=i.id,l=jr();return n.set(a,l),{...i,id:l}});let s=(o=r[0])==null?void 0:o.id;return t&&n.has(t)&&(s=n.get(t)),{...e,id:jr(),cards:r,activeCardId:s}}var mG=E.forwardRef((e,t)=>{const{children:n,...r}=e,s=E.Children.toArray(n),o=s.find(BRe);if(o){const i=o.props.children,a=s.map(l=>l===o?E.Children.count(i)>1?E.Children.only(null):E.isValidElement(i)?i.props.children:null:l);return c.jsx(vE,{...r,ref:t,children:E.isValidElement(i)?E.cloneElement(i,void 0,a):null})}return c.jsx(vE,{...r,ref:t,children:n})});mG.displayName="Slot";var vE=E.forwardRef((e,t)=>{const{children:n,...r}=e;if(E.isValidElement(n)){const s=HRe(n),o=VRe(r,n.props);return n.type!==E.Fragment&&(o.ref=t?Es(t,s):s),E.cloneElement(n,o)}return E.Children.count(n)>1?E.Children.only(null):null});vE.displayName="SlotClone";var zRe=({children:e})=>c.jsx(c.Fragment,{children:e});function BRe(e){return E.isValidElement(e)&&e.type===zRe}function VRe(e,t){const n={...t};for(const r in t){const s=e[r],o=t[r];/^on[A-Z]/.test(r)?s&&o?n[r]=(...a)=>{o(...a),s(...a)}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}function HRe(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var iR="Popover",[gG]=_r(iR,[va]),ux=va(),[URe,tu]=gG(iR),bG=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:s,onOpenChange:o,modal:i=!1}=e,a=ux(t),l=E.useRef(null),[u,d]=E.useState(!1),[f=!1,h]=$r({prop:r,defaultProp:s,onChange:o});return c.jsx(lp,{...a,children:c.jsx(URe,{scope:t,contentId:nr(),triggerRef:l,open:f,onOpenChange:h,onOpenToggle:E.useCallback(()=>h(p=>!p),[h]),hasCustomAnchor:u,onCustomAnchorAdd:E.useCallback(()=>d(!0),[]),onCustomAnchorRemove:E.useCallback(()=>d(!1),[]),modal:i,children:n})})};bG.displayName=iR;var xG="PopoverAnchor",WRe=E.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=tu(xG,n),o=ux(n),{onCustomAnchorAdd:i,onCustomAnchorRemove:a}=s;return E.useEffect(()=>(i(),()=>a()),[i,a]),c.jsx(cp,{...o,...r,ref:t})});WRe.displayName=xG;var yG="PopoverTrigger",vG=E.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=tu(yG,n),o=ux(n),i=ft(t,s.triggerRef),a=c.jsx(Be.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":kG(s.open),...r,ref:i,onClick:Ee(e.onClick,s.onOpenToggle)});return s.hasCustomAnchor?a:c.jsx(cp,{asChild:!0,...o,children:a})});vG.displayName=yG;var aR="PopoverPortal",[qRe,YRe]=gG(aR,{forceMount:void 0}),wG=e=>{const{__scopePopover:t,forceMount:n,children:r,container:s}=e,o=tu(aR,t);return c.jsx(qRe,{scope:t,forceMount:n,children:c.jsx(sr,{present:n||o.open,children:c.jsx(Wd,{asChild:!0,container:s,children:r})})})};wG.displayName=aR;var Kh="PopoverContent",SG=E.forwardRef((e,t)=>{const n=YRe(Kh,e.__scopePopover),{forceMount:r=n.forceMount,...s}=e,o=tu(Kh,e.__scopePopover);return c.jsx(sr,{present:r||o.open,children:o.modal?c.jsx(GRe,{...s,ref:t}):c.jsx(KRe,{...s,ref:t})})});SG.displayName=Kh;var GRe=E.forwardRef((e,t)=>{const n=tu(Kh,e.__scopePopover),r=E.useRef(null),s=ft(t,r),o=E.useRef(!1);return E.useEffect(()=>{const i=r.current;if(i)return zb(i)},[]),c.jsx(dp,{as:mG,allowPinchZoom:!0,children:c.jsx(CG,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ee(e.onCloseAutoFocus,i=>{var a;i.preventDefault(),o.current||(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Ee(e.onPointerDownOutside,i=>{const a=i.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,u=a.button===2||l;o.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:Ee(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1})})})}),KRe=E.forwardRef((e,t)=>{const n=tu(Kh,e.__scopePopover),r=E.useRef(!1),s=E.useRef(!1);return c.jsx(CG,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,o),o.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),o.preventDefault()),r.current=!1,s.current=!1},onInteractOutside:o=>{var l,u;(l=e.onInteractOutside)==null||l.call(e,o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const i=o.target;((u=n.triggerRef.current)==null?void 0:u.contains(i))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&s.current&&o.preventDefault()}})}),CG=E.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:i,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:d,...f}=e,h=tu(Kh,n),p=ux(n);return c1(),c.jsx(op,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:o,children:c.jsx(Ud,{asChild:!0,disableOutsidePointerEvents:i,onInteractOutside:d,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:u,onDismiss:()=>h.onOpenChange(!1),children:c.jsx($b,{"data-state":kG(h.open),role:"dialog",id:h.contentId,...p,...f,ref:t,style:{...f.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),NG="PopoverClose",ZRe=E.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=tu(NG,n);return c.jsx(Be.button,{type:"button",...r,ref:t,onClick:Ee(e.onClick,()=>s.onOpenChange(!1))})});ZRe.displayName=NG;var XRe="PopoverArrow",jG=E.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=ux(n);return c.jsx(Lb,{...s,...r,ref:t})});jG.displayName=XRe;function kG(e){return e?"open":"closed"}var QRe=bG,JRe=vG,eIe=wG,pS=SG,tIe=jG;const Ns=QRe,js=JRe,ks=E.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},s)=>c.jsx(eIe,{children:c.jsx(wa,{children:c.jsx(pS,{ref:s,align:t,sideOffset:n,className:J("z-49 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})})}));ks.displayName=pS.displayName;function nIe({emails:e,onChange:t}){const[n,r]=N.useState(""),[s,o]=N.useState(null),i=d=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d),a=()=>{if(o(null),!n.trim()){o("Please enter at least one email address");return}const d=n.split(/[,;]/).map(p=>p.trim()).filter(p=>p),f=d.filter(p=>!i(p));if(f.length>0){o(`Invalid email${f.length>1?"s":""}: ${f.join(", ")}`);return}const h=d.filter(p=>!e.includes(p));if(h.length===0){o("Email address already added");return}t([...e,...h]),r("")},l=d=>{t(e.filter(f=>f!==d))},u=d=>{d.key==="Enter"&&(d.preventDefault(),a())};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex gap-2",children:[c.jsx(Nn,{type:"text",placeholder:"email@company.com, team@company.com",value:n,onChange:d=>{r(d.target.value),o(null)},onKeyPress:u,className:J(s&&"border-destructive")}),c.jsxs(oe,{type:"button",size:"sm",onClick:a,disabled:!n.trim(),children:[c.jsx(kr,{className:"h-4 w-4 mr-1"}),"Add"]})]}),s&&c.jsxs("div",{className:"flex items-center gap-2 text-sm text-destructive",children:[c.jsx(bd,{className:"h-4 w-4"}),s]}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Enter email addresses for external recipients. Separate multiple emails with commas."})]}),e.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"text-sm font-medium",children:["Added Emails (",e.length,")"]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(d=>c.jsxs(Fe,{variant:"secondary",className:"pl-3 pr-1 py-1 flex items-center gap-1",children:[c.jsx("span",{className:"text-xs",children:d}),c.jsx("button",{type:"button",onClick:()=>l(d),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:c.jsx(vt,{className:"h-3 w-3"})})]},d))})]})]})}function rIe({tenantUserIds:e,orgUserIds:t,onChangeTenantUsers:n,onChangeOrgUsers:r}){const[s,o]=N.useState(""),[i,a]=N.useState("");N.useEffect(()=>{const b=setTimeout(()=>{a(s)},300);return()=>clearTimeout(b)},[s]);const{users:l,isLoading:u,error:d}=WM({search:i,limit:50}),f=new Set([...e,...t]),h=l.map(b=>({id:b.id,name:b.name,email:b.email,type:b.type})),p=h.filter(b=>f.has(b.id)),m=b=>{const x=f.has(b.id);b.type==="tenant"?n(x?e.filter(y=>y!==b.id):[...e,b.id]):b.type==="organization"&&r(x?t.filter(y=>y!==b.id):[...t,b.id])},g=(b,x)=>{x==="tenant"?n(e.filter(y=>y!==b)):x==="organization"&&r(t.filter(y=>y!==b))};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"relative",children:[c.jsx(xa,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),c.jsx(Nn,{type:"text",placeholder:"Search users by name or email...",value:s,onChange:b=>o(b.target.value),className:"pl-9"})]}),f.size>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"text-sm font-medium",children:["Selected Users (",f.size,")"]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:p.map(b=>c.jsxs(Fe,{variant:"secondary",className:"pl-2 pr-1 py-1 flex items-center gap-1",children:[b.type==="organization"?c.jsx(gd,{className:"h-3 w-3"}):c.jsx(vc,{className:"h-3 w-3"}),c.jsx("span",{className:"text-xs",children:b.name}),c.jsx("button",{type:"button",onClick:()=>g(b.id,b.type),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:c.jsx(vt,{className:"h-3 w-3"})})]},b.id))})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm text-muted-foreground",children:s?"Search Results":"Available Users"}),u?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx(On,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):d?c.jsx("div",{className:"text-sm text-destructive py-4 text-center",children:"Failed to load users. Please try again."}):h.length===0?c.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center",children:s?"No users found":"No users available"}):c.jsx(Ds,{className:"h-[300px] rounded-md border p-2",children:c.jsx("div",{className:"space-y-1",children:h.map(b=>{const x=f.has(b.id);return c.jsxs("div",{className:J("flex items-center gap-3 rounded-md p-2 hover:bg-muted/50 cursor-pointer",x&&"bg-primary/10"),onClick:()=>m(b),children:[c.jsx(dn,{checked:x,onCheckedChange:()=>m(b),onClick:y=>y.stopPropagation()}),c.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[b.type==="organization"?c.jsx(gd,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}):c.jsx(vc,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-sm font-medium truncate",children:b.name}),c.jsx("div",{className:"text-xs text-muted-foreground truncate",children:b.email})]}),c.jsx(Fe,{variant:"outline",className:"text-xs",children:b.type==="organization"?"Org":"Tenant"})]})]},b.id)})})})]})]})}function sIe({groupIds:e,onChange:t}){const[n,r]=N.useState(""),{currentUser:s}=Ms(),{groups:o,isLoading:i,error:a}=qM({search:n,type:"all",limit:50}),l=o.filter(p=>(s==null?void 0:s.type)==="organization"?!0:(s==null?void 0:s.type)==="tenant"?p.type==="TENANT_GROUP"&&p.tenantId===s.tenantId:!1).map(p=>({id:p.id,name:p.name,description:p.description,type:p.type,memberCount:p.memberCount})),u=l.filter(p=>p.name.toLowerCase().includes(n.toLowerCase())||p.description&&p.description.toLowerCase().includes(n.toLowerCase())),d=l.filter(p=>e.includes(p.id)),f=p=>{e.includes(p)?t(e.filter(m=>m!==p)):t([...e,p])},h=p=>{t(e.filter(m=>m!==p))};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"relative",children:[c.jsx(xa,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),c.jsx(Nn,{type:"text",placeholder:"Search groups by name...",value:n,onChange:p=>r(p.target.value),className:"pl-9"})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",d.length,")"]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:d.map(p=>c.jsxs(Fe,{variant:"secondary",className:"pl-2 pr-1 py-1 flex items-center gap-1",children:[p.type==="ORG_GROUP"?c.jsx(gd,{className:"h-3 w-3"}):c.jsx(is,{className:"h-3 w-3"}),c.jsx("span",{className:"text-xs",children:p.name}),p.memberCount!==void 0&&c.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",p.memberCount,")"]}),c.jsx("button",{type:"button",onClick:()=>h(p.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:c.jsx(vt,{className:"h-3 w-3"})})]},p.id))})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm text-muted-foreground",children:n?"Search Results":"Available Groups"}),i?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx(On,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):a?c.jsx("div",{className:"text-sm text-destructive py-4 text-center",children:"Failed to load groups. Please try again."}):u.length===0?c.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center",children:n?"No groups found":"No groups available"}):c.jsx(Ds,{className:"h-[300px] rounded-md border p-2",children:c.jsx("div",{className:"space-y-1",children:u.map(p=>{const m=e.includes(p.id);return c.jsxs("div",{className:J("flex items-center gap-3 rounded-md p-2 hover:bg-muted/50 cursor-pointer",m&&"bg-primary/10"),onClick:()=>f(p.id),children:[c.jsx(dn,{checked:m,onCheckedChange:()=>f(p.id),onClick:g=>g.stopPropagation()}),c.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[p.type==="ORG_GROUP"?c.jsx(gd,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}):c.jsx(is,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-sm font-medium truncate",children:p.name}),p.description&&c.jsx("div",{className:"text-xs text-muted-foreground truncate",children:p.description})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[p.memberCount!==void 0&&c.jsxs(Fe,{variant:"outline",className:"text-xs",children:[p.memberCount," members"]}),c.jsx(Fe,{variant:"outline",className:"text-xs",children:p.type==="ORG_GROUP"?"Org":"Tenant"})]})]})]},p.id)})})})]})]})}const EG=N.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},s)=>c.jsx(wa,{children:c.jsx(pS,{ref:s,align:t,sideOffset:n,className:J("w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));EG.displayName=pS.displayName;function oIe({value:e,onChange:t,className:n}){const[r,s]=N.useState(!1),[o,i]=N.useState("emails"),a=e.emails.length+e.tenantUserIds.length+e.orgUserIds.length+e.groupIds.length,l=f=>{t({...e,...f})},u=(f,h)=>{switch(h){case"email":l({emails:e.emails.filter(p=>p!==f)});break;case"tenantUser":l({tenantUserIds:e.tenantUserIds.filter(p=>p!==f)});break;case"orgUser":l({orgUserIds:e.orgUserIds.filter(p=>p!==f)});break;case"group":l({groupIds:e.groupIds.filter(p=>p!==f)});break}},d=()=>{const f=[];e.emails.length>0&&f.push(`${e.emails.length} email${e.emails.length!==1?"s":""}`);const h=e.tenantUserIds.length+e.orgUserIds.length;return h>0&&f.push(`${h} user${h!==1?"s":""}`),e.groupIds.length>0&&f.push(`${e.groupIds.length} group${e.groupIds.length!==1?"s":""}`),f.join(", ")};return c.jsxs("div",{className:J("space-y-2",n),children:[a>0&&c.jsx("div",{className:"space-y-2",children:c.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.emails.map(f=>c.jsxs(Fe,{variant:"secondary",className:"gap-1 pr-1",children:[c.jsx(dv,{className:"h-3 w-3"}),c.jsx("span",{className:"max-w-[150px] truncate text-xs",children:f}),c.jsx("button",{onClick:h=>{h.stopPropagation(),u(f,"email")},className:"ml-1 rounded-sm hover:bg-secondary-foreground/20",children:c.jsx(vt,{className:"h-3 w-3"})})]},f)),e.tenantUserIds.length+e.orgUserIds.length>0&&c.jsxs(Fe,{variant:"secondary",className:"gap-1",children:[c.jsx(is,{className:"h-3 w-3"}),e.tenantUserIds.length+e.orgUserIds.length," users"]}),e.groupIds.length>0&&c.jsxs(Fe,{variant:"secondary",className:"gap-1",children:[c.jsx(eP,{className:"h-3 w-3"}),e.groupIds.length," groups"]})]})}),c.jsxs(Ns,{open:r,onOpenChange:s,modal:!0,children:[c.jsx(js,{asChild:!0,children:c.jsxs(oe,{variant:"outline",size:"sm",className:"w-full justify-start",children:[c.jsx(H8,{className:"mr-2 h-4 w-4"}),a>0?c.jsxs("span",{children:["Add more recipients (",d(),")"]}):"Add recipients"]})}),c.jsx(EG,{className:"z-[51] w-[500px] p-0",align:"start",side:"bottom",sideOffset:4,children:c.jsxs("div",{className:"p-4",children:[c.jsxs("div",{className:"mb-4",children:[c.jsx("h4",{className:"text-sm font-medium",children:"Select Recipients"}),c.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Choose who should receive the scheduled reports"})]}),c.jsxs(cs,{value:o,onValueChange:f=>i(f),children:[c.jsxs(Wr,{className:"grid w-full grid-cols-3",children:[c.jsxs(Ht,{value:"emails",className:"flex items-center gap-2 text-xs",children:[c.jsx(dv,{className:"h-3 w-3"}),c.jsx("span",{children:"Emails"}),e.emails.length>0&&c.jsx(Fe,{variant:"secondary",className:"ml-1 h-4 px-1 text-xs",children:e.emails.length})]}),c.jsxs(Ht,{value:"users",className:"flex items-center gap-2 text-xs",children:[c.jsx(is,{className:"h-3 w-3"}),c.jsx("span",{children:"Users"}),e.tenantUserIds.length+e.orgUserIds.length>0&&c.jsx(Fe,{variant:"secondary",className:"ml-1 h-4 px-1 text-xs",children:e.tenantUserIds.length+e.orgUserIds.length})]}),c.jsxs(Ht,{value:"groups",className:"flex items-center gap-2 text-xs",children:[c.jsx(eP,{className:"h-3 w-3"}),c.jsx("span",{children:"Groups"}),e.groupIds.length>0&&c.jsx(Fe,{variant:"secondary",className:"ml-1 h-4 px-1 text-xs",children:e.groupIds.length})]})]}),c.jsxs("div",{className:"mt-4 max-h-[300px] overflow-y-auto",children:[c.jsx(Gn,{value:"emails",className:"mt-0",children:c.jsx(nIe,{emails:e.emails,onChange:f=>l({emails:f})})}),c.jsx(Gn,{value:"users",className:"mt-0",children:c.jsx(rIe,{tenantUserIds:e.tenantUserIds,orgUserIds:e.orgUserIds,onChangeTenantUsers:f=>l({tenantUserIds:f}),onChangeOrgUsers:f=>l({orgUserIds:f})})}),c.jsx(Gn,{value:"groups",className:"mt-0",children:c.jsx(sIe,{groupIds:e.groupIds,onChange:f=>l({groupIds:f})})})]})]}),c.jsx("div",{className:"mt-4 border-t pt-4",children:c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("p",{className:"text-xs text-muted-foreground",children:a>0?`${a} recipient${a!==1?"s":""} selected`:"No recipients selected"}),c.jsx(oe,{size:"sm",onClick:()=>s(!1),className:"h-7",children:"Done"})]})})]})})]})]})}var _G={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},S4=N.createContext&&N.createContext(_G),iIe=["attr","size","title"];function aIe(e,t){if(e==null)return{};var n=lIe(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 lIe(e,t){if(e==null)return{};var n={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(t.indexOf(r)>=0)continue;n[r]=e[r]}return n}function lw(){return lw=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},lw.apply(this,arguments)}function C4(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 cw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?C4(Object(n),!0).forEach(function(r){cIe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):C4(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function cIe(e,t,n){return t=uIe(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function uIe(e){var t=dIe(e,"string");return typeof t=="symbol"?t:t+""}function dIe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function DG(e){return e&&e.map((t,n)=>N.createElement(t.tag,cw({key:n},t.attr),DG(t.child)))}function nu(e){return t=>N.createElement(fIe,lw({attr:cw({},e.attr)},t),DG(e.child))}function fIe(e){var t=n=>{var{attr:r,size:s,title:o}=e,i=aIe(e,iIe),a=s||n.size||"1em",l;return n.className&&(l=n.className),e.className&&(l=(l?l+" ":"")+e.className),N.createElement("svg",lw({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,i,{className:l,style:cw(cw({color:e.color||n.color},n.style),e.style),height:a,width:a,xmlns:"http://www.w3.org/2000/svg"}),o&&N.createElement("title",null,o),e.children)};return S4!==void 0?N.createElement(S4.Consumer,null,n=>t(n)):t(_G)}function MG(e){return nu({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(e)}function hIe(e){return nu({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(e)}function TG(e){return nu({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(e)}function RG(e){return nu({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(e)}function IG(e){return nu({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4 4m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z"},child:[]},{tag:"path",attr:{d:"M12 4v16"},child:[]},{tag:"path",attr:{d:"M4 15h8"},child:[]},{tag:"path",attr:{d:"M12 12h8"},child:[]},{tag:"path",attr:{d:"M16 12v8"},child:[]},{tag:"path",attr:{d:"M16 16h4"},child:[]}]})(e)}function AG(e){return nu({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(e)}function PG(e){return nu({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(e)}function OG(e){return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 48 48",...e,children:c.jsxs("g",{stroke:"currentColor",strokeWidth:"3.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none",children:[c.jsx("line",{x1:"12",y1:"6",x2:"12",y2:"42"}),c.jsx("line",{x1:"12",y1:"12",x2:"32",y2:"12"}),c.jsx("line",{x1:"12",y1:"24",x2:"32",y2:"24"}),c.jsx("line",{x1:"12",y1:"36",x2:"32",y2:"36"}),c.jsx("line",{x1:"42",y1:"9",x2:"42",y2:"15"}),c.jsx("line",{x1:"44",y1:"21",x2:"44",y2:"27"}),c.jsx("line",{x1:"42",y1:"33",x2:"42",y2:"39"})]})})}const mS=[{id:"table",icon:ky,label:"Table"},{id:"pivotTable",icon:ky,label:"Pivot Table"},{id:"aggregateTable",icon:ky,label:"Aggregate Table"},{id:"bar",icon:h8,label:"Bar Chart"},{id:"line",icon:m8,label:"Line Chart"},{id:"area",icon:f8,label:"Area Chart"},{id:"stackedBar",icon:p8,label:"Stacked Bar Chart"},{id:"combo",icon:b8,label:"Combo Chart"},{id:"stackedLine",icon:AG,label:"Stacked Line Chart"},{id:"scatter",icon:v8,label:"Scatter Chart"},{id:"bubble",icon:TG,label:"Bubble Chart"},{id:"pie",icon:y8,label:"Pie Chart"},{id:"doughnut",icon:k8,label:"Doughnut Chart"},{id:"funnel",icon:RG,label:"Funnel Chart"},{id:"radar",icon:$8,label:"Radar Chart"},{id:"polarArea",icon:MG,label:"Polar Area Chart"},{id:"tornado",icon:V8,label:"Tornado Chart"},{id:"range",icon:x8,label:"Range Chart"},{id:"bullet",icon:OG,label:"Bullet Chart"},{id:"treemap",icon:IG,label:"Treemap"},{id:"heatmap",icon:D8,label:"Heatmap"},{id:"kpi",icon:PG,label:"KPI"},{id:"text",icon:d8,label:"Text"},{id:"map",icon:O8,label:"Map"}],pIe=e=>{const t=e.toLowerCase();for(const n of mS)if(n.id==="doughnut"){if(t.includes("doughnut")||t.includes("donut")){const r=n.icon;return N.createElement(r,{className:"h-4 w-4"})}}else if(t.includes(n.id.toLowerCase())){const r=n.icon;return N.createElement(r,{className:"h-4 w-4"})}return null},mIe=(e,t="h-4 w-4")=>{const n=mS.find(r=>r.id===e);if(n){const r=n.icon;return N.createElement(r,{className:t})}return N.createElement(b8,{className:t})};function gIe({open:e,onOpenChange:t,dashboardId:n,onSelect:r,existingAttachments:s}){const[o,i]=N.useState(new Map),a=ee(g=>g.dashboard),l=N.useMemo(()=>(a==null?void 0:a.sheets)||[],[a]),u=ee(g=>g.selectedSheetId),d=l.find(g=>g.id===u),f=N.useMemo(()=>{var b;const g=[];if(g.push({id:"dashboard-full",title:`${(a==null?void 0:a.title)||"Dashboard"} (All Sheets)`,type:"dashboard",icon:c.jsx(Vj,{className:"h-4 w-4"}),supportedFormats:["pdf"]}),l.length>1&&d&&g.push({id:`dashboard-${d.id}`,title:`${(a==null?void 0:a.title)||"Dashboard"} (${d.title})`,type:"dashboard",icon:c.jsx(Ni,{className:"h-4 w-4"}),supportedFormats:["pdf"]}),d){const x=[];(b=d.frames)==null||b.forEach(y=>{var v;(v=y.cards)==null||v.forEach(w=>{if(w.type==="text")return;const S=mIe(w.type),C=_T(w.type);x.push({id:w.id,title:w.title||`${w.type} Chart`,type:"visual",visualId:w.id,cardType:w.type,icon:S,supportedFormats:C})})}),g.push(...x)}return g},[a,l,d]);N.useEffect(()=>{if(!e){i(new Map);return}if(s.length>0&&f.length>0){const g=new Map;s.forEach(b=>{const x=f.find(y=>{var v,w;if(b.type==="visual"&&b.visualId)return y.visualId===b.visualId;if(b.type==="dashboard"){if(((v=b.settings)==null?void 0:v.sheetSelection)==="all")return y.id==="dashboard-full";if((w=b.settings)!=null&&w.currentSheetId)return y.id===`dashboard-${b.settings.currentSheetId}`}return!1});x&&g.set(x.id,{item:x,format:b.format||"pdf"})}),i(g)}},[e,s,f]);const h=g=>{const b=new Map(o);if(b.has(g.id))b.delete(g.id);else{let x="pdf";g.type==="dashboard"?x="pdf":g.cardType?x=DT(g.cardType):x=g.supportedFormats.includes("csv")?"csv":"pdf",b.set(g.id,{item:g,format:x})}i(b)},p=(g,b)=>{const x=o.get(g);if(x){const y=new Map(o);y.set(g,{...x,format:b}),i(y)}},m=()=>{const g=[];o.forEach(({item:b,format:x})=>{const y={type:b.type,visualId:b.visualId,cardType:b.cardType,title:b.title,format:x,supportedFormats:b.supportedFormats,settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0}};b.type==="dashboard"&&(b.id==="dashboard-full"?y.settings.sheetSelection="all":d&&(y.settings.sheetSelection="current",y.settings.currentSheetId=d.id,y.settings.currentSheetName=d.title)),x==="csv"&&(y.settings.delimiter=",",y.settings.includeHeaders=!0,y.settings.useFormattedValues=!0),g.push(y)}),r(g),t(!1)};return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsxs(Vr,{className:"max-w-2xl",children:[c.jsx(Hr,{children:c.jsx(Ur,{children:"Select Attachment"})}),c.jsx("div",{className:"space-y-4",children:c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(ce,{children:"Select items to attach:"}),o.size>0&&c.jsxs("span",{className:"text-sm text-muted-foreground",children:[o.size," selected"]})]}),c.jsx("div",{className:"max-h-[400px] space-y-2 overflow-y-auto",children:f.map(g=>{var y;const b=o.has(g.id),x=((y=o.get(g.id))==null?void 0:y.format)||"pdf";return c.jsxs("div",{className:J("flex items-center gap-3 rounded-lg border p-3 transition-colors",b?"border-primary bg-primary/5":"border-border hover:bg-muted/50"),children:[c.jsx(dn,{checked:b,onCheckedChange:()=>h(g)}),c.jsx("div",{className:"flex-shrink-0",children:g.icon}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:g.title}),c.jsx("div",{className:"text-xs text-muted-foreground",children:g.type==="dashboard"?"Dashboard":"Visual"})]}),b&&c.jsxs(rt,{value:x,onValueChange:v=>p(g.id,v),children:[c.jsx(Je,{className:"h-7 w-20 text-xs",children:c.jsx(lt,{})}),c.jsxs(et,{children:[g.supportedFormats.includes("pdf")&&c.jsx(pe,{value:"pdf",children:"PDF"}),g.supportedFormats.includes("csv")&&c.jsx(pe,{value:"csv",children:"CSV"})]})]})]},g.id)})})]})}),c.jsxs(Ts,{children:[c.jsx(oe,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),c.jsxs(oe,{onClick:m,disabled:o.size===0,children:[c.jsx(Rr,{className:"mr-2 h-4 w-4"}),"Add"," ",o.size>1?`${o.size} Attachments`:"Attachment"]})]})]})})}function bIe({open:e,onOpenChange:t,attachment:n,onSave:r}){const[s,o]=N.useState(n.settings);N.useEffect(()=>{o(n.settings)},[n]);const i=()=>{r({...n,settings:s}),t(!1)};return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsxs(Vr,{className:"max-w-md",children:[c.jsx(Hr,{children:c.jsx(Ur,{children:"Export Settings"})}),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsx(ce,{className:"text-sm font-medium",children:n.title}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[n.type==="dashboard"?"Dashboard":"Visual"," • ",n.format.toUpperCase()]})]}),c.jsx(yo,{}),n.format==="pdf"&&c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{htmlFor:"page-size",children:"Page Size"}),c.jsxs(rt,{value:s.pageSize||"letter",onValueChange:a=>o({...s,pageSize:a}),children:[c.jsx(Je,{id:"page-size",children:c.jsx(lt,{})}),c.jsxs(et,{children:[c.jsx(pe,{value:"letter",children:'Letter (8.5" × 11")'}),c.jsx(pe,{value:"a4",children:"A4 (210mm × 297mm)"}),c.jsx(pe,{value:"legal",children:'Legal (8.5" × 14")'}),c.jsx(pe,{value:"a3",children:"A3 (297mm × 420mm)"}),c.jsx(pe,{value:"tabloid",children:'Tabloid (11" × 17")'})]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{htmlFor:"orientation",children:"Orientation"}),c.jsxs(rt,{value:s.orientation||"portrait",onValueChange:a=>o({...s,orientation:a}),children:[c.jsx(Je,{id:"orientation",children:c.jsx(lt,{})}),c.jsxs(et,{children:[c.jsx(pe,{value:"portrait",children:"Portrait"}),c.jsx(pe,{value:"landscape",children:"Landscape"})]})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(dn,{id:"include-filters",checked:s.includeFilters!==!1,onCheckedChange:a=>o({...s,includeFilters:a})}),c.jsx(ce,{htmlFor:"include-filters",className:"text-sm font-normal cursor-pointer",children:"Include applied filters"})]}),c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(dn,{id:"include-timestamp",checked:s.includeTimestamp!==!1,onCheckedChange:a=>o({...s,includeTimestamp:a})}),c.jsx(ce,{htmlFor:"include-timestamp",className:"text-sm font-normal cursor-pointer",children:"Include timestamp"})]})]})]}),n.format==="csv"&&c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{htmlFor:"delimiter",children:"Delimiter"}),c.jsxs(rt,{value:s.delimiter||",",onValueChange:a=>o({...s,delimiter:a}),children:[c.jsx(Je,{id:"delimiter",children:c.jsx(lt,{})}),c.jsxs(et,{children:[c.jsx(pe,{value:",",children:"Comma (,)"}),c.jsx(pe,{value:";",children:"Semicolon (;)"}),c.jsx(pe,{value:"\\t",children:"Tab"})]})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(dn,{id:"include-headers",checked:s.includeHeaders!==!1,onCheckedChange:a=>o({...s,includeHeaders:a})}),c.jsx(ce,{htmlFor:"include-headers",className:"text-sm font-normal cursor-pointer",children:"Include column headers"})]}),c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(dn,{id:"use-formatted",checked:s.useFormattedValues!==!1,onCheckedChange:a=>o({...s,useFormattedValues:a})}),c.jsx(ce,{htmlFor:"use-formatted",className:"text-sm font-normal cursor-pointer",children:"Use formatted values"})]})]}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Formatted values preserve number formatting, dates, and currency symbols. Raw values export the underlying data."})]})]}),c.jsxs(Ts,{children:[c.jsx(oe,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),c.jsx(oe,{onClick:i,children:"Save Settings"})]})]})})}function xIe({attachments:e,onRemove:t,onUpdate:n}){const[r,s]=N.useState({open:!1,index:null}),o=(d,f)=>{const h=e[d],p={...h,format:f,settings:{...h.settings,...f==="csv"?{delimiter:",",includeHeaders:!0,useFormattedValues:!0}:{}}};n(d,p)},i=d=>d==="csv"?c.jsx(E8,{className:"h-4 w-4"}):c.jsx(Ni,{className:"h-4 w-4"}),a=d=>d==="csv"?"text-green-600":"text-red-600",l=d=>{s({open:!0,index:d})},u=d=>{r.index!==null&&n(r.index,d),s({open:!1,index:null})};return c.jsxs("div",{className:"space-y-2",children:[e.map((d,f)=>{var h,p,m;return c.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg bg-muted/30",children:[c.jsx("div",{className:J("flex-shrink-0",a(d.format)),children:i(d.format)}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"font-medium text-sm truncate",children:d.title}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:[d.type==="dashboard"?"Dashboard":"Visual",((h=d.settings)==null?void 0:h.sheetSelection)==="all"&&" • All sheets",((p=d.settings)==null?void 0:p.sheetSelection)==="current"&&((m=d.settings)==null?void 0:m.currentSheetName)&&` • ${d.settings.currentSheetName}`]})]}),d.supportedFormats&&d.supportedFormats.length>1?c.jsxs(rt,{value:d.format,onValueChange:g=>o(f,g),children:[c.jsx(Je,{className:"w-24 h-8",children:c.jsx(lt,{})}),c.jsxs(et,{children:[d.supportedFormats.includes("pdf")&&c.jsx(pe,{value:"pdf",children:"PDF"}),d.supportedFormats.includes("csv")&&c.jsx(pe,{value:"csv",children:"CSV"})]})]}):c.jsx(Fe,{variant:"secondary",className:"uppercase",children:d.format}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>l(f),children:c.jsx(sp,{className:"h-4 w-4"})}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive",onClick:()=>t(f),children:c.jsx(vt,{className:"h-4 w-4"})})]},f)}),r.open&&r.index!==null&&c.jsx(bIe,{open:r.open,onOpenChange:d=>s({...r,open:d}),attachment:e[r.index],onSave:u})]})}const lR=[{value:0,label:"Sun",shortLabel:"S"},{value:1,label:"Mon",shortLabel:"M"},{value:2,label:"Tue",shortLabel:"T"},{value:3,label:"Wed",shortLabel:"W"},{value:4,label:"Thu",shortLabel:"T"},{value:5,label:"Fri",shortLabel:"F"},{value:6,label:"Sat",shortLabel:"S"}],wE=[{value:"America/New_York",label:"Eastern Time (ET)",offset:"UTC-5"},{value:"America/Chicago",label:"Central Time (CT)",offset:"UTC-6"},{value:"America/Denver",label:"Mountain Time (MT)",offset:"UTC-7"},{value:"America/Los_Angeles",label:"Pacific Time (PT)",offset:"UTC-8"},{value:"Europe/London",label:"London (GMT)",offset:"UTC+0"},{value:"Europe/Paris",label:"Paris (CET)",offset:"UTC+1"},{value:"Asia/Tokyo",label:"Tokyo (JST)",offset:"UTC+9"},{value:"Asia/Shanghai",label:"Shanghai (CST)",offset:"UTC+8"},{value:"Australia/Sydney",label:"Sydney (AEDT)",offset:"UTC+11"},{value:"UTC",label:"UTC",offset:"UTC+0"}],ny=[...wE,{value:"America/Phoenix",label:"Phoenix (MST)",offset:"UTC-7"},{value:"America/Toronto",label:"Toronto (ET)",offset:"UTC-5"},{value:"America/Vancouver",label:"Vancouver (PT)",offset:"UTC-8"},{value:"America/Mexico_City",label:"Mexico City (CST)",offset:"UTC-6"},{value:"America/Sao_Paulo",label:"São Paulo (BRT)",offset:"UTC-3"},{value:"Europe/Berlin",label:"Berlin (CET)",offset:"UTC+1"},{value:"Europe/Moscow",label:"Moscow (MSK)",offset:"UTC+3"},{value:"Asia/Dubai",label:"Dubai (GST)",offset:"UTC+4"},{value:"Asia/Mumbai",label:"Mumbai (IST)",offset:"UTC+5:30"},{value:"Asia/Singapore",label:"Singapore (SGT)",offset:"UTC+8"},{value:"Asia/Hong_Kong",label:"Hong Kong (HKT)",offset:"UTC+8"},{value:"Australia/Melbourne",label:"Melbourne (AEDT)",offset:"UTC+11"},{value:"Pacific/Auckland",label:"Auckland (NZDT)",offset:"UTC+13"}];function yIe({value:e,onChange:t,className:n}){var i;const r=N.useMemo(()=>Intl.DateTimeFormat().resolvedOptions().timeZone,[]),s=N.useMemo(()=>{var l;const a=ny.find(u=>u.value===e);return a?a.label:e===r?`${(l=e.split("/").pop())==null?void 0:l.replace(/_/g," ")}`:e},[e,r]),o=N.useMemo(()=>{var l;const a=ny.find(u=>u.value===e);return a?`${a.label} (${a.offset})`:e===r?`${(l=e.split("/").pop())==null?void 0:l.replace(/_/g," ")} (Browser)`:e},[e,r]);return c.jsx("div",{className:J("relative",n),children:c.jsxs(rt,{value:e||r,onValueChange:t,children:[c.jsx(Je,{className:"w-full",title:o,children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(s1,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"truncate",children:s})]})}),c.jsxs(et,{className:"w-full max-h-[300px]",children:[r&&!ny.find(a=>a.value===r)&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"px-2 py-1.5 text-xs font-medium text-muted-foreground",children:"Your timezone"}),c.jsx(pe,{value:r,children:c.jsxs("div",{className:"flex items-center justify-between w-full",children:[c.jsx("span",{children:(i=r.split("/").pop())==null?void 0:i.replace(/_/g," ")}),c.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:"(Browser)"})]})}),c.jsx("div",{className:"my-1 h-px bg-border"})]}),c.jsx("div",{className:"px-2 py-1.5 text-xs font-medium text-muted-foreground",children:"Common timezones"}),wE.map(a=>c.jsx(pe,{value:a.value,children:c.jsxs("div",{className:"flex items-center justify-between w-full",children:[c.jsx("span",{children:a.label}),c.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:a.offset})]})},a.value)),c.jsx("div",{className:"my-1 h-px bg-border"}),c.jsx("div",{className:"px-2 py-1.5 text-xs font-medium text-muted-foreground",children:"Other timezones"}),ny.filter(a=>!wE.find(l=>l.value===a.value)).map(a=>c.jsx(pe,{value:a.value,children:c.jsxs("div",{className:"flex items-center justify-between w-full",children:[c.jsx("span",{children:a.label}),c.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:a.offset})]})},a.value))]})]})})}function vIe({value:e,onChange:t,className:n}){const r=N.useMemo(()=>{const o=[];for(let i=0;i<24;i++)for(let a=0;a<60;a+=30){const l=`${i.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`;let u;i===0?u=12:i>12?u=i-12:u=i;const d=i<12?"AM":"PM",f=`${u}:${a.toString().padStart(2,"0")} ${d}`;o.push({value:l,label:f})}return o},[]),s=N.useMemo(()=>{const o=r.find(i=>i.value===e);return(o==null?void 0:o.label)||e},[e,r]);return c.jsxs(rt,{value:e,onValueChange:t,children:[c.jsx(Je,{className:J("w-full",n),children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(dl,{className:"h-4 w-4 text-muted-foreground"}),c.jsx(lt,{placeholder:"Select time",children:s})]})}),c.jsx(et,{className:"max-h-[300px]",children:r.map(o=>c.jsx(pe,{className:"hover:bg-muted",value:o.value,children:o.label},o.value))})]})}function wIe({value:e=[],onChange:t,disabled:n=!1,className:r}){const s=h=>{if(n)return;const p=e.includes(h)?e.filter(m=>m!==h):[...e,h];t(p.sort())},o=()=>{n||t([1,2,3,4,5])},i=()=>{n||t([0,6])},a=()=>{n||t([0,1,2,3,4,5,6])},l=()=>{n||t([])},u=[1,2,3,4,5].every(h=>e.includes(h))&&e.length===5,d=e.includes(0)&&e.includes(6)&&e.length===2,f=e.length===7;return c.jsxs("div",{className:J("space-y-3",r),children:[c.jsxs("div",{className:"flex flex-wrap gap-2",children:[c.jsx(oe,{type:"button",variant:u?"default":"outline",size:"sm",onClick:o,disabled:n,className:"h-7 text-xs",children:"Weekdays"}),c.jsx(oe,{type:"button",variant:d?"default":"outline",size:"sm",onClick:i,disabled:n,className:"h-7 text-xs",children:"Weekends"}),c.jsx(oe,{type:"button",variant:f?"default":"outline",size:"sm",onClick:a,disabled:n,className:"h-7 text-xs",children:"Every day"}),e.length>0&&c.jsx(oe,{type:"button",variant:"ghost",size:"sm",onClick:l,disabled:n,className:"h-7 text-xs",children:"Clear"})]}),c.jsx("div",{className:"grid grid-cols-7 gap-2",children:lR.map(h=>c.jsxs("div",{className:J("flex flex-col items-center space-y-2",n&&"opacity-50"),children:[c.jsx(ce,{htmlFor:`weekday-${h.value}`,className:J("text-xs font-medium cursor-pointer select-none",n&&"cursor-not-allowed"),children:h.shortLabel}),c.jsx(dn,{id:`weekday-${h.value}`,checked:e.includes(h.value),onCheckedChange:()=>s(h.value),disabled:n,className:"h-5 w-5"}),c.jsx("span",{className:"text-[10px] text-muted-foreground",children:h.label.slice(0,3)})]},h.value))}),e.length>0&&c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Selected: ",SIe(e)]})]})}function SIe(e){if(e.length===0)return"None";if(e.length===7)return"Every day";const t=new Set(e),n=[1,2,3,4,5].every(a=>t.has(a))&&e.length===5,r=t.has(0)&&t.has(6)&&e.length===2;if(n)return"Monday through Friday";if(r)return"Saturday and Sunday";const o=[...e].sort().map(a=>lR[a].label);if(o.length===1)return o[0];if(o.length===2)return`${o[0]} and ${o[1]}`;const i=o.pop();return`${o.join(", ")}, and ${i}`}function CIe(e,t,n="long"){return new Intl.DateTimeFormat("en-US",{hour:"numeric",timeZone:e,timeZoneName:n}).format(t).split(/\s/g).slice(2).join(" ")}const d2={},Bm={};function $u(e,t){try{const r=(d2[e]||(d2[e]=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"}).format))(t).split("GMT")[1];return r in Bm?Bm[r]:N4(r,r.split(":"))}catch{if(e in Bm)return Bm[e];const n=e==null?void 0:e.match(NIe);return n?N4(e,n.slice(1)):NaN}}const NIe=/([+-]\d\d):?(\d\d)?/;function N4(e,t){const n=+(t[0]||0),r=+(t[1]||0),s=+(t[2]||0)/60;return Bm[e]=n*60+r>0?n*60+r+s:n*60-r-s}class ra extends Date{constructor(...t){super(),t.length>1&&typeof t[t.length-1]=="string"&&(this.timeZone=t.pop()),this.internal=new Date,isNaN($u(this.timeZone,this))?this.setTime(NaN):t.length?typeof t[0]=="number"&&(t.length===1||t.length===2&&typeof t[1]!="number")?this.setTime(t[0]):typeof t[0]=="string"?this.setTime(+new Date(t[0])):t[0]instanceof Date?this.setTime(+t[0]):(this.setTime(+new Date(...t)),FG(this),SE(this)):this.setTime(Date.now())}static tz(t,...n){return n.length?new ra(...n,t):new ra(Date.now(),t)}withTimeZone(t){return new ra(+this,t)}getTimezoneOffset(){const t=-$u(this.timeZone,this);return t>0?Math.floor(t):Math.ceil(t)}setTime(t){return Date.prototype.setTime.apply(this,arguments),SE(this),+this}[Symbol.for("constructDateFrom")](t){return new ra(+new Date(t),this.timeZone)}}const j4=/^(get|set)(?!UTC)/;Object.getOwnPropertyNames(Date.prototype).forEach(e=>{if(!j4.test(e))return;const t=e.replace(j4,"$1UTC");ra.prototype[t]&&(e.startsWith("get")?ra.prototype[e]=function(){return this.internal[t]()}:(ra.prototype[e]=function(){return Date.prototype[t].apply(this.internal,arguments),jIe(this),+this},ra.prototype[t]=function(){return Date.prototype[t].apply(this,arguments),SE(this),+this}))});function SE(e){e.internal.setTime(+e),e.internal.setUTCSeconds(e.internal.getUTCSeconds()-Math.round(-$u(e.timeZone,e)*60))}function jIe(e){Date.prototype.setFullYear.call(e,e.internal.getUTCFullYear(),e.internal.getUTCMonth(),e.internal.getUTCDate()),Date.prototype.setHours.call(e,e.internal.getUTCHours(),e.internal.getUTCMinutes(),e.internal.getUTCSeconds(),e.internal.getUTCMilliseconds()),FG(e)}function FG(e){const t=$u(e.timeZone,e),n=t>0?Math.floor(t):Math.ceil(t),r=new Date(+e);r.setUTCHours(r.getUTCHours()-1);const s=-new Date(+e).getTimezoneOffset(),o=-new Date(+r).getTimezoneOffset(),i=s-o,a=Date.prototype.getHours.apply(e)!==e.internal.getUTCHours();i&&a&&e.internal.setUTCMinutes(e.internal.getUTCMinutes()+i);const l=s-n;l&&Date.prototype.setUTCMinutes.call(e,Date.prototype.getUTCMinutes.call(e)+l);const u=new Date(+e);u.setUTCSeconds(0);const d=s>0?u.getSeconds():(u.getSeconds()-60)%60,f=Math.round(-($u(e.timeZone,e)*60))%60;(f||d)&&(e.internal.setUTCSeconds(e.internal.getUTCSeconds()+f),Date.prototype.setUTCSeconds.call(e,Date.prototype.getUTCSeconds.call(e)+f+d));const h=$u(e.timeZone,e),p=h>0?Math.floor(h):Math.ceil(h),g=-new Date(+e).getTimezoneOffset()-p,b=p!==n,x=g-l;if(b&&x){Date.prototype.setUTCMinutes.call(e,Date.prototype.getUTCMinutes.call(e)+x);const y=$u(e.timeZone,e),v=y>0?Math.floor(y):Math.ceil(y),w=p-v;w&&(e.internal.setUTCMinutes(e.internal.getUTCMinutes()+w),Date.prototype.setUTCMinutes.call(e,Date.prototype.getUTCMinutes.call(e)+w))}}class Qr extends ra{static tz(t,...n){return n.length?new Qr(...n,t):new Qr(Date.now(),t)}toISOString(){const[t,n,r]=this.tzComponents(),s=`${t}${n}:${r}`;return this.internal.toISOString().slice(0,-1)+s}toString(){return`${this.toDateString()} ${this.toTimeString()}`}toDateString(){const[t,n,r,s]=this.internal.toUTCString().split(" ");return`${t==null?void 0:t.slice(0,-1)} ${r} ${n} ${s}`}toTimeString(){const t=this.internal.toUTCString().split(" ")[4],[n,r,s]=this.tzComponents();return`${t} GMT${n}${r}${s} (${CIe(this.timeZone,this)})`}toLocaleString(t,n){return Date.prototype.toLocaleString.call(this,t,{...n,timeZone:(n==null?void 0:n.timeZone)||this.timeZone})}toLocaleDateString(t,n){return Date.prototype.toLocaleDateString.call(this,t,{...n,timeZone:(n==null?void 0:n.timeZone)||this.timeZone})}toLocaleTimeString(t,n){return Date.prototype.toLocaleTimeString.call(this,t,{...n,timeZone:(n==null?void 0:n.timeZone)||this.timeZone})}tzComponents(){const t=this.getTimezoneOffset(),n=t>0?"-":"+",r=String(Math.floor(Math.abs(t)/60)).padStart(2,"0"),s=String(Math.abs(t)%60).padStart(2,"0");return[n,r,s]}withTimeZone(t){return new Qr(+this,t)}[Symbol.for("constructDateFrom")](t){return new Qr(+new Date(t),this.timeZone)}}const $G=6048e5,kIe=864e5,k4=Symbol.for("constructDateFrom");function Er(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&k4 in e?e[k4](t):e instanceof Date?new e.constructor(t):new Date(t)}function vn(e,t){return Er(t||e,e)}function LG(e,t,n){const r=vn(e,n==null?void 0:n.in);return isNaN(t)?Er(e,NaN):(t&&r.setDate(r.getDate()+t),r)}function zG(e,t,n){const r=vn(e,n==null?void 0:n.in);if(isNaN(t))return Er(e,NaN);if(!t)return r;const s=r.getDate(),o=Er(e,r.getTime());o.setMonth(r.getMonth()+t+1,0);const i=o.getDate();return s>=i?o:(r.setFullYear(o.getFullYear(),o.getMonth(),s),r)}let EIe={};function dx(){return EIe}function Zh(e,t){var a,l,u,d;const n=dx(),r=(t==null?void 0:t.weekStartsOn)??((l=(a=t==null?void 0:t.locale)==null?void 0:a.options)==null?void 0:l.weekStartsOn)??n.weekStartsOn??((d=(u=n.locale)==null?void 0:u.options)==null?void 0:d.weekStartsOn)??0,s=vn(e,t==null?void 0:t.in),o=s.getDay(),i=(o<r?7:0)+o-r;return s.setDate(s.getDate()-i),s.setHours(0,0,0,0),s}function Jg(e,t){return Zh(e,{...t,weekStartsOn:1})}function BG(e,t){const n=vn(e,t==null?void 0:t.in),r=n.getFullYear(),s=Er(n,0);s.setFullYear(r+1,0,4),s.setHours(0,0,0,0);const o=Jg(s),i=Er(n,0);i.setFullYear(r,0,4),i.setHours(0,0,0,0);const a=Jg(i);return n.getTime()>=o.getTime()?r+1:n.getTime()>=a.getTime()?r:r-1}function E4(e){const t=vn(e),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),+e-+n}function Wp(e,...t){const n=Er.bind(null,t.find(r=>typeof r=="object"));return t.map(n)}function eb(e,t){const n=vn(e,t==null?void 0:t.in);return n.setHours(0,0,0,0),n}function VG(e,t,n){const[r,s]=Wp(n==null?void 0:n.in,e,t),o=eb(r),i=eb(s),a=+o-E4(o),l=+i-E4(i);return Math.round((a-l)/kIe)}function _Ie(e,t){const n=BG(e,t),r=Er(e,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),Jg(r)}function DIe(e,t,n){return LG(e,t*7,n)}function MIe(e,t,n){return zG(e,t*12,n)}function TIe(e,t){let n,r=t==null?void 0:t.in;return e.forEach(s=>{!r&&typeof s=="object"&&(r=Er.bind(null,s));const o=vn(s,r);(!n||n<o||isNaN(+o))&&(n=o)}),Er(r,n||NaN)}function RIe(e,t){let n,r=t==null?void 0:t.in;return e.forEach(s=>{!r&&typeof s=="object"&&(r=Er.bind(null,s));const o=vn(s,r);(!n||n>o||isNaN(+o))&&(n=o)}),Er(r,n||NaN)}function IIe(e,t,n){const[r,s]=Wp(n==null?void 0:n.in,e,t);return+eb(r)==+eb(s)}function HG(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function AIe(e){return!(!HG(e)&&typeof e!="number"||isNaN(+vn(e)))}function PIe(e,t,n){const[r,s]=Wp(n==null?void 0:n.in,e,t),o=r.getFullYear()-s.getFullYear(),i=r.getMonth()-s.getMonth();return o*12+i}function OIe(e,t){const n=vn(e,t==null?void 0:t.in),r=n.getMonth();return n.setFullYear(n.getFullYear(),r+1,0),n.setHours(23,59,59,999),n}function FIe(e,t){const[n,r]=Wp(e,t.start,t.end);return{start:n,end:r}}function $Ie(e,t){const{start:n,end:r}=FIe(t==null?void 0:t.in,e);let s=+n>+r;const o=s?+n:+r,i=s?r:n;i.setHours(0,0,0,0),i.setDate(1);let a=1;const l=[];for(;+i<=o;)l.push(Er(n,i)),i.setMonth(i.getMonth()+a);return s?l.reverse():l}function LIe(e,t){const n=vn(e,t==null?void 0:t.in);return n.setDate(1),n.setHours(0,0,0,0),n}function zIe(e,t){const n=vn(e,t==null?void 0:t.in),r=n.getFullYear();return n.setFullYear(r+1,0,0),n.setHours(23,59,59,999),n}function UG(e,t){const n=vn(e,t==null?void 0:t.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}function WG(e,t){var a,l,u,d;const n=dx(),r=(t==null?void 0:t.weekStartsOn)??((l=(a=t==null?void 0:t.locale)==null?void 0:a.options)==null?void 0:l.weekStartsOn)??n.weekStartsOn??((d=(u=n.locale)==null?void 0:u.options)==null?void 0:d.weekStartsOn)??0,s=vn(e,t==null?void 0:t.in),o=s.getDay(),i=(o<r?-7:0)+6-(o-r);return s.setDate(s.getDate()+i),s.setHours(23,59,59,999),s}function BIe(e,t){return WG(e,{...t,weekStartsOn:1})}const VIe={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},HIe=(e,t,n)=>{let r;const s=VIe[e];return typeof s=="string"?r=s:t===1?r=s.one:r=s.other.replace("{{count}}",t.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function f2(e){return(t={})=>{const n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}const UIe={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},WIe={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},qIe={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},YIe={date:f2({formats:UIe,defaultWidth:"full"}),time:f2({formats:WIe,defaultWidth:"full"}),dateTime:f2({formats:qIe,defaultWidth:"full"})},GIe={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},KIe=(e,t,n,r)=>GIe[e];function bm(e){return(t,n)=>{const r=n!=null&&n.context?String(n.context):"standalone";let s;if(r==="formatting"&&e.formattingValues){const i=e.defaultFormattingWidth||e.defaultWidth,a=n!=null&&n.width?String(n.width):i;s=e.formattingValues[a]||e.formattingValues[i]}else{const i=e.defaultWidth,a=n!=null&&n.width?String(n.width):e.defaultWidth;s=e.values[a]||e.values[i]}const o=e.argumentCallback?e.argumentCallback(t):t;return s[o]}}const ZIe={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},XIe={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},QIe={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},JIe={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},eAe={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},tAe={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},nAe=(e,t)=>{const n=Number(e),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},rAe={ordinalNumber:nAe,era:bm({values:ZIe,defaultWidth:"wide"}),quarter:bm({values:XIe,defaultWidth:"wide",argumentCallback:e=>e-1}),month:bm({values:QIe,defaultWidth:"wide"}),day:bm({values:JIe,defaultWidth:"wide"}),dayPeriod:bm({values:eAe,defaultWidth:"wide",formattingValues:tAe,defaultFormattingWidth:"wide"})};function xm(e){return(t,n={})=>{const r=n.width,s=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],o=t.match(s);if(!o)return null;const i=o[0],a=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(a)?oAe(a,f=>f.test(i)):sAe(a,f=>f.test(i));let u;u=e.valueCallback?e.valueCallback(l):l,u=n.valueCallback?n.valueCallback(u):u;const d=t.slice(i.length);return{value:u,rest:d}}}function sAe(e,t){for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function oAe(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function iAe(e){return(t,n={})=>{const r=t.match(e.matchPattern);if(!r)return null;const s=r[0],o=t.match(e.parsePattern);if(!o)return null;let i=e.valueCallback?e.valueCallback(o[0]):o[0];i=n.valueCallback?n.valueCallback(i):i;const a=t.slice(s.length);return{value:i,rest:a}}}const aAe=/^(\d+)(th|st|nd|rd)?/i,lAe=/\d+/i,cAe={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},uAe={any:[/^b/i,/^(a|c)/i]},dAe={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},fAe={any:[/1/i,/2/i,/3/i,/4/i]},hAe={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},pAe={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},mAe={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},gAe={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},bAe={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},xAe={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},yAe={ordinalNumber:iAe({matchPattern:aAe,parsePattern:lAe,valueCallback:e=>parseInt(e,10)}),era:xm({matchPatterns:cAe,defaultMatchWidth:"wide",parsePatterns:uAe,defaultParseWidth:"any"}),quarter:xm({matchPatterns:dAe,defaultMatchWidth:"wide",parsePatterns:fAe,defaultParseWidth:"any",valueCallback:e=>e+1}),month:xm({matchPatterns:hAe,defaultMatchWidth:"wide",parsePatterns:pAe,defaultParseWidth:"any"}),day:xm({matchPatterns:mAe,defaultMatchWidth:"wide",parsePatterns:gAe,defaultParseWidth:"any"}),dayPeriod:xm({matchPatterns:bAe,defaultMatchWidth:"any",parsePatterns:xAe,defaultParseWidth:"any"})},cR={code:"en-US",formatDistance:HIe,formatLong:YIe,formatRelative:KIe,localize:rAe,match:yAe,options:{weekStartsOn:0,firstWeekContainsDate:1}};function vAe(e,t){const n=vn(e,t==null?void 0:t.in);return VG(n,UG(n))+1}function qG(e,t){const n=vn(e,t==null?void 0:t.in),r=+Jg(n)-+_Ie(n);return Math.round(r/$G)+1}function YG(e,t){var d,f,h,p;const n=vn(e,t==null?void 0:t.in),r=n.getFullYear(),s=dx(),o=(t==null?void 0:t.firstWeekContainsDate)??((f=(d=t==null?void 0:t.locale)==null?void 0:d.options)==null?void 0:f.firstWeekContainsDate)??s.firstWeekContainsDate??((p=(h=s.locale)==null?void 0:h.options)==null?void 0:p.firstWeekContainsDate)??1,i=Er((t==null?void 0:t.in)||e,0);i.setFullYear(r+1,0,o),i.setHours(0,0,0,0);const a=Zh(i,t),l=Er((t==null?void 0:t.in)||e,0);l.setFullYear(r,0,o),l.setHours(0,0,0,0);const u=Zh(l,t);return+n>=+a?r+1:+n>=+u?r:r-1}function wAe(e,t){var a,l,u,d;const n=dx(),r=(t==null?void 0:t.firstWeekContainsDate)??((l=(a=t==null?void 0:t.locale)==null?void 0:a.options)==null?void 0:l.firstWeekContainsDate)??n.firstWeekContainsDate??((d=(u=n.locale)==null?void 0:u.options)==null?void 0:d.firstWeekContainsDate)??1,s=YG(e,t),o=Er((t==null?void 0:t.in)||e,0);return o.setFullYear(s,0,r),o.setHours(0,0,0,0),Zh(o,t)}function GG(e,t){const n=vn(e,t==null?void 0:t.in),r=+Zh(n,t)-+wAe(n,t);return Math.round(r/$G)+1}function cn(e,t){const n=e<0?"-":"",r=Math.abs(e).toString().padStart(t,"0");return n+r}const Rl={y(e,t){const n=e.getFullYear(),r=n>0?n:1-n;return cn(t==="yy"?r%100:r,t.length)},M(e,t){const n=e.getMonth();return t==="M"?String(n+1):cn(n+1,2)},d(e,t){return cn(e.getDate(),t.length)},a(e,t){const n=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h(e,t){return cn(e.getHours()%12||12,t.length)},H(e,t){return cn(e.getHours(),t.length)},m(e,t){return cn(e.getMinutes(),t.length)},s(e,t){return cn(e.getSeconds(),t.length)},S(e,t){const n=t.length,r=e.getMilliseconds(),s=Math.trunc(r*Math.pow(10,n-3));return cn(s,t.length)}},Cf={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},_4={G:function(e,t,n){const r=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});case"GGGG":default:return n.era(r,{width:"wide"})}},y:function(e,t,n){if(t==="yo"){const r=e.getFullYear(),s=r>0?r:1-r;return n.ordinalNumber(s,{unit:"year"})}return Rl.y(e,t)},Y:function(e,t,n,r){const s=YG(e,r),o=s>0?s:1-s;if(t==="YY"){const i=o%100;return cn(i,2)}return t==="Yo"?n.ordinalNumber(o,{unit:"year"}):cn(o,t.length)},R:function(e,t){const n=BG(e);return cn(n,t.length)},u:function(e,t){const n=e.getFullYear();return cn(n,t.length)},Q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(r);case"QQ":return cn(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(r);case"qq":return cn(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,t,n){const r=e.getMonth();switch(t){case"M":case"MM":return Rl.M(e,t);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(e,t,n){const r=e.getMonth();switch(t){case"L":return String(r+1);case"LL":return cn(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(e,t,n,r){const s=GG(e,r);return t==="wo"?n.ordinalNumber(s,{unit:"week"}):cn(s,t.length)},I:function(e,t,n){const r=qG(e);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):cn(r,t.length)},d:function(e,t,n){return t==="do"?n.ordinalNumber(e.getDate(),{unit:"date"}):Rl.d(e,t)},D:function(e,t,n){const r=vAe(e);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):cn(r,t.length)},E:function(e,t,n){const r=e.getDay();switch(t){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});case"EEEE":default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(e,t,n,r){const s=e.getDay(),o=(s-r.weekStartsOn+8)%7||7;switch(t){case"e":return String(o);case"ee":return cn(o,2);case"eo":return n.ordinalNumber(o,{unit:"day"});case"eee":return n.day(s,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(s,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(s,{width:"short",context:"formatting"});case"eeee":default:return n.day(s,{width:"wide",context:"formatting"})}},c:function(e,t,n,r){const s=e.getDay(),o=(s-r.weekStartsOn+8)%7||7;switch(t){case"c":return String(o);case"cc":return cn(o,t.length);case"co":return n.ordinalNumber(o,{unit:"day"});case"ccc":return n.day(s,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(s,{width:"narrow",context:"standalone"});case"cccccc":return n.day(s,{width:"short",context:"standalone"});case"cccc":default:return n.day(s,{width:"wide",context:"standalone"})}},i:function(e,t,n){const r=e.getDay(),s=r===0?7:r;switch(t){case"i":return String(s);case"ii":return cn(s,t.length);case"io":return n.ordinalNumber(s,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});case"iiii":default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(e,t,n){const s=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(e,t,n){const r=e.getHours();let s;switch(r===12?s=Cf.noon:r===0?s=Cf.midnight:s=r/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},B:function(e,t,n){const r=e.getHours();let s;switch(r>=17?s=Cf.evening:r>=12?s=Cf.afternoon:r>=4?s=Cf.morning:s=Cf.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},h:function(e,t,n){if(t==="ho"){let r=e.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return Rl.h(e,t)},H:function(e,t,n){return t==="Ho"?n.ordinalNumber(e.getHours(),{unit:"hour"}):Rl.H(e,t)},K:function(e,t,n){const r=e.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):cn(r,t.length)},k:function(e,t,n){let r=e.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):cn(r,t.length)},m:function(e,t,n){return t==="mo"?n.ordinalNumber(e.getMinutes(),{unit:"minute"}):Rl.m(e,t)},s:function(e,t,n){return t==="so"?n.ordinalNumber(e.getSeconds(),{unit:"second"}):Rl.s(e,t)},S:function(e,t){return Rl.S(e,t)},X:function(e,t,n){const r=e.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return M4(r);case"XXXX":case"XX":return Cu(r);case"XXXXX":case"XXX":default:return Cu(r,":")}},x:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"x":return M4(r);case"xxxx":case"xx":return Cu(r);case"xxxxx":case"xxx":default:return Cu(r,":")}},O:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+D4(r,":");case"OOOO":default:return"GMT"+Cu(r,":")}},z:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+D4(r,":");case"zzzz":default:return"GMT"+Cu(r,":")}},t:function(e,t,n){const r=Math.trunc(+e/1e3);return cn(r,t.length)},T:function(e,t,n){return cn(+e,t.length)}};function D4(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),s=Math.trunc(r/60),o=r%60;return o===0?n+String(s):n+String(s)+t+cn(o,2)}function M4(e,t){return e%60===0?(e>0?"-":"+")+cn(Math.abs(e)/60,2):Cu(e,t)}function Cu(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),s=cn(Math.trunc(r/60),2),o=cn(r%60,2);return n+s+t+o}const T4=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});case"PPPP":default:return t.date({width:"full"})}},KG=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});case"pppp":default:return t.time({width:"full"})}},SAe=(e,t)=>{const n=e.match(/(P+)(p+)?/)||[],r=n[1],s=n[2];if(!s)return T4(e,t);let o;switch(r){case"P":o=t.dateTime({width:"short"});break;case"PP":o=t.dateTime({width:"medium"});break;case"PPP":o=t.dateTime({width:"long"});break;case"PPPP":default:o=t.dateTime({width:"full"});break}return o.replace("{{date}}",T4(r,t)).replace("{{time}}",KG(s,t))},CAe={p:KG,P:SAe},NAe=/^D+$/,jAe=/^Y+$/,kAe=["D","DD","YY","YYYY"];function EAe(e){return NAe.test(e)}function _Ae(e){return jAe.test(e)}function DAe(e,t,n){const r=MAe(e,t,n);if(console.warn(r),kAe.includes(e))throw new RangeError(r)}function MAe(e,t,n){const r=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const TAe=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,RAe=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,IAe=/^'([^]*?)'?$/,AAe=/''/g,PAe=/[a-zA-Z]/;function OAe(e,t,n){var d,f,h,p,m,g,b,x;const r=dx(),s=(n==null?void 0:n.locale)??r.locale??cR,o=(n==null?void 0:n.firstWeekContainsDate)??((f=(d=n==null?void 0:n.locale)==null?void 0:d.options)==null?void 0:f.firstWeekContainsDate)??r.firstWeekContainsDate??((p=(h=r.locale)==null?void 0:h.options)==null?void 0:p.firstWeekContainsDate)??1,i=(n==null?void 0:n.weekStartsOn)??((g=(m=n==null?void 0:n.locale)==null?void 0:m.options)==null?void 0:g.weekStartsOn)??r.weekStartsOn??((x=(b=r.locale)==null?void 0:b.options)==null?void 0:x.weekStartsOn)??0,a=vn(e,n==null?void 0:n.in);if(!AIe(a))throw new RangeError("Invalid time value");let l=t.match(RAe).map(y=>{const v=y[0];if(v==="p"||v==="P"){const w=CAe[v];return w(y,s.formatLong)}return y}).join("").match(TAe).map(y=>{if(y==="''")return{isToken:!1,value:"'"};const v=y[0];if(v==="'")return{isToken:!1,value:FAe(y)};if(_4[v])return{isToken:!0,value:y};if(v.match(PAe))throw new RangeError("Format string contains an unescaped latin alphabet character `"+v+"`");return{isToken:!1,value:y}});s.localize.preprocessor&&(l=s.localize.preprocessor(a,l));const u={firstWeekContainsDate:o,weekStartsOn:i,locale:s};return l.map(y=>{if(!y.isToken)return y.value;const v=y.value;(!(n!=null&&n.useAdditionalWeekYearTokens)&&_Ae(v)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&EAe(v))&&DAe(v,t,String(e));const w=_4[v[0]];return w(a,v,s.localize,u)}).join("")}function FAe(e){const t=e.match(IAe);return t?t[1].replace(AAe,"'"):e}function $Ae(e,t){const n=vn(e,t==null?void 0:t.in),r=n.getFullYear(),s=n.getMonth(),o=Er(n,0);return o.setFullYear(r,s+1,0),o.setHours(0,0,0,0),o.getDate()}function LAe(e,t){return vn(e,t==null?void 0:t.in).getMonth()}function zAe(e,t){return vn(e,t==null?void 0:t.in).getFullYear()}function BAe(e,t){return+vn(e)>+vn(t)}function VAe(e,t){return+vn(e)<+vn(t)}function HAe(e,t,n){const[r,s]=Wp(n==null?void 0:n.in,e,t);return r.getFullYear()===s.getFullYear()&&r.getMonth()===s.getMonth()}function UAe(e,t,n){const[r,s]=Wp(n==null?void 0:n.in,e,t);return r.getFullYear()===s.getFullYear()}function WAe(e,t,n){const r=vn(e,n==null?void 0:n.in),s=r.getFullYear(),o=r.getDate(),i=Er(e,0);i.setFullYear(s,t,15),i.setHours(0,0,0,0);const a=$Ae(i);return r.setMonth(t,Math.min(o,a)),r}function qAe(e,t,n){const r=vn(e,n==null?void 0:n.in);return isNaN(+r)?Er(e,NaN):(r.setFullYear(t),r)}const R4=5,YAe=4;function GAe(e,t){const n=t.startOfMonth(e),r=n.getDay()>0?n.getDay():7,s=t.addDays(e,-r+1),o=t.addDays(s,R4*7-1);return t.getMonth(e)===t.getMonth(o)?R4:YAe}function ZG(e,t){const n=t.startOfMonth(e),r=n.getDay();return r===1?n:r===0?t.addDays(n,-1*6):t.addDays(n,-1*(r-1))}function KAe(e,t){const n=ZG(e,t),r=GAe(e,t);return t.addDays(n,r*7-1)}class Cl{constructor(t,n){this.Date=Date,this.today=()=>{var r;return(r=this.overrides)!=null&&r.today?this.overrides.today():this.options.timeZone?Qr.tz(this.options.timeZone):new this.Date},this.newDate=(r,s,o)=>{var i;return(i=this.overrides)!=null&&i.newDate?this.overrides.newDate(r,s,o):this.options.timeZone?new Qr(r,s,o,this.options.timeZone):new Date(r,s,o)},this.addDays=(r,s)=>{var o;return(o=this.overrides)!=null&&o.addDays?this.overrides.addDays(r,s):LG(r,s)},this.addMonths=(r,s)=>{var o;return(o=this.overrides)!=null&&o.addMonths?this.overrides.addMonths(r,s):zG(r,s)},this.addWeeks=(r,s)=>{var o;return(o=this.overrides)!=null&&o.addWeeks?this.overrides.addWeeks(r,s):DIe(r,s)},this.addYears=(r,s)=>{var o;return(o=this.overrides)!=null&&o.addYears?this.overrides.addYears(r,s):MIe(r,s)},this.differenceInCalendarDays=(r,s)=>{var o;return(o=this.overrides)!=null&&o.differenceInCalendarDays?this.overrides.differenceInCalendarDays(r,s):VG(r,s)},this.differenceInCalendarMonths=(r,s)=>{var o;return(o=this.overrides)!=null&&o.differenceInCalendarMonths?this.overrides.differenceInCalendarMonths(r,s):PIe(r,s)},this.eachMonthOfInterval=r=>{var s;return(s=this.overrides)!=null&&s.eachMonthOfInterval?this.overrides.eachMonthOfInterval(r):$Ie(r)},this.endOfBroadcastWeek=r=>{var s;return(s=this.overrides)!=null&&s.endOfBroadcastWeek?this.overrides.endOfBroadcastWeek(r):KAe(r,this)},this.endOfISOWeek=r=>{var s;return(s=this.overrides)!=null&&s.endOfISOWeek?this.overrides.endOfISOWeek(r):BIe(r)},this.endOfMonth=r=>{var s;return(s=this.overrides)!=null&&s.endOfMonth?this.overrides.endOfMonth(r):OIe(r)},this.endOfWeek=(r,s)=>{var o;return(o=this.overrides)!=null&&o.endOfWeek?this.overrides.endOfWeek(r,s):WG(r,this.options)},this.endOfYear=r=>{var s;return(s=this.overrides)!=null&&s.endOfYear?this.overrides.endOfYear(r):zIe(r)},this.format=(r,s,o)=>{var a;const i=(a=this.overrides)!=null&&a.format?this.overrides.format(r,s,this.options):OAe(r,s,this.options);return this.options.numerals&&this.options.numerals!=="latn"?this.replaceDigits(i):i},this.getISOWeek=r=>{var s;return(s=this.overrides)!=null&&s.getISOWeek?this.overrides.getISOWeek(r):qG(r)},this.getMonth=(r,s)=>{var o;return(o=this.overrides)!=null&&o.getMonth?this.overrides.getMonth(r,this.options):LAe(r,this.options)},this.getYear=(r,s)=>{var o;return(o=this.overrides)!=null&&o.getYear?this.overrides.getYear(r,this.options):zAe(r,this.options)},this.getWeek=(r,s)=>{var o;return(o=this.overrides)!=null&&o.getWeek?this.overrides.getWeek(r,this.options):GG(r,this.options)},this.isAfter=(r,s)=>{var o;return(o=this.overrides)!=null&&o.isAfter?this.overrides.isAfter(r,s):BAe(r,s)},this.isBefore=(r,s)=>{var o;return(o=this.overrides)!=null&&o.isBefore?this.overrides.isBefore(r,s):VAe(r,s)},this.isDate=r=>{var s;return(s=this.overrides)!=null&&s.isDate?this.overrides.isDate(r):HG(r)},this.isSameDay=(r,s)=>{var o;return(o=this.overrides)!=null&&o.isSameDay?this.overrides.isSameDay(r,s):IIe(r,s)},this.isSameMonth=(r,s)=>{var o;return(o=this.overrides)!=null&&o.isSameMonth?this.overrides.isSameMonth(r,s):HAe(r,s)},this.isSameYear=(r,s)=>{var o;return(o=this.overrides)!=null&&o.isSameYear?this.overrides.isSameYear(r,s):UAe(r,s)},this.max=r=>{var s;return(s=this.overrides)!=null&&s.max?this.overrides.max(r):TIe(r)},this.min=r=>{var s;return(s=this.overrides)!=null&&s.min?this.overrides.min(r):RIe(r)},this.setMonth=(r,s)=>{var o;return(o=this.overrides)!=null&&o.setMonth?this.overrides.setMonth(r,s):WAe(r,s)},this.setYear=(r,s)=>{var o;return(o=this.overrides)!=null&&o.setYear?this.overrides.setYear(r,s):qAe(r,s)},this.startOfBroadcastWeek=(r,s)=>{var o;return(o=this.overrides)!=null&&o.startOfBroadcastWeek?this.overrides.startOfBroadcastWeek(r,this):ZG(r,this)},this.startOfDay=r=>{var s;return(s=this.overrides)!=null&&s.startOfDay?this.overrides.startOfDay(r):eb(r)},this.startOfISOWeek=r=>{var s;return(s=this.overrides)!=null&&s.startOfISOWeek?this.overrides.startOfISOWeek(r):Jg(r)},this.startOfMonth=r=>{var s;return(s=this.overrides)!=null&&s.startOfMonth?this.overrides.startOfMonth(r):LIe(r)},this.startOfWeek=(r,s)=>{var o;return(o=this.overrides)!=null&&o.startOfWeek?this.overrides.startOfWeek(r,this.options):Zh(r,this.options)},this.startOfYear=r=>{var s;return(s=this.overrides)!=null&&s.startOfYear?this.overrides.startOfYear(r):UG(r)},this.options={locale:cR,...t},this.overrides=n}getDigitMap(){const{numerals:t="latn"}=this.options,n=new Intl.NumberFormat("en-US",{numberingSystem:t}),r={};for(let s=0;s<10;s++)r[s.toString()]=n.format(s);return r}replaceDigits(t){const n=this.getDigitMap();return t.replace(/\d/g,r=>n[r]||r)}formatNumber(t){return this.replaceDigits(t.toString())}}const ka=new Cl;class XG{constructor(t,n,r=ka){this.date=t,this.displayMonth=n,this.outside=!!(n&&!r.isSameMonth(t,n)),this.dateLib=r}isEqualTo(t){return this.dateLib.isSameDay(t.date,this.date)&&this.dateLib.isSameMonth(t.displayMonth,this.displayMonth)}}class ZAe{constructor(t,n){this.date=t,this.weeks=n}}class XAe{constructor(t,n){this.days=n,this.weekNumber=t}}function QAe(e){return N.createElement("button",{...e})}function JAe(e){return N.createElement("span",{...e})}function ePe(e){const{size:t=24,orientation:n="left",className:r}=e;return N.createElement("svg",{className:r,width:t,height:t,viewBox:"0 0 24 24"},n==="up"&&N.createElement("polygon",{points:"6.77 17 12.5 11.43 18.24 17 20 15.28 12.5 8 5 15.28"}),n==="down"&&N.createElement("polygon",{points:"6.77 8 12.5 13.57 18.24 8 20 9.72 12.5 17 5 9.72"}),n==="left"&&N.createElement("polygon",{points:"16 18.112 9.81111111 12 16 5.87733333 14.0888889 4 6 12 14.0888889 20"}),n==="right"&&N.createElement("polygon",{points:"8 18.112 14.18888889 12 8 5.87733333 9.91111111 4 18 12 9.91111111 20"}))}function tPe(e){const{day:t,modifiers:n,...r}=e;return N.createElement("td",{...r})}function nPe(e){const{day:t,modifiers:n,...r}=e,s=N.useRef(null);return N.useEffect(()=>{var o;n.focused&&((o=s.current)==null||o.focus())},[n.focused]),N.createElement("button",{ref:s,...r})}var Xe;(function(e){e.Root="root",e.Chevron="chevron",e.Day="day",e.DayButton="day_button",e.CaptionLabel="caption_label",e.Dropdowns="dropdowns",e.Dropdown="dropdown",e.DropdownRoot="dropdown_root",e.Footer="footer",e.MonthGrid="month_grid",e.MonthCaption="month_caption",e.MonthsDropdown="months_dropdown",e.Month="month",e.Months="months",e.Nav="nav",e.NextMonthButton="button_next",e.PreviousMonthButton="button_previous",e.Week="week",e.Weeks="weeks",e.Weekday="weekday",e.Weekdays="weekdays",e.WeekNumber="week_number",e.WeekNumberHeader="week_number_header",e.YearsDropdown="years_dropdown"})(Xe||(Xe={}));var qn;(function(e){e.disabled="disabled",e.hidden="hidden",e.outside="outside",e.focused="focused",e.today="today"})(qn||(qn={}));var mi;(function(e){e.range_end="range_end",e.range_middle="range_middle",e.range_start="range_start",e.selected="selected"})(mi||(mi={}));var io;(function(e){e.weeks_before_enter="weeks_before_enter",e.weeks_before_exit="weeks_before_exit",e.weeks_after_enter="weeks_after_enter",e.weeks_after_exit="weeks_after_exit",e.caption_after_enter="caption_after_enter",e.caption_after_exit="caption_after_exit",e.caption_before_enter="caption_before_enter",e.caption_before_exit="caption_before_exit"})(io||(io={}));function rPe(e){const{options:t,className:n,components:r,classNames:s,...o}=e,i=[s[Xe.Dropdown],n].join(" "),a=t==null?void 0:t.find(({value:l})=>l===o.value);return N.createElement("span",{"data-disabled":o.disabled,className:s[Xe.DropdownRoot]},N.createElement(r.Select,{className:i,...o},t==null?void 0:t.map(({value:l,label:u,disabled:d})=>N.createElement(r.Option,{key:l,value:l,disabled:d},u))),N.createElement("span",{className:s[Xe.CaptionLabel],"aria-hidden":!0},a==null?void 0:a.label,N.createElement(r.Chevron,{orientation:"down",size:18,className:s[Xe.Chevron]})))}function sPe(e){return N.createElement("div",{...e})}function oPe(e){return N.createElement("div",{...e})}function iPe(e){const{calendarMonth:t,displayIndex:n,...r}=e;return N.createElement("div",{...r},e.children)}function aPe(e){const{calendarMonth:t,displayIndex:n,...r}=e;return N.createElement("div",{...r})}function lPe(e){return N.createElement("table",{...e})}function cPe(e){return N.createElement("div",{...e})}const QG=N.createContext(void 0);function fx(){const e=N.useContext(QG);if(e===void 0)throw new Error("useDayPicker() must be used within a custom component.");return e}function uPe(e){const{components:t}=fx();return N.createElement(t.Dropdown,{...e})}function dPe(e){const{onPreviousClick:t,onNextClick:n,previousMonth:r,nextMonth:s,...o}=e,{components:i,classNames:a,labels:{labelPrevious:l,labelNext:u}}=fx(),d=N.useCallback(h=>{s&&(n==null||n(h))},[s,n]),f=N.useCallback(h=>{r&&(t==null||t(h))},[r,t]);return N.createElement("nav",{...o},N.createElement(i.PreviousMonthButton,{type:"button",className:a[Xe.PreviousMonthButton],tabIndex:r?void 0:-1,"aria-disabled":r?void 0:!0,"aria-label":l(r),onClick:f},N.createElement(i.Chevron,{disabled:r?void 0:!0,className:a[Xe.Chevron],orientation:"left"})),N.createElement(i.NextMonthButton,{type:"button",className:a[Xe.NextMonthButton],tabIndex:s?void 0:-1,"aria-disabled":s?void 0:!0,"aria-label":u(s),onClick:d},N.createElement(i.Chevron,{disabled:s?void 0:!0,orientation:"right",className:a[Xe.Chevron]})))}function fPe(e){const{components:t}=fx();return N.createElement(t.Button,{...e})}function hPe(e){return N.createElement("option",{...e})}function pPe(e){const{components:t}=fx();return N.createElement(t.Button,{...e})}function mPe(e){const{rootRef:t,...n}=e;return N.createElement("div",{...n,ref:t})}function gPe(e){return N.createElement("select",{...e})}function bPe(e){const{week:t,...n}=e;return N.createElement("tr",{...n})}function xPe(e){return N.createElement("th",{...e})}function yPe(e){return N.createElement("thead",{"aria-hidden":!0},N.createElement("tr",{...e}))}function vPe(e){const{week:t,...n}=e;return N.createElement("th",{...n})}function wPe(e){return N.createElement("th",{...e})}function SPe(e){return N.createElement("tbody",{...e})}function CPe(e){const{components:t}=fx();return N.createElement(t.Dropdown,{...e})}const NPe=Object.freeze(Object.defineProperty({__proto__:null,Button:QAe,CaptionLabel:JAe,Chevron:ePe,Day:tPe,DayButton:nPe,Dropdown:rPe,DropdownNav:sPe,Footer:oPe,Month:iPe,MonthCaption:aPe,MonthGrid:lPe,Months:cPe,MonthsDropdown:uPe,Nav:dPe,NextMonthButton:fPe,Option:hPe,PreviousMonthButton:pPe,Root:mPe,Select:gPe,Week:bPe,WeekNumber:vPe,WeekNumberHeader:wPe,Weekday:xPe,Weekdays:yPe,Weeks:SPe,YearsDropdown:CPe},Symbol.toStringTag,{value:"Module"}));function tl(e,t,n=!1,r=ka){let{from:s,to:o}=e;const{differenceInCalendarDays:i,isSameDay:a}=r;return s&&o?(i(o,s)<0&&([s,o]=[o,s]),i(t,s)>=(n?1:0)&&i(o,t)>=(n?1:0)):!n&&o?a(o,t):!n&&s?a(s,t):!1}function JG(e){return!!(e&&typeof e=="object"&&"before"in e&&"after"in e)}function uR(e){return!!(e&&typeof e=="object"&&"from"in e)}function eK(e){return!!(e&&typeof e=="object"&&"after"in e)}function tK(e){return!!(e&&typeof e=="object"&&"before"in e)}function nK(e){return!!(e&&typeof e=="object"&&"dayOfWeek"in e)}function rK(e,t){return Array.isArray(e)&&e.every(t.isDate)}function nl(e,t,n=ka){const r=Array.isArray(t)?t:[t],{isSameDay:s,differenceInCalendarDays:o,isAfter:i}=n;return r.some(a=>{if(typeof a=="boolean")return a;if(n.isDate(a))return s(e,a);if(rK(a,n))return a.includes(e);if(uR(a))return tl(a,e,!1,n);if(nK(a))return Array.isArray(a.dayOfWeek)?a.dayOfWeek.includes(e.getDay()):a.dayOfWeek===e.getDay();if(JG(a)){const l=o(a.before,e),u=o(a.after,e),d=l>0,f=u<0;return i(a.before,a.after)?f&&d:d||f}return eK(a)?o(e,a.after)>0:tK(a)?o(a.before,e)>0:typeof a=="function"?a(e):!1})}function jPe(e,t,n,r,s){const{disabled:o,hidden:i,modifiers:a,showOutsideDays:l,broadcastCalendar:u,today:d}=t,{isSameDay:f,isSameMonth:h,startOfMonth:p,isBefore:m,endOfMonth:g,isAfter:b}=s,x=n&&p(n),y=r&&g(r),v={[qn.focused]:[],[qn.outside]:[],[qn.disabled]:[],[qn.hidden]:[],[qn.today]:[]},w={};for(const S of e){const{date:C,displayMonth:j}=S,D=!!(j&&!h(C,j)),k=!!(x&&m(C,x)),_=!!(y&&b(C,y)),M=!!(o&&nl(C,o,s)),R=!!(i&&nl(C,i,s))||k||_||!u&&!l&&D||u&&l===!1&&D,O=f(C,d??s.today());D&&v.outside.push(S),M&&v.disabled.push(S),R&&v.hidden.push(S),O&&v.today.push(S),a&&Object.keys(a).forEach(T=>{const I=a==null?void 0:a[T];I&&nl(C,I,s)&&(w[T]?w[T].push(S):w[T]=[S])})}return S=>{const C={[qn.focused]:!1,[qn.disabled]:!1,[qn.hidden]:!1,[qn.outside]:!1,[qn.today]:!1},j={};for(const D in v){const k=v[D];C[D]=k.some(_=>_===S)}for(const D in w)j[D]=w[D].some(k=>k===S);return{...C,...j}}}function kPe(e,t,n={}){return Object.entries(e).filter(([,s])=>s===!0).reduce((s,[o])=>(n[o]?s.push(n[o]):t[qn[o]]?s.push(t[qn[o]]):t[mi[o]]&&s.push(t[mi[o]]),s),[t[Xe.Day]])}function EPe(e){return{...NPe,...e}}function _Pe(e){const t={"data-mode":e.mode??void 0,"data-required":"required"in e?e.required:void 0,"data-multiple-months":e.numberOfMonths&&e.numberOfMonths>1||void 0,"data-week-numbers":e.showWeekNumber||void 0,"data-broadcast-calendar":e.broadcastCalendar||void 0,"data-nav-layout":e.navLayout||void 0};return Object.entries(e).forEach(([n,r])=>{n.startsWith("data-")&&(t[n]=r)}),t}function dR(){const e={};for(const t in Xe)e[Xe[t]]=`rdp-${Xe[t]}`;for(const t in qn)e[qn[t]]=`rdp-${qn[t]}`;for(const t in mi)e[mi[t]]=`rdp-${mi[t]}`;for(const t in io)e[io[t]]=`rdp-${io[t]}`;return e}function sK(e,t,n){return(n??new Cl(t)).format(e,"LLLL y")}const DPe=sK;function MPe(e,t,n){return(n??new Cl(t)).format(e,"d")}function TPe(e,t=ka){return t.format(e,"LLLL")}function RPe(e,t,n){return(n??new Cl(t)).format(e,"cccccc")}function IPe(e,t=ka){return e<10?t.formatNumber(`0${e.toLocaleString()}`):t.formatNumber(`${e.toLocaleString()}`)}function APe(){return""}function oK(e,t=ka){return t.format(e,"yyyy")}const PPe=oK,OPe=Object.freeze(Object.defineProperty({__proto__:null,formatCaption:sK,formatDay:MPe,formatMonthCaption:DPe,formatMonthDropdown:TPe,formatWeekNumber:IPe,formatWeekNumberHeader:APe,formatWeekdayName:RPe,formatYearCaption:PPe,formatYearDropdown:oK},Symbol.toStringTag,{value:"Module"}));function FPe(e){return e!=null&&e.formatMonthCaption&&!e.formatCaption&&(e.formatCaption=e.formatMonthCaption),e!=null&&e.formatYearCaption&&!e.formatYearDropdown&&(e.formatYearDropdown=e.formatYearCaption),{...OPe,...e}}function $Pe(e,t,n,r,s){const{startOfMonth:o,startOfYear:i,endOfYear:a,eachMonthOfInterval:l,getMonth:u}=s;return l({start:i(e),end:a(e)}).map(h=>{const p=r.formatMonthDropdown(h,s),m=u(h),g=t&&h<o(t)||n&&h>o(n)||!1;return{value:m,label:p,disabled:g}})}function LPe(e,t={},n={}){let r={...t==null?void 0:t[Xe.Day]};return Object.entries(e).filter(([,s])=>s===!0).forEach(([s])=>{r={...r,...n==null?void 0:n[s]}}),r}function zPe(e,t,n){const r=e.today(),s=t?e.startOfISOWeek(r):e.startOfWeek(r),o=[];for(let i=0;i<7;i++){const a=e.addDays(s,i);o.push(a)}return o}function BPe(e,t,n,r,s=!1){if(!e||!t)return;const{startOfYear:o,endOfYear:i,addYears:a,getYear:l,isBefore:u,isSameYear:d}=r,f=o(e),h=i(t),p=[];let m=f;for(;u(m,h)||d(m,h);)p.push(m),m=a(m,1);return s&&p.reverse(),p.map(g=>{const b=n.formatYearDropdown(g,r);return{value:l(g),label:b,disabled:!1}})}function iK(e,t,n,r){let s=(r??new Cl(n)).format(e,"PPPP");return t.today&&(s=`Today, ${s}`),t.selected&&(s=`${s}, selected`),s}const VPe=iK;function aK(e,t,n){return(n??new Cl(t)).format(e,"LLLL y")}const HPe=aK;function UPe(e,t,n,r){let s=(r??new Cl(n)).format(e,"PPPP");return t!=null&&t.today&&(s=`Today, ${s}`),s}function WPe(e){return"Choose the Month"}function qPe(){return""}function YPe(e){return"Go to the Next Month"}function GPe(e){return"Go to the Previous Month"}function KPe(e,t,n){return(n??new Cl(t)).format(e,"cccc")}function ZPe(e,t){return`Week ${e}`}function XPe(e){return"Week Number"}function QPe(e){return"Choose the Year"}const JPe=Object.freeze(Object.defineProperty({__proto__:null,labelCaption:HPe,labelDay:VPe,labelDayButton:iK,labelGrid:aK,labelGridcell:UPe,labelMonthDropdown:WPe,labelNav:qPe,labelNext:YPe,labelPrevious:GPe,labelWeekNumber:ZPe,labelWeekNumberHeader:XPe,labelWeekday:KPe,labelYearDropdown:QPe},Symbol.toStringTag,{value:"Module"})),hx=e=>e instanceof HTMLElement?e:null,h2=e=>[...e.querySelectorAll("[data-animated-month]")??[]],eOe=e=>hx(e.querySelector("[data-animated-month]")),p2=e=>hx(e.querySelector("[data-animated-caption]")),m2=e=>hx(e.querySelector("[data-animated-weeks]")),tOe=e=>hx(e.querySelector("[data-animated-nav]")),nOe=e=>hx(e.querySelector("[data-animated-weekdays]"));function rOe(e,t,{classNames:n,months:r,focused:s,dateLib:o}){const i=N.useRef(null),a=N.useRef(r),l=N.useRef(!1);N.useLayoutEffect(()=>{const u=a.current;if(a.current=r,!t||!e.current||!(e.current instanceof HTMLElement)||r.length===0||u.length===0||r.length!==u.length)return;const d=o.isSameMonth(r[0].date,u[0].date),f=o.isAfter(r[0].date,u[0].date),h=f?n[io.caption_after_enter]:n[io.caption_before_enter],p=f?n[io.weeks_after_enter]:n[io.weeks_before_enter],m=i.current,g=e.current.cloneNode(!0);if(g instanceof HTMLElement?(h2(g).forEach(v=>{if(!(v instanceof HTMLElement))return;const w=eOe(v);w&&v.contains(w)&&v.removeChild(w);const S=p2(v);S&&S.classList.remove(h);const C=m2(v);C&&C.classList.remove(p)}),i.current=g):i.current=null,l.current||d||s)return;const b=m instanceof HTMLElement?h2(m):[],x=h2(e.current);if(x!=null&&x.every(y=>y instanceof HTMLElement)&&b&&b.every(y=>y instanceof HTMLElement)){l.current=!0,e.current.style.isolation="isolate";const y=tOe(e.current);y&&(y.style.zIndex="1"),x.forEach((v,w)=>{const S=b[w];if(!S)return;v.style.position="relative",v.style.overflow="hidden";const C=p2(v);C&&C.classList.add(h);const j=m2(v);j&&j.classList.add(p);const D=()=>{l.current=!1,e.current&&(e.current.style.isolation=""),y&&(y.style.zIndex=""),C&&C.classList.remove(h),j&&j.classList.remove(p),v.style.position="",v.style.overflow="",v.contains(S)&&v.removeChild(S)};S.style.pointerEvents="none",S.style.position="absolute",S.style.overflow="hidden",S.setAttribute("aria-hidden","true");const k=nOe(S);k&&(k.style.opacity="0");const _=p2(S);_&&(_.classList.add(f?n[io.caption_before_exit]:n[io.caption_after_exit]),_.addEventListener("animationend",D));const M=m2(S);M&&M.classList.add(f?n[io.weeks_before_exit]:n[io.weeks_after_exit]),v.insertBefore(S,v.firstChild)})}})}function sOe(e,t,n,r){const s=e[0],o=e[e.length-1],{ISOWeek:i,fixedWeeks:a,broadcastCalendar:l}=n??{},{addDays:u,differenceInCalendarDays:d,differenceInCalendarMonths:f,endOfBroadcastWeek:h,endOfISOWeek:p,endOfMonth:m,endOfWeek:g,isAfter:b,startOfBroadcastWeek:x,startOfISOWeek:y,startOfWeek:v}=r,w=l?x(s,r):i?y(s):v(s),S=l?h(o):i?p(m(o)):g(m(o)),C=d(S,w),j=f(o,s)+1,D=[];for(let M=0;M<=C;M++){const R=u(w,M);if(t&&b(R,t))break;D.push(R)}const _=(l?35:42)*j;if(a&&D.length<_){const M=_-D.length;for(let R=0;R<M;R++){const O=u(D[D.length-1],1);D.push(O)}}return D}function oOe(e){const t=[];return e.reduce((n,r)=>{const s=r.weeks.reduce((o,i)=>o.concat(i.days.slice()),t.slice());return n.concat(s.slice())},t.slice())}function iOe(e,t,n,r){const{numberOfMonths:s=1}=n,o=[];for(let i=0;i<s;i++){const a=r.addMonths(e,i);if(t&&a>t)break;o.push(a)}return o}function I4(e,t,n,r){const{month:s,defaultMonth:o,today:i=r.today(),numberOfMonths:a=1}=e;let l=s||o||i;const{differenceInCalendarMonths:u,addMonths:d,startOfMonth:f}=r;if(n&&u(n,l)<a-1){const h=-1*(a-1);l=d(n,h)}return t&&u(l,t)<0&&(l=t),f(l)}function aOe(e,t,n,r){const{addDays:s,endOfBroadcastWeek:o,endOfISOWeek:i,endOfMonth:a,endOfWeek:l,getISOWeek:u,getWeek:d,startOfBroadcastWeek:f,startOfISOWeek:h,startOfWeek:p}=r,m=e.reduce((g,b)=>{const x=n.broadcastCalendar?f(b,r):n.ISOWeek?h(b):p(b),y=n.broadcastCalendar?o(b):n.ISOWeek?i(a(b)):l(a(b)),v=t.filter(j=>j>=x&&j<=y),w=n.broadcastCalendar?35:42;if(n.fixedWeeks&&v.length<w){const j=t.filter(D=>{const k=w-v.length;return D>y&&D<=s(y,k)});v.push(...j)}const S=v.reduce((j,D)=>{const k=n.ISOWeek?u(D):d(D),_=j.find(R=>R.weekNumber===k),M=new XG(D,b,r);return _?_.days.push(M):j.push(new XAe(k,[M])),j},[]),C=new ZAe(b,S);return g.push(C),g},[]);return n.reverseMonths?m.reverse():m}function lOe(e,t){let{startMonth:n,endMonth:r}=e;const{startOfYear:s,startOfDay:o,startOfMonth:i,endOfMonth:a,addYears:l,endOfYear:u,newDate:d,today:f}=t,{fromYear:h,toYear:p,fromMonth:m,toMonth:g}=e;!n&&m&&(n=m),!n&&h&&(n=t.newDate(h,0,1)),!r&&g&&(r=g),!r&&p&&(r=d(p,11,31));const b=e.captionLayout==="dropdown"||e.captionLayout==="dropdown-years";return n?n=i(n):h?n=d(h,0,1):!n&&b&&(n=s(l(e.today??f(),-100))),r?r=a(r):p?r=d(p,11,31):!r&&b&&(r=u(e.today??f())),[n&&o(n),r&&o(r)]}function cOe(e,t,n,r){if(n.disableNavigation)return;const{pagedNavigation:s,numberOfMonths:o=1}=n,{startOfMonth:i,addMonths:a,differenceInCalendarMonths:l}=r,u=s?o:1,d=i(e);if(!t)return a(d,u);if(!(l(t,e)<o))return a(d,u)}function uOe(e,t,n,r){if(n.disableNavigation)return;const{pagedNavigation:s,numberOfMonths:o}=n,{startOfMonth:i,addMonths:a,differenceInCalendarMonths:l}=r,u=s?o??1:1,d=i(e);if(!t)return a(d,-u);if(!(l(d,t)<=0))return a(d,-u)}function dOe(e){const t=[];return e.reduce((n,r)=>n.concat(r.weeks.slice()),t.slice())}function gS(e,t){const[n,r]=N.useState(e);return[t===void 0?n:t,r]}function fOe(e,t){const[n,r]=lOe(e,t),{startOfMonth:s,endOfMonth:o}=t,i=I4(e,n,r,t),[a,l]=gS(i,e.month?i:void 0);N.useEffect(()=>{const C=I4(e,n,r,t);l(C)},[e.timeZone]);const u=iOe(a,r,e,t),d=sOe(u,e.endMonth?o(e.endMonth):void 0,e,t),f=aOe(u,d,e,t),h=dOe(f),p=oOe(f),m=uOe(a,n,e,t),g=cOe(a,r,e,t),{disableNavigation:b,onMonthChange:x}=e,y=C=>h.some(j=>j.days.some(D=>D.isEqualTo(C))),v=C=>{if(b)return;let j=s(C);n&&j<s(n)&&(j=s(n)),r&&j>s(r)&&(j=s(r)),l(j),x==null||x(j)};return{months:f,weeks:h,days:p,navStart:n,navEnd:r,previousMonth:m,nextMonth:g,goToMonth:v,goToDay:C=>{y(C)||v(C.date)}}}var Vi;(function(e){e[e.Today=0]="Today",e[e.Selected=1]="Selected",e[e.LastFocused=2]="LastFocused",e[e.FocusedModifier=3]="FocusedModifier"})(Vi||(Vi={}));function A4(e){return!e[qn.disabled]&&!e[qn.hidden]&&!e[qn.outside]}function hOe(e,t,n,r){let s,o=-1;for(const i of e){const a=t(i);A4(a)&&(a[qn.focused]&&o<Vi.FocusedModifier?(s=i,o=Vi.FocusedModifier):r!=null&&r.isEqualTo(i)&&o<Vi.LastFocused?(s=i,o=Vi.LastFocused):n(i.date)&&o<Vi.Selected?(s=i,o=Vi.Selected):a[qn.today]&&o<Vi.Today&&(s=i,o=Vi.Today))}return s||(s=e.find(i=>A4(t(i)))),s}function pOe(e,t,n,r,s,o,i){const{ISOWeek:a,broadcastCalendar:l}=o,{addDays:u,addMonths:d,addWeeks:f,addYears:h,endOfBroadcastWeek:p,endOfISOWeek:m,endOfWeek:g,max:b,min:x,startOfBroadcastWeek:y,startOfISOWeek:v,startOfWeek:w}=i;let C={day:u,week:f,month:d,year:h,startOfWeek:j=>l?y(j,i):a?v(j):w(j),endOfWeek:j=>l?p(j):a?m(j):g(j)}[e](n,t==="after"?1:-1);return t==="before"&&r?C=b([r,C]):t==="after"&&s&&(C=x([s,C])),C}function lK(e,t,n,r,s,o,i,a=0){if(a>365)return;const l=pOe(e,t,n.date,r,s,o,i),u=!!(o.disabled&&nl(l,o.disabled,i)),d=!!(o.hidden&&nl(l,o.hidden,i)),f=l,h=new XG(l,f,i);return!u&&!d?h:lK(e,t,h,r,s,o,i,a+1)}function mOe(e,t,n,r,s){const{autoFocus:o}=e,[i,a]=N.useState(),l=hOe(t.days,n,r||(()=>!1),i),[u,d]=N.useState(o?l:void 0);return{isFocusTarget:g=>!!(l!=null&&l.isEqualTo(g)),setFocused:d,focused:u,blur:()=>{a(u),d(void 0)},moveFocus:(g,b)=>{if(!u)return;const x=lK(g,b,u,t.navStart,t.navEnd,e,s);x&&(t.goToDay(x),d(x))}}}function gOe(e,t){const{selected:n,required:r,onSelect:s}=e,[o,i]=gS(n,s?n:void 0),a=s?n:o,{isSameDay:l}=t,u=p=>(a==null?void 0:a.some(m=>l(m,p)))??!1,{min:d,max:f}=e;return{selected:a,select:(p,m,g)=>{let b=[...a??[]];if(u(p)){if((a==null?void 0:a.length)===d||r&&(a==null?void 0:a.length)===1)return;b=a==null?void 0:a.filter(x=>!l(x,p))}else(a==null?void 0:a.length)===f?b=[p]:b=[...b,p];return s||i(b),s==null||s(b,p,m,g),b},isSelected:u}}function bOe(e,t,n=0,r=0,s=!1,o=ka){const{from:i,to:a}=t||{},{isSameDay:l,isAfter:u,isBefore:d}=o;let f;if(!i&&!a)f={from:e,to:n>0?void 0:e};else if(i&&!a)l(i,e)?n===0?f={from:i,to:e}:s?f={from:i,to:void 0}:f=void 0:d(e,i)?f={from:e,to:i}:f={from:i,to:e};else if(i&&a)if(l(i,e)&&l(a,e))s?f={from:i,to:a}:f=void 0;else if(l(i,e))f={from:i,to:n>0?void 0:e};else if(l(a,e))f={from:e,to:n>0?void 0:e};else if(d(e,i))f={from:e,to:a};else if(u(e,i))f={from:i,to:e};else if(u(e,a))f={from:i,to:e};else throw new Error("Invalid range");if(f!=null&&f.from&&(f!=null&&f.to)){const h=o.differenceInCalendarDays(f.to,f.from);r>0&&h>r?f={from:e,to:void 0}:n>1&&h<n&&(f={from:e,to:void 0})}return f}function xOe(e,t,n=ka){const r=Array.isArray(t)?t:[t];let s=e.from;const o=n.differenceInCalendarDays(e.to,e.from),i=Math.min(o,6);for(let a=0;a<=i;a++){if(r.includes(s.getDay()))return!0;s=n.addDays(s,1)}return!1}function P4(e,t,n=ka){return tl(e,t.from,!1,n)||tl(e,t.to,!1,n)||tl(t,e.from,!1,n)||tl(t,e.to,!1,n)}function yOe(e,t,n=ka){const r=Array.isArray(t)?t:[t];if(r.filter(a=>typeof a!="function").some(a=>typeof a=="boolean"?a:n.isDate(a)?tl(e,a,!1,n):rK(a,n)?a.some(l=>tl(e,l,!1,n)):uR(a)?a.from&&a.to?P4(e,{from:a.from,to:a.to},n):!1:nK(a)?xOe(e,a.dayOfWeek,n):JG(a)?n.isAfter(a.before,a.after)?P4(e,{from:n.addDays(a.after,1),to:n.addDays(a.before,-1)},n):nl(e.from,a,n)||nl(e.to,a,n):eK(a)||tK(a)?nl(e.from,a,n)||nl(e.to,a,n):!1))return!0;const i=r.filter(a=>typeof a=="function");if(i.length){let a=e.from;const l=n.differenceInCalendarDays(e.to,e.from);for(let u=0;u<=l;u++){if(i.some(d=>d(a)))return!0;a=n.addDays(a,1)}}return!1}function vOe(e,t){const{disabled:n,excludeDisabled:r,selected:s,required:o,onSelect:i}=e,[a,l]=gS(s,i?s:void 0),u=i?s:a;return{selected:u,select:(h,p,m)=>{const{min:g,max:b}=e,x=h?bOe(h,u,g,b,o,t):void 0;return r&&n&&(x!=null&&x.from)&&x.to&&yOe({from:x.from,to:x.to},n,t)&&(x.from=h,x.to=void 0),i||l(x),i==null||i(x,h,p,m),x},isSelected:h=>u&&tl(u,h,!1,t)}}function wOe(e,t){const{selected:n,required:r,onSelect:s}=e,[o,i]=gS(n,s?n:void 0),a=s?n:o,{isSameDay:l}=t;return{selected:a,select:(f,h,p)=>{let m=f;return!r&&a&&a&&l(f,a)&&(m=void 0),s||i(m),s==null||s(m,f,h,p),m},isSelected:f=>a?l(a,f):!1}}function SOe(e,t){const n=wOe(e,t),r=gOe(e,t),s=vOe(e,t);switch(e.mode){case"single":return n;case"multiple":return r;case"range":return s;default:return}}function COe(e){var Ve;let t=e;t.timeZone&&(t={...e},t.today&&(t.today=new Qr(t.today,t.timeZone)),t.month&&(t.month=new Qr(t.month,t.timeZone)),t.defaultMonth&&(t.defaultMonth=new Qr(t.defaultMonth,t.timeZone)),t.startMonth&&(t.startMonth=new Qr(t.startMonth,t.timeZone)),t.endMonth&&(t.endMonth=new Qr(t.endMonth,t.timeZone)),t.mode==="single"&&t.selected?t.selected=new Qr(t.selected,t.timeZone):t.mode==="multiple"&&t.selected?t.selected=(Ve=t.selected)==null?void 0:Ve.map(Ue=>new Qr(Ue,t.timeZone)):t.mode==="range"&&t.selected&&(t.selected={from:t.selected.from?new Qr(t.selected.from,t.timeZone):void 0,to:t.selected.to?new Qr(t.selected.to,t.timeZone):void 0}));const{components:n,formatters:r,labels:s,dateLib:o,locale:i,classNames:a}=N.useMemo(()=>{const Ue={...cR,...t.locale};return{dateLib:new Cl({locale:Ue,weekStartsOn:t.broadcastCalendar?1:t.weekStartsOn,firstWeekContainsDate:t.firstWeekContainsDate,useAdditionalWeekYearTokens:t.useAdditionalWeekYearTokens,useAdditionalDayOfYearTokens:t.useAdditionalDayOfYearTokens,timeZone:t.timeZone,numerals:t.numerals},t.dateLib),components:EPe(t.components),formatters:FPe(t.formatters),labels:{...JPe,...t.labels},locale:Ue,classNames:{...dR(),...t.classNames}}},[t.locale,t.broadcastCalendar,t.weekStartsOn,t.firstWeekContainsDate,t.useAdditionalWeekYearTokens,t.useAdditionalDayOfYearTokens,t.timeZone,t.numerals,t.dateLib,t.components,t.formatters,t.labels,t.classNames]),{captionLayout:l,mode:u,navLayout:d,numberOfMonths:f=1,onDayBlur:h,onDayClick:p,onDayFocus:m,onDayKeyDown:g,onDayMouseEnter:b,onDayMouseLeave:x,onNextClick:y,onPrevClick:v,showWeekNumber:w,styles:S}=t,{formatCaption:C,formatDay:j,formatMonthDropdown:D,formatWeekNumber:k,formatWeekNumberHeader:_,formatWeekdayName:M,formatYearDropdown:R}=r,O=fOe(t,o),{days:T,months:I,navStart:F,navEnd:z,previousMonth:B,nextMonth:$,goToMonth:P}=O,V=jPe(T,t,F,z,o),{isSelected:L,select:A,selected:W}=SOe(t,o)??{},{blur:U,focused:Y,isFocusTarget:K,moveFocus:H,setFocused:q}=mOe(t,O,V,L??(()=>!1),o),{labelDayButton:X,labelGridcell:Z,labelGrid:G,labelMonthDropdown:Q,labelNav:ne,labelPrevious:ae,labelNext:ie,labelWeekday:he,labelWeekNumber:be,labelWeekNumberHeader:Ce,labelYearDropdown:Oe}=s,ue=N.useMemo(()=>zPe(o,t.ISOWeek),[o,t.ISOWeek]),De=u!==void 0||p!==void 0,Ie=N.useCallback(()=>{B&&(P(B),v==null||v(B))},[B,P,v]),ht=N.useCallback(()=>{$&&(P($),y==null||y($))},[P,$,y]),xe=N.useCallback((Ue,pt)=>He=>{He.preventDefault(),He.stopPropagation(),q(Ue),A==null||A(Ue.date,pt,He),p==null||p(Ue.date,pt,He)},[A,p,q]),se=N.useCallback((Ue,pt)=>He=>{q(Ue),m==null||m(Ue.date,pt,He)},[m,q]),de=N.useCallback((Ue,pt)=>He=>{U(),h==null||h(Ue.date,pt,He)},[U,h]),we=N.useCallback((Ue,pt)=>He=>{const Ze={ArrowLeft:[He.shiftKey?"month":"day",t.dir==="rtl"?"after":"before"],ArrowRight:[He.shiftKey?"month":"day",t.dir==="rtl"?"before":"after"],ArrowDown:[He.shiftKey?"year":"week","after"],ArrowUp:[He.shiftKey?"year":"week","before"],PageUp:[He.shiftKey?"year":"month","before"],PageDown:[He.shiftKey?"year":"month","after"],Home:["startOfWeek","before"],End:["endOfWeek","after"]};if(Ze[He.key]){He.preventDefault(),He.stopPropagation();const[ve,je]=Ze[He.key];H(ve,je)}g==null||g(Ue.date,pt,He)},[H,g,t.dir]),Se=N.useCallback((Ue,pt)=>He=>{b==null||b(Ue.date,pt,He)},[b]),Pe=N.useCallback((Ue,pt)=>He=>{x==null||x(Ue.date,pt,He)},[x]),Qe=N.useCallback(Ue=>pt=>{const He=Number(pt.target.value),Ze=o.setMonth(o.startOfMonth(Ue),He);P(Ze)},[o,P]),Nt=N.useCallback(Ue=>pt=>{const He=Number(pt.target.value),Ze=o.setYear(o.startOfMonth(Ue),He);P(Ze)},[o,P]),{className:Ke,style:Lt}=N.useMemo(()=>({className:[a[Xe.Root],t.className].filter(Boolean).join(" "),style:{...S==null?void 0:S[Xe.Root],...t.style}}),[a,t.className,t.style,S]),Ne=_Pe(t),Dt=N.useRef(null);rOe(Dt,!!t.animate,{classNames:a,months:I,focused:Y,dateLib:o});const hn={dayPickerProps:t,selected:W,select:A,isSelected:L,months:I,nextMonth:$,previousMonth:B,goToMonth:P,getModifiers:V,components:n,classNames:a,styles:S,labels:s,formatters:r};return N.createElement(QG.Provider,{value:hn},N.createElement(n.Root,{rootRef:t.animate?Dt:void 0,className:Ke,style:Lt,dir:t.dir,id:t.id,lang:t.lang,nonce:t.nonce,title:t.title,role:t.role,"aria-label":t["aria-label"],...Ne},N.createElement(n.Months,{className:a[Xe.Months],style:S==null?void 0:S[Xe.Months]},!t.hideNavigation&&!d&&N.createElement(n.Nav,{"data-animated-nav":t.animate?"true":void 0,className:a[Xe.Nav],style:S==null?void 0:S[Xe.Nav],"aria-label":ne(),onPreviousClick:Ie,onNextClick:ht,previousMonth:B,nextMonth:$}),I.map((Ue,pt)=>N.createElement(n.Month,{"data-animated-month":t.animate?"true":void 0,className:a[Xe.Month],style:S==null?void 0:S[Xe.Month],key:pt,displayIndex:pt,calendarMonth:Ue},d==="around"&&!t.hideNavigation&&pt===0&&N.createElement(n.PreviousMonthButton,{type:"button",className:a[Xe.PreviousMonthButton],tabIndex:B?void 0:-1,"aria-disabled":B?void 0:!0,"aria-label":ae(B),onClick:Ie,"data-animated-button":t.animate?"true":void 0},N.createElement(n.Chevron,{disabled:B?void 0:!0,className:a[Xe.Chevron],orientation:t.dir==="rtl"?"right":"left"})),N.createElement(n.MonthCaption,{"data-animated-caption":t.animate?"true":void 0,className:a[Xe.MonthCaption],style:S==null?void 0:S[Xe.MonthCaption],calendarMonth:Ue,displayIndex:pt},l!=null&&l.startsWith("dropdown")?N.createElement(n.DropdownNav,{className:a[Xe.Dropdowns],style:S==null?void 0:S[Xe.Dropdowns]},l==="dropdown"||l==="dropdown-months"?N.createElement(n.MonthsDropdown,{className:a[Xe.MonthsDropdown],"aria-label":Q(),classNames:a,components:n,disabled:!!t.disableNavigation,onChange:Qe(Ue.date),options:$Pe(Ue.date,F,z,r,o),style:S==null?void 0:S[Xe.Dropdown],value:o.getMonth(Ue.date)}):N.createElement("span",null,D(Ue.date,o)),l==="dropdown"||l==="dropdown-years"?N.createElement(n.YearsDropdown,{className:a[Xe.YearsDropdown],"aria-label":Oe(o.options),classNames:a,components:n,disabled:!!t.disableNavigation,onChange:Nt(Ue.date),options:BPe(F,z,r,o,!!t.reverseYears),style:S==null?void 0:S[Xe.Dropdown],value:o.getYear(Ue.date)}):N.createElement("span",null,R(Ue.date,o)),N.createElement("span",{role:"status","aria-live":"polite",style:{border:0,clip:"rect(0 0 0 0)",height:"1px",margin:"-1px",overflow:"hidden",padding:0,position:"absolute",width:"1px",whiteSpace:"nowrap",wordWrap:"normal"}},C(Ue.date,o.options,o))):N.createElement(n.CaptionLabel,{className:a[Xe.CaptionLabel],role:"status","aria-live":"polite"},C(Ue.date,o.options,o))),d==="around"&&!t.hideNavigation&&pt===f-1&&N.createElement(n.NextMonthButton,{type:"button",className:a[Xe.NextMonthButton],tabIndex:$?void 0:-1,"aria-disabled":$?void 0:!0,"aria-label":ie($),onClick:ht,"data-animated-button":t.animate?"true":void 0},N.createElement(n.Chevron,{disabled:$?void 0:!0,className:a[Xe.Chevron],orientation:t.dir==="rtl"?"left":"right"})),pt===f-1&&d==="after"&&!t.hideNavigation&&N.createElement(n.Nav,{"data-animated-nav":t.animate?"true":void 0,className:a[Xe.Nav],style:S==null?void 0:S[Xe.Nav],"aria-label":ne(),onPreviousClick:Ie,onNextClick:ht,previousMonth:B,nextMonth:$}),N.createElement(n.MonthGrid,{role:"grid","aria-multiselectable":u==="multiple"||u==="range","aria-label":G(Ue.date,o.options,o)||void 0,className:a[Xe.MonthGrid],style:S==null?void 0:S[Xe.MonthGrid]},!t.hideWeekdays&&N.createElement(n.Weekdays,{"data-animated-weekdays":t.animate?"true":void 0,className:a[Xe.Weekdays],style:S==null?void 0:S[Xe.Weekdays]},w&&N.createElement(n.WeekNumberHeader,{"aria-label":Ce(o.options),className:a[Xe.WeekNumberHeader],style:S==null?void 0:S[Xe.WeekNumberHeader],scope:"col"},_()),ue.map(He=>N.createElement(n.Weekday,{"aria-label":he(He,o.options,o),className:a[Xe.Weekday],key:String(He),style:S==null?void 0:S[Xe.Weekday],scope:"col"},M(He,o.options,o)))),N.createElement(n.Weeks,{"data-animated-weeks":t.animate?"true":void 0,className:a[Xe.Weeks],style:S==null?void 0:S[Xe.Weeks]},Ue.weeks.map(He=>N.createElement(n.Week,{className:a[Xe.Week],key:He.weekNumber,style:S==null?void 0:S[Xe.Week],week:He},w&&N.createElement(n.WeekNumber,{week:He,style:S==null?void 0:S[Xe.WeekNumber],"aria-label":be(He.weekNumber,{locale:i}),className:a[Xe.WeekNumber],scope:"row",role:"rowheader"},k(He.weekNumber,o)),He.days.map(Ze=>{const{date:ve}=Ze,je=V(Ze);if(je[qn.focused]=!je.hidden&&!!(Y!=null&&Y.isEqualTo(Ze)),je[mi.selected]=(L==null?void 0:L(ve))||je.selected,uR(W)){const{from:Xt,to:zt}=W;je[mi.range_start]=!!(Xt&&zt&&o.isSameDay(ve,Xt)),je[mi.range_end]=!!(Xt&&zt&&o.isSameDay(ve,zt)),je[mi.range_middle]=tl(W,ve,!0,o)}const Te=LPe(je,S,t.modifiersStyles),ze=kPe(je,a,t.modifiersClassNames),nt=!De&&!je.hidden?Z(ve,je,o.options,o):void 0;return N.createElement(n.Day,{key:`${o.format(ve,"yyyy-MM-dd")}_${o.format(Ze.displayMonth,"yyyy-MM")}`,day:Ze,modifiers:je,className:ze.join(" "),style:Te,role:"gridcell","aria-selected":je.selected||void 0,"aria-label":nt,"data-day":o.format(ve,"yyyy-MM-dd"),"data-month":Ze.outside?o.format(ve,"yyyy-MM"):void 0,"data-selected":je.selected||void 0,"data-disabled":je.disabled||void 0,"data-hidden":je.hidden||void 0,"data-outside":Ze.outside||void 0,"data-focused":je.focused||void 0,"data-today":je.today||void 0},!je.hidden&&De?N.createElement(n.DayButton,{className:a[Xe.DayButton],style:S==null?void 0:S[Xe.DayButton],type:"button",day:Ze,modifiers:je,disabled:je.disabled||void 0,tabIndex:K(Ze)?0:-1,"aria-label":X(ve,je,o.options,o),onClick:xe(Ze,je),onBlur:de(Ze,je),onFocus:se(Ze,je),onKeyDown:we(Ze,je),onMouseEnter:Se(Ze,je),onMouseLeave:Pe(Ze,je)},j(ve,o.options,o)):!je.hidden&&j(Ze.date,o.options,o))})))))))),t.footer&&N.createElement(n.Footer,{className:a[Xe.Footer],style:S==null?void 0:S[Xe.Footer],role:"status","aria-live":"polite"},t.footer)))}function uw({className:e,classNames:t,showOutsideDays:n=!0,captionLayout:r="label",buttonVariant:s="ghost",formatters:o,components:i,...a}){const l=dR();return c.jsx(COe,{showOutsideDays:n,className:J("bg-background group/calendar p-3 [--cell-size:2rem] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,e),captionLayout:r,formatters:{formatMonthDropdown:u=>u.toLocaleString("default",{month:"short"}),...o},classNames:{root:J("w-fit",l.root),months:J("relative flex flex-col gap-4 md:flex-row",l.months),month:J("flex w-full flex-col gap-4",l.month),nav:J("absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",l.nav),button_previous:J(Tg({variant:s}),"h-[--cell-size] w-[--cell-size] select-none p-0 aria-disabled:opacity-50",l.button_previous),button_next:J(Tg({variant:s}),"h-[--cell-size] w-[--cell-size] select-none p-0 aria-disabled:opacity-50",l.button_next),month_caption:J("flex h-[--cell-size] w-full items-center justify-center px-[--cell-size]",l.month_caption),dropdowns:J("flex h-[--cell-size] w-full items-center justify-center gap-1.5 text-sm font-medium",l.dropdowns),dropdown_root:J("has-focus:border-ring border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] relative rounded-md border",l.dropdown_root),dropdown:J("bg-popover absolute inset-0 opacity-0",l.dropdown),caption_label:J("select-none font-medium",r==="label"?"text-sm":"[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md pl-2 pr-1 text-sm [&>svg]:size-3.5",l.caption_label),table:"w-full border-collapse",weekdays:J("flex",l.weekdays),weekday:J("text-muted-foreground flex-1 select-none rounded-md text-[0.8rem] font-normal",l.weekday),week:J("mt-2 flex w-full",l.week),week_number_header:J("w-[--cell-size] select-none",l.week_number_header),week_number:J("text-muted-foreground select-none text-[0.8rem]",l.week_number),day:J("group/day relative aspect-square h-full w-full select-none p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md",l.day),range_start:J("bg-accent rounded-l-md",l.range_start),range_middle:J("rounded-none",l.range_middle),range_end:J("bg-accent rounded-r-md",l.range_end),today:J("bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",l.today),outside:J("text-muted-foreground aria-selected:text-muted-foreground",l.outside),disabled:J("text-muted-foreground opacity-50",l.disabled),hidden:J("invisible",l.hidden),...t},components:{Root:({className:u,rootRef:d,...f})=>c.jsx("div",{"data-slot":"calendar",ref:d,className:J(u),...f}),Chevron:({className:u,orientation:d,...f})=>d==="left"?c.jsx(X_,{className:J("size-4",u),...f}):d==="right"?c.jsx(Ci,{className:J("size-4",u),...f}):c.jsx(Ys,{className:J("size-4",u),...f}),DayButton:NOe,WeekNumber:({children:u,...d})=>c.jsx("td",{...d,children:c.jsx("div",{className:"flex size-[--cell-size] items-center justify-center text-center",children:u})}),...i},...a})}function NOe({className:e,day:t,modifiers:n,...r}){const s=dR(),o=E.useRef(null);return E.useEffect(()=>{var i;n.focused&&((i=o.current)==null||i.focus())},[n.focused]),c.jsx(oe,{ref:o,variant:"ghost",size:"icon","data-day":t.date.toLocaleDateString(),"data-selected-single":n.selected&&!n.range_start&&!n.range_end&&!n.range_middle,"data-range-start":n.range_start,"data-range-end":n.range_end,"data-range-middle":n.range_middle,className:J("data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 flex aspect-square h-auto w-full min-w-[--cell-size] flex-col gap-1 font-normal leading-none data-[range-end=true]:rounded-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] [&>span]:text-xs [&>span]:opacity-70",s.day,e),...r})}function jOe(e,t,n){const[r,s]=e.split(":").map(Number);switch(t){case"daily":return`${s} ${r} * * *`;case"weekly":if(n&&n.length>0){const o=n.sort().join(",");return`${s} ${r} * * ${o}`}return`${s} ${r} * * 0`;case"biweekly":return`${s} ${r} 1,15 * *`;case"monthly":return`${s} ${r} 1 * *`;default:return`${s} ${r} * * *`}}function kOe(e){if(!e)return"";if(e.includes("AM")||e.includes("PM"))return e;const t=e.split(":");if(t.length!==2)return e;const n=parseInt(t[0],10),r=parseInt(t[1],10);if(isNaN(n)||isNaN(r))return console.warn("Invalid time format:",e),e;if(n<0||n>23||r<0||r>59)return console.warn("Time out of range:",e),e;const s=n>=12?"PM":"AM";return`${n%12||12}:${r.toString().padStart(2,"0")} ${s}`}function EOe(e){if(!e||e.length===0)return"No days selected";const t=new Set(e),n=[1,2,3,4,5].every(a=>t.has(a))&&t.size===5,r=t.has(0)&&t.has(6)&&t.size===2;if(t.size===7)return"Every day";if(n)return"Weekdays";if(r)return"Weekends";const i=[...e].sort().map(a=>lR[a].label);return i.length===1?i[0]:i.length===2?`${i[0]} and ${i[1]}`:i.join(", ")}function _Oe(e){if(!e||e.length===0)return"No dates excluded";const t=e.map(n=>new Date(n).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}));return t.length===1?t[0]:t.length===2?`${t[0]} and ${t[1]}`:t.length>5?`${t.slice(0,3).join(", ")} and ${t.length-3} more`:t.join(", ")}function DOe(e,t){if(!e&&!t)return"Ongoing";const n=r=>new Date(r).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return e&&!t?`Starting ${n(e)}`:!e&&t?`Until ${n(t)}`:`${n(e)} - ${n(t)}`}function MOe(e){if(typeof e=="string"){const r=e.split(/[,;]/).filter(s=>s.trim());return`${r.length} recipient${r.length!==1?"s":""}`}const t=[];e.emails.length>0&&t.push(`${e.emails.length} email${e.emails.length!==1?"s":""}`);const n=e.tenantUserIds.length+e.orgUserIds.length;return n>0&&t.push(`${n} user${n!==1?"s":""}`),e.groupIds.length>0&&t.push(`${e.groupIds.length} group${e.groupIds.length!==1?"s":""}`),t.join(", ")||"No recipients"}function TOe({schedules:e,onDelete:t,isDeleting:n,isLoading:r=!1,onRefresh:s}){const[o,i]=N.useState(null),a=u=>{i(u)},l=()=>{o&&(t(o),i(null))};return r?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx(On,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.length===0?c.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[c.jsx(os,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),c.jsx("p",{className:"text-sm",children:"No active schedules"}),c.jsx("p",{className:"mt-1 text-xs",children:"Create a schedule to start receiving reports"})]}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx("h4",{className:"text-sm font-medium",children:"Active Schedules"}),c.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[e.length," active schedule",e.length!==1?"s":""]})]}),s&&c.jsx(oe,{variant:"ghost",size:"sm",onClick:s,className:"h-8",children:c.jsx(L8,{className:"h-3 w-3"})})]}),c.jsx(yo,{}),c.jsx("div",{className:"space-y-3",children:e.map(u=>c.jsx(ROe,{schedule:u,onDelete:()=>a(u.id),isDeleting:n===u.id},u.id))})]}),c.jsx(Wb,{open:!!o,onOpenChange:()=>i(null),children:c.jsxs(mp,{children:[c.jsxs(gp,{children:[c.jsx(xp,{children:"Delete Schedule?"}),c.jsx(yp,{children:"This will permanently delete this schedule. You will no longer receive these reports."})]}),c.jsxs(bp,{children:[c.jsx(wp,{children:"Cancel"}),c.jsx(vp,{className:"bg-destructive/90 hover:bg-destructive",onClick:l,children:"Delete Schedule"})]})]})})]})}function ROe({schedule:e,onDelete:t,isDeleting:n}){var l,u,d,f,h,p;const s=(()=>{if(typeof e.recipients=="string"){const m=e.recipients?e.recipients.split(/[,;]/).filter(Boolean):[];return{summary:`${m.length} recipient${m.length!==1?"s":""}`,details:m.length===1?m[0]:null}}else if(e.recipients)return{summary:MOe(e.recipients),details:null};return{summary:"No recipients",details:null}})(),o=e.endDate&&new Date(e.endDate)<new Date,i=new Date(e.nextRun),a=i<new Date&&!o;return c.jsx("div",{className:J("rounded-lg border bg-card p-4 transition-colors",o&&"opacity-60"),children:c.jsxs("div",{className:"flex items-start justify-between gap-3",children:[c.jsxs("div",{className:"flex-1 space-y-3",children:[c.jsx("div",{className:"flex-1",children:c.jsx("p",{className:"text-sm font-medium",children:e.subject||"Untitled"})}),typeof e.recipients=="object"&&"emails"in e.recipients?c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[c.jsx(dv,{className:"h-3 w-3"}),c.jsx("span",{className:"text-xs font-medium",children:"Recipients:"})]}),c.jsx(Yn,{children:c.jsxs("div",{className:"ml-4 flex flex-wrap gap-1",children:[e.recipients.emails.map(m=>c.jsx(Fe,{variant:"outline",className:"h-5 py-0 text-xs",children:m},m)),e.recipients.tenantUserIds.length+e.recipients.orgUserIds.length>0&&c.jsxs(bn,{delayDuration:300,children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{variant:"outline",className:"h-5 cursor-help py-0 text-xs",children:[e.recipients.tenantUserIds.length+e.recipients.orgUserIds.length," ","users"]})}),c.jsx(Cn,{className:"max-w-xs p-2",side:"top",align:"start",children:c.jsxs("div",{className:"space-y-2 text-xs",children:[((l=e.recipientDetails)==null?void 0:l.tenantUsers)&&e.recipientDetails.tenantUsers.length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"mb-1 font-medium",children:"Tenant Users:"}),c.jsx("div",{className:"ml-2 space-y-0.5",children:e.recipientDetails.tenantUsers.map(m=>c.jsxs("div",{className:"text-muted-foreground",children:[m.name," (",m.email,")"]},m.id))})]}),((u=e.recipientDetails)==null?void 0:u.orgUsers)&&e.recipientDetails.orgUsers.length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"mb-1 font-medium",children:"Organization Users:"}),c.jsx("div",{className:"ml-2 space-y-0.5",children:e.recipientDetails.orgUsers.map(m=>c.jsxs("div",{className:"text-muted-foreground",children:[m.name," (",m.email,")"]},m.id))})]}),!e.recipientDetails&&c.jsx("div",{className:"italic text-muted-foreground",children:"User details not available"})]})})]}),e.recipients.groupIds.length>0&&c.jsxs(bn,{delayDuration:300,children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{variant:"outline",className:"h-5 cursor-help py-0 text-xs",children:[e.recipients.groupIds.length," group",e.recipients.groupIds.length!==1?"s":""]})}),c.jsx(Cn,{className:"max-w-xs p-2",side:"top",align:"start",children:c.jsxs("div",{className:"space-y-1 text-xs",children:[c.jsx("div",{className:"mb-1 font-medium",children:"Groups:"}),(d=e.recipientDetails)!=null&&d.groups&&e.recipientDetails.groups.length>0?c.jsx("div",{className:"ml-2 space-y-1",children:e.recipientDetails.groups.map(m=>c.jsxs("div",{className:"space-y-0.5",children:[c.jsx("div",{className:"font-medium",children:m.name}),c.jsxs("div",{className:"text-[10px] text-muted-foreground",children:[m.type==="TENANT_GROUP"?"Tenant":"Organization"," ","Group",m.memberCount&&` • ${m.memberCount} members`]})]},m.id))}):c.jsx("div",{className:"ml-2 italic text-muted-foreground",children:"Group details not available"})]})})]})]})})]}):c.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[c.jsx(dv,{className:"h-3 w-3"}),c.jsx("span",{children:s.details||s.summary})]}),c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[c.jsx(nD,{className:"h-3 w-3"}),c.jsx("span",{children:"Attachments:"})]}),c.jsx("div",{className:"flex flex-wrap items-start gap-2",children:(f=e.reportParams)!=null&&f.attachments&&e.reportParams.attachments.length>0?e.reportParams.attachments.map((m,g)=>{var y,v;const b=(y=m.title)==null?void 0:y.includes("(All Sheets)"),x=((v=m.settings)==null?void 0:v.sheetSelection)==="all"&&!b;return c.jsxs(Fe,{variant:"outline",className:"text-xs",children:[m.type==="dashboard"?c.jsx(JA,{className:"mr-1 h-3 w-3"}):m.type==="visual"?c.jsx(Ni,{className:"mr-1 h-3 w-3"}):c.jsx(Vj,{className:"mr-1 h-3 w-3"}),m.title,x&&" (All Sheets)"]},g)}):c.jsxs(c.Fragment,{children:[(e.dashboardName||e.reportName)&&c.jsxs(Fe,{variant:"outline",className:"text-xs",children:[e.reportType==="VISUAL"?c.jsx(Ni,{className:"mr-1 h-3 w-3"}):c.jsx(JA,{className:"mr-1 h-3 w-3"}),e.dashboardName||e.reportName]}),((h=e.reportParams)==null?void 0:h.sheetSelection)==="all"&&c.jsxs(Fe,{variant:"outline",className:"text-xs",children:[c.jsx(Vj,{className:"mr-1 h-3 w-3"}),"All Sheets"]})]})})]}),c.jsxs("div",{className:"grid gap-2 text-xs",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[c.jsx(dl,{className:"h-3 w-3"}),c.jsxs("span",{children:[Zw(e.frequency),e.frequency==="weekly"&&e.weekdays&&c.jsxs(c.Fragment,{children:[" on ",EOe(e.weekdays)]})," at ",kOe(e.time)||e.time||"Time not set",e.timezone&&e.timezone!=="UTC"&&c.jsxs(c.Fragment,{children:[" ","(",(p=e.timezone.split("/").pop())==null?void 0:p.replace(/_/g," "),")"]})]})]}),(e.startDate||e.endDate)&&c.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[c.jsx(os,{className:"h-3 w-3"}),c.jsx("span",{children:DOe(e.startDate?String(e.startDate):void 0,e.endDate?String(e.endDate):void 0)})]}),e.skipDates&&e.skipDates.length>0&&c.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[c.jsx(bd,{className:"h-3 w-3"}),c.jsxs("span",{children:["Skipping: ",_Oe(e.skipDates)]})]}),c.jsxs("div",{className:J("flex items-center gap-1.5 font-medium",o?"text-muted-foreground line-through":a?"text-orange-500":"text-foreground"),children:[c.jsx(dl,{className:"h-3 w-3"}),c.jsx("span",{children:o?"Schedule expired":c.jsxs(c.Fragment,{children:["Next: ",qa(i,"MMM d, yyyy")," at"," ",qa(i,"h:mm a"),a&&" (processing)"]})})]})]})]}),c.jsx("div",{className:"flex items-center",children:n?c.jsx(On,{className:"h-4 w-4 animate-spin text-muted-foreground"}):c.jsx(oe,{variant:"ghost",size:"sm",onClick:t,className:"h-8 w-8 p-0 hover:bg-destructive/10 hover:text-destructive",children:c.jsx(Vd,{className:"h-4 w-4"})})})]})})}function IOe(e={}){const{reportType:t,dashboardId:n,visualId:r,pageSettings:s,enabled:o=!0}=e,[i,a]=N.useState(!1),[l,u]=N.useState(null),[d,f]=N.useState(null),h=ee(R=>R.authToken),{tokenProps:p}=qe(),m=ee(R=>{var O;return(O=R.dashboard)==null?void 0:O.id}),g=ee(R=>{var O;return(O=R.dashboard)==null?void 0:O.title});ee(R=>R.theme);const b=ee(R=>R.dashboard.filters),x=ee(R=>R.filterValues),y=ee(R=>R.selectedSheetId),v=Qc(b,y),w=x==null?void 0:x.filter(R=>(v==null?void 0:v.some(O=>O.id===R.filterId))||R.filterId.endsWith(y)),S=n||m;Ms();const{data:C=[],isLoading:j,isError:D,refetch:k}=un({queryKey:["schedules","with-details"],queryFn:async()=>{const R=`${p.apiServiceUrl}/v1/schedules`;return await Vn(R,(h==null?void 0:h.accessToken)||"",{includeRecipientDetails:"true"})},enabled:!!(h!=null&&h.accessToken)&&!!(p!=null&&p.apiServiceUrl)&&o,staleTime:5*60*1e3,gcTime:10*60*1e3}),_=N.useCallback(async R=>{a(!0),u(null);try{const O=jOe(R.time,R.frequency,R.weekdays),{authToken:T,...I}=t==="DASHBOARD"?jT():{},F=Rq(w||[]),z={recipients:R.recipients,recipientsString:void 0,subject:R.subject||g||"Scheduled Report",message:R.message,frequency:R.frequency,time:R.time,timezone:R.timezone,dashboardId:S,weekdays:R.weekdays,skipDates:R.skipDates,startDate:R.startDate,endDate:R.endDate,reportParams:R.reportParams||{}};t&&(t==="DASHBOARD"?(z.reportParams||(z.reportParams={}),z.dashboardParams={...I,filterLine:F}):t==="VISUAL"&&r&&(z.reportParams={attachments:[{type:"visual",visualId:r,title:R.subject||"Visual Report",format:"pdf",settings:{...s,filterLine:F}}]}));const B=`${p.apiServiceUrl}/v1/schedules`,$=await gl(B,(h==null?void 0:h.accessToken)||"",z);return $e.success("Schedule created successfully!",{description:`Reports will be sent ${R.frequency} at ${R.time}`}),await k(),a(!1),$}catch(O){console.error("Failed to create schedule:",O);const T=O instanceof Error?O.message:"Failed to create schedule";throw u(T),a(!1),$e.error("Failed to create schedule",{description:T}),O}},[t,S,r,s,h,p.apiServiceUrl,g,w,k]),M=N.useCallback(async R=>{f(R);try{const O=`${p.apiServiceUrl}/v1/schedules`;if(!(await fetch(`${O}/${R}`,{method:"DELETE",headers:{Authorization:`Bearer ${(h==null?void 0:h.accessToken)||""}`,"Content-Type":"application/json"}})).ok)throw new Error("Failed to delete schedule");$e.success("Schedule deleted successfully"),await k(),f(null)}catch(O){throw console.error("Failed to delete schedule:",O),f(null),$e.error("Failed to delete schedule",{description:O instanceof Error?O.message:"Please try again"}),O}},[h,k,p.apiServiceUrl]);return{schedules:C,isLoading:j,isError:D,createSchedule:_,deleteSchedule:M,refetch:k,isSubmitting:i,submitError:l,deletingId:d}}const O4=`Hello,
|
|
966
966
|
|
|
967
967
|
Your scheduled email is ready. The attachments you requested are included for your review.`;function cK({open:e,onOpenChange:t,dashboardId:n,dashboardName:r="Dashboard",preSelectedVisual:s}){const[o,i]=N.useState("create"),[a,l]=N.useState({emails:[],tenantUserIds:[],orgUserIds:[],groupIds:[]}),[u,d]=N.useState(`${r} Report`),[f,h]=N.useState(O4),[p,m]=N.useState(s?[s]:[]),[g,b]=N.useState(!1),[x,y]=N.useState(!1),{currentUser:v}=Ms(),w=ee(ie=>ie.dashboard),S=N.useMemo(()=>(w==null?void 0:w.sheets)||[],[w==null?void 0:w.sheets]),C=ee(ie=>ie.selectedSheetId),j=S.find(ie=>ie.id===C),[D,k]=N.useState("daily"),[_,M]=N.useState("09:00"),[R,O]=N.useState(Intl.DateTimeFormat().resolvedOptions().timeZone),[T,I]=N.useState([1,2,3,4,5]),[F,z]=N.useState(new Date),[B,$]=N.useState(),{schedules:P,isLoading:V,createSchedule:L,deleteSchedule:A,isSubmitting:W,deletingId:U,refetch:Y}=IOe({enabled:e});N.useEffect(()=>{if(e&&!x){if(v){const ie={emails:[],tenantUserIds:[],orgUserIds:[],groupIds:[]};v.type==="tenant"&&v.id?ie.tenantUserIds=[v.id]:v.type==="organization"&&v.id&&(ie.orgUserIds=[v.id]),l(ie)}if(s)m([s]);else if(w&&j){const ie={type:"dashboard",title:S.length>1?`${w.title} (${j.title})`:`${w.title} (All Sheets)`,format:"pdf",settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0,sheetSelection:S.length>1?"current":"all",currentSheetId:S.length>1?j.id:void 0,currentSheetName:S.length>1?j.title:void 0}};m([ie])}else if(w){const ie={type:"dashboard",title:`${w.title} (All Sheets)`,format:"pdf",settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0,sheetSelection:"all"}};m([ie])}y(!0)}},[e,v,w,j,S,x,s]),N.useEffect(()=>{e||y(!1)},[e]);const K=ie=>{m(ie),b(!1)},H=ie=>{m(p.filter((he,be)=>be!==ie))},q=(ie,he)=>{const be=[...p];be[ie]=he,m(be)},X=()=>{l({emails:[],tenantUserIds:[],orgUserIds:[],groupIds:[]}),d(`${r} Report`),h(O4),m([]),k("daily"),M("09:00"),O(Intl.DateTimeFormat().resolvedOptions().timeZone),I([1,2,3,4,5]),z(new Date),$(void 0)},Z=async()=>{try{await L({recipients:a,subject:u,message:f,frequency:D,time:_,timezone:R,weekdays:D==="weekly"?T:void 0,startDate:qa(F,"yyyy-MM-dd"),endDate:B?qa(B,"yyyy-MM-dd"):void 0,reportParams:{attachments:p.map(ie=>({type:ie.type,visualId:ie.visualId,cardType:ie.cardType,title:ie.title,format:ie.format,settings:ie.settings}))}}),X(),i("active"),Y()}catch(ie){console.error("Failed to create schedule:",ie)}},G=async ie=>{try{await A(ie)}catch(he){console.error("Failed to delete schedule:",he)}},ne=(a.emails.length>0||a.tenantUserIds.length>0||a.orgUserIds.length>0||a.groupIds.length>0)&&u&&p.length>0,ae=ie=>{ie||y(!1),t(ie)};return c.jsxs(c.Fragment,{children:[c.jsx(ls,{open:e,onOpenChange:ae,children:c.jsxs(Vr,{className:"max-h-[90vh] max-w-2xl",children:[c.jsxs(Hr,{children:[c.jsx(Ur,{children:"Schedule Export"}),c.jsx(Rs,{className:"sr-only",children:"Create and manage scheduled exports for your dashboard"})]}),c.jsxs(cs,{value:o,onValueChange:ie=>i(ie),className:"w-full",children:[c.jsxs(Wr,{className:"grid w-full grid-cols-2",children:[c.jsxs(Ht,{value:"create",className:"flex items-center gap-2",children:[c.jsx(kr,{className:"h-4 w-4"}),"Create Schedule"]}),c.jsxs(Ht,{value:"active",className:"flex items-center gap-2",children:[c.jsx(A8,{className:"h-4 w-4"}),"Active Schedules",P&&P.length>0&&c.jsx(Fe,{variant:"secondary",className:"ml-1 h-5 px-1",children:P.length})]})]}),c.jsxs(Gn,{value:"create",className:"mt-4 max-h-[calc(80vh-200px)] space-y-4 overflow-y-auto",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{children:"Recipients"}),c.jsx(oIe,{value:a,onChange:l})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{htmlFor:"subject",children:"Subject"}),c.jsx(Nn,{id:"subject",value:u,onChange:ie=>d(ie.target.value),placeholder:"Enter email subject"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{htmlFor:"message",children:"Message"}),c.jsx(Kd,{className:"ring-inset focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",id:"message",value:f,onChange:ie=>h(ie.target.value),placeholder:"Enter email message",rows:4})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(ce,{children:"Attachments"}),c.jsxs(oe,{variant:"secondary",size:"sm",onClick:()=>b(!0),children:[c.jsx(nD,{className:"mr-2 h-4 w-4"}),"Select attachments"]})]}),p.length>0?c.jsx(xIe,{attachments:p,onRemove:H,onUpdate:q}):c.jsx("div",{className:"rounded-lg border-2 border-dashed p-4 text-center text-sm text-muted-foreground",children:"No attachments selected"})]}),c.jsx(yo,{}),c.jsx("div",{className:"space-y-4",children:c.jsxs("div",{className:"space-y-4",children:[c.jsx(ce,{className:"text-base font-medium",children:"Schedule Settings"}),c.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{htmlFor:"date",className:"text-xs text-muted-foreground",children:"First occurrence"}),c.jsxs(Ns,{modal:!0,children:[c.jsx(js,{asChild:!0,children:c.jsxs(oe,{variant:"outline",className:J("w-full justify-start text-left font-normal",!F&&"text-muted-foreground"),children:[c.jsx(os,{className:"mr-2 h-4 w-4 shrink-0"}),F?qa(F,"PPP"):"Pick a date"]})}),c.jsx(ks,{className:"z-[51] w-auto p-0",align:"start",children:c.jsx(uw,{mode:"single",selected:F,onSelect:ie=>ie&&z(ie),disabled:ie=>ie<new Date(new Date().setHours(0,0,0,0)),initialFocus:!0})})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{htmlFor:"time",className:"text-xs text-muted-foreground",children:"Time"}),c.jsx(vIe,{value:_,onChange:M})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{htmlFor:"timezone",className:"text-xs text-muted-foreground",children:"Timezone"}),c.jsx(yIe,{value:R,onChange:O})]})]})]})}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{htmlFor:"frequency",children:"Repeats:"}),c.jsxs(rt,{value:D,onValueChange:ie=>k(ie),children:[c.jsx(Je,{children:c.jsx(lt,{})}),c.jsxs(et,{children:[c.jsx(pe,{className:"hover:bg-muted",value:"daily",children:"Daily"}),c.jsx(pe,{className:"hover:bg-muted",value:"weekly",children:"Weekly"}),c.jsx(pe,{className:"hover:bg-muted",value:"biweekly",children:"Biweekly"}),c.jsx(pe,{className:"hover:bg-muted",value:"monthly",children:"Monthly"})]})]})]}),D==="weekly"&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{children:"On days:"}),c.jsx(wIe,{value:T,onChange:I})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(fae,{className:"h-4 w-4 text-muted-foreground"}),c.jsx(ce,{className:"text-xs text-muted-foreground",htmlFor:"end-date",children:"End date (optional):"})]}),c.jsxs(Ns,{modal:!0,children:[c.jsx(js,{asChild:!0,children:c.jsxs(oe,{variant:"outline",className:J("w-full justify-start text-left font-normal",!B&&"text-muted-foreground"),children:[c.jsx(os,{className:"mr-2 h-4 w-4"}),B?qa(B,"PPP"):"No end date"]})}),c.jsx(ks,{className:"z-[51] w-auto p-0",align:"start",children:c.jsx(uw,{mode:"single",selected:B,onSelect:$,disabled:ie=>ie<=F,initialFocus:!0})})]})]})]}),c.jsx(Gn,{value:"active",className:"mt-4 max-h-[calc(80vh-200px)] overflow-y-auto",children:P&&P.length>0?c.jsx(TOe,{schedules:P,onDelete:G,isDeleting:U,isLoading:V,onRefresh:Y}):c.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[c.jsx(dl,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),c.jsx("p",{className:"text-sm font-medium",children:"No active schedules"}),c.jsx("p",{className:"mt-1 text-xs",children:'Switch to the "Create Schedule" tab to add your first schedule'})]})})]}),o==="create"&&c.jsxs(Ts,{children:[c.jsx(oe,{variant:"outline",onClick:()=>ae(!1),disabled:W,children:"Cancel"}),c.jsx(oe,{onClick:Z,disabled:!ne||W,children:W?c.jsx(c.Fragment,{children:"Scheduling..."}):c.jsxs(c.Fragment,{children:[c.jsx(z8,{className:"mr-2 h-4 w-4"}),"Schedule"]})})]})]})}),g&&c.jsx(gIe,{open:g,onOpenChange:b,dashboardId:n,onSelect:K,existingAttachments:p})]})}function uK({frame:e,isHovered:t,isExpandedViewOpen:n=!1,onExpandClick:r}){const{tokenProps:s}=qe(),[o,i]=N.useState(!1),{openPopover:a}=CT(),[l,u]=N.useState(!1),[d,f]=N.useState(!1),[h,p]=N.useState(!1),[m,g]=N.useState(""),[b,x]=N.useState(!1),[y,v]=N.useState(!1),w=r?n:y,S=r||(()=>v(!0)),C=N.useRef(null),j=N.useRef(null),D=ee(Q=>Q.isDashboardEditing),k=ee(Q=>Q.isDownloadingPdf),_=ee(Q=>Q.selectedSheetId),M=ee(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.id}),R=ee(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.title}),{removeFrame:O,addFrame:T,setSelectedFrameId:I}=ee(Q=>Q.actions),F=e.cards.find(Q=>Q.id===e.activeCardId),{handleEditVisual:z,card:B,data:$}=gke(e),{cardFilterValues:P}=k1((B==null?void 0:B.id)||""),{permissions:V}=jq();N.useEffect(()=>()=>{j.current&&clearTimeout(j.current)},[]);const L=()=>{j.current&&clearTimeout(j.current),i(!0)},A=()=>{j.current=setTimeout(()=>{i(!1)},300)},W=()=>{i(!1),j.current&&clearTimeout(j.current)},U=async()=>{if(!m)return;u(!1),g(""),x(!1);const Q=$e.loading("Generating protected PDF report... may take up to 60 seconds");try{await Mq(s.apiServiceUrl,e.activeCardId||"",e.id,(B==null?void 0:B.title)||"visual",B==null?void 0:B.type,m,void 0,void 0,void 0,P),$e.dismiss(Q),$e.success("Protected visual PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(ne){$e.dismiss(Q),$e.error("Failed to download protected visual PDF. Please try again."),console.error("Protected visual PDF download error:",ne)}},Y=()=>{if(_)try{const Q=JSON.parse(JSON.stringify(e)),ne=oR(Q),ae=ne.cards.findIndex(ie=>ie.id===ne.activeCardId);ae!==-1&&(ne.cards[ae].title=`${ne.cards[ae].title} (Copy)`),T(_,ne),I(ne.id),$e.success("Card duplicated successfully")}catch(Q){console.error("Failed to duplicate frame:",Q),$e.error("Failed to duplicate card")}},K=()=>{const{authToken:Q,theme:ne,dashboardTitle:ae,selectedSheetId:ie,dashboardId:he}=jT(),be=new URLSearchParams;be.set("token",(Q==null?void 0:Q.accessToken)||""),be.set("theme",ne||"light"),be.set("filterValues",JSON.stringify(P||[])),be.set("dashboardTitle",ae||""),be.set("selectedSheetId",ie||""),be.set("dashboardId",he||"");const Ce=e.activeCardId,Oe=`https://semaphor.cloud/view/dashboard/${he}/visual/${Ce}?${be.toString()}`;window.open(Oe,"_blank")},H=(B==null?void 0:B.type)==="kpi",q=(B==null?void 0:B.type)==="text",X={editVisual:{visible:D&&V.canEdit},duplicateFrame:{visible:D&&V.canEdit},expand:{visible:!H&&!q},export:{visible:!H&&!q},deleteCard:{visible:D&&V.canEdit},moreOptions:{visible:!H&&!q,submenu:{interactions:{visible:D&&V.canEdit&&!!(F!=null&&F.config)&&!H&&!q},schedule:{visible:!H&&!q&&!D}}}},Z=X.editVisual.visible||X.duplicateFrame.visible||X.expand.visible||X.export.visible||X.deleteCard.visible||X.moreOptions.visible,G=t&&!w&&Z;return c.jsxs(c.Fragment,{children:[G&&c.jsx("div",{ref:C,className:"absolute right-2 top-2 z-50 duration-200 animate-in fade-in-0 zoom-in-95",onMouseLeave:W,children:c.jsx(xo,{className:"min-w-[32px] border-border bg-popover p-0.5 shadow-lg",children:c.jsxs("div",{className:"flex flex-row gap-0.5",children:[X.moreOptions.visible&&c.jsxs("div",{className:"relative",children:[c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-accent hover:text-accent-foreground",onMouseEnter:L,onMouseLeave:A,onClick:Q=>Q.stopPropagation(),title:"More Options",children:c.jsx(rp,{className:"h-3.5 w-3.5"})}),o&&c.jsx("div",{className:"z-60 absolute right-full top-0 mr-0.5 duration-150 animate-in fade-in-0 zoom-in-95",onMouseEnter:L,onMouseLeave:A,children:c.jsx(xo,{className:"min-w-[140px] border-border bg-popover p-0.5 shadow-lg",children:c.jsxs("div",{className:"flex flex-col gap-0.5",children:[X.moreOptions.submenu.interactions.visible&&c.jsxs(oe,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:Q=>{Q.stopPropagation(),I(e.id);const ne=e.activeCardId;ne&&a(e.id,ne,Q.currentTarget),i(!1)},children:[c.jsx(sp,{className:"mr-1.5 h-3.5 w-3.5"}),c.jsx("span",{className:"text-xs",children:"Interactions"})]}),X.export.visible&&c.jsxs(oe,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:Q=>{Q.stopPropagation(),f(!0),i(!1)},children:[c.jsx(n1,{className:"mr-1.5 h-3.5 w-3.5"}),c.jsx("span",{className:"text-xs",children:"Download"})]}),c.jsxs(oe,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:Q=>{Q.stopPropagation(),K()},children:[c.jsx(uv,{className:"mr-1.5 h-3.5 w-3.5"}),c.jsx("span",{className:"text-xs",children:"Open in New Window"})]}),X.moreOptions.submenu.schedule.visible&&c.jsxs(oe,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:Q=>{Q.stopPropagation(),p(!0),i(!1)},children:[c.jsx(dl,{className:"mr-1.5 h-3.5 w-3.5"}),c.jsx("span",{className:"text-xs",children:"Schedule Export"})]})]})})})]}),X.deleteCard.visible&&c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-destructive hover:text-destructive-foreground",onClick:Q=>{Q.stopPropagation(),O(_,e.id)},disabled:!1,title:"Delete Card",children:c.jsx(Vd,{className:"h-3.5 w-3.5"})}),X.duplicateFrame.visible&&c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:Q=>{Q.stopPropagation(),Y()},disabled:!1,title:"Duplicate Card",children:c.jsx(j8,{className:"h-3.5 w-3.5"})}),X.expand.visible&&c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:Q=>{Q.stopPropagation(),S(),i(!1)},disabled:!1,title:"Expand View",children:c.jsx(i1,{className:"h-3.5 w-3.5"})}),X.editVisual.visible&&c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-primary hover:text-primary-foreground",onClick:Q=>{Q.stopPropagation(),z()},disabled:!1,title:"Edit Visual",children:c.jsx(rD,{className:"h-3.5 w-3.5"})})]})})}),c.jsx(ls,{open:l,onOpenChange:u,children:c.jsxs(Vr,{className:"sm:max-w-[425px]",children:[c.jsxs(Hr,{children:[c.jsx(Ur,{children:"Download Protected Visual PDF"}),c.jsx(Rs,{children:"Enter a password to protect your visual PDF. The PDF will be encrypted and require this password to open."})]}),c.jsx("div",{className:"grid gap-4 py-4",children:c.jsxs("div",{className:"grid gap-2",children:[c.jsx(ce,{htmlFor:"password",children:"Password"}),c.jsxs("div",{className:"relative",children:[c.jsx(Nn,{id:"password",type:b?"text":"password",value:m,onChange:Q=>g(Q.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:Q=>{Q.key==="Enter"&&m&&U()}}),c.jsx(oe,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>x(!b),children:b?c.jsx(r1,{className:"h-4 w-4 text-muted-foreground"}):c.jsx(yc,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),c.jsxs(Ts,{children:[c.jsx(oe,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),c.jsx(oe,{onClick:U,disabled:!m||k,children:"Download"})]})]})}),!r&&y&&c.jsx(LRe,{isOpen:y,onClose:()=>v(!1),frame:e,card:B,data:$}),c.jsx(Wq,{isOpen:d,onClose:()=>f(!1),frame:e,card:B,data:$}),c.jsx(cK,{open:h,onOpenChange:p,dashboardId:M||"",dashboardName:R,preSelectedVisual:B?{visualId:B.id,cardType:B.type,title:B.title||"Visual",type:"visual",format:DT(B.type),supportedFormats:_T(B.type),settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0}}:void 0})]})}function tb({children:e,containerClassName:t,className:n,text:r,onSave:s,type:o="input",placeholder:i,enabled:a}){const[l,u]=N.useState(!1),[d,f]=N.useState(r),h=ee(x=>x.isDashboardEditing);N.useEffect(()=>{f(x=>x!==r?r:x)},[r]);const p=x=>{x.stopPropagation(),h&&u(!0)};function m(x){if(x.stopPropagation(),x.key==="Escape"){u(!1);return}x.key==="Enter"&&x.shiftKey||(x.key==="Enter"||x.key==="Tab")&&(u(!1),s(d))}function g(){return o==="textarea"?c.jsx("textarea",{className:J("resize rounded-sm bg-background px-2 py-1 text-sm outline-[0.5px] outline-muted",n),onChange:x=>f(x.target.value),value:d,autoFocus:!0,placeholder:i,onBlur:()=>u(!1),onKeyDown:m}):c.jsx("input",{onMouseDown:x=>x.stopPropagation(),type:"text",className:J("rounded-sm bg-background outline-none",n),onChange:x=>f(x.target.value),value:d,autoFocus:!0,placeholder:i,onBlur:()=>u(!1),onKeyDown:m})}function b(){return a?c.jsxs("div",{className:"flex grow items-center gap-2",children:[c.jsx("div",{children:l?g():e}),!l&&c.jsx(rD,{onClick:()=>u(!0),className:"hidden size-3 cursor-pointer text-muted-foreground group-hover/editable:block"})]}):e}return c.jsx("div",{className:J("flex",t),role:"editable",onDoubleClick:p,onMouseDown:x=>x.stopPropagation(),children:c.jsx("div",{className:"group/editable flex grow items-center gap-2",children:b()})})}function bS(e){const{authToken:t}=qe(),n=ase(t==null?void 0:t.accessToken);function r(){var o,i,a,l,u,d;if((i=(o=e.preferences)==null?void 0:o.formatNumber)!=null&&i.currency&&((l=(a=e.preferences)==null?void 0:a.formatNumber)==null?void 0:l.currency)!=="none")return n!=null&&n.currency?n==null?void 0:n.currency:(d=(u=e.preferences)==null?void 0:u.formatNumber)==null?void 0:d.currency}function s(){var o,i,a,l,u,d;return(i=(o=e.preferences)==null?void 0:o.formatNumber)!=null&&i.locale&&((l=(a=e.preferences)==null?void 0:a.formatNumber)==null?void 0:l.locale)!=="none"?n!=null&&n.locale?n==null?void 0:n.locale:(d=(u=e.preferences)==null?void 0:u.formatNumber)==null?void 0:d.locale:navigator.language||"en-US"}return{getCurrency:r,getLocale:s}}var AOe="Toggle",dK=E.forwardRef((e,t)=>{const{pressed:n,defaultPressed:r=!1,onPressedChange:s,...o}=e,[i=!1,a]=$r({prop:n,onChange:s,defaultProp:r});return c.jsx(Be.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...o,ref:t,onClick:Ee(e.onClick,()=>{e.disabled||a(!i)})})});dK.displayName=AOe;var fK=dK;const POe=Ob("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),px=E.forwardRef(({className:e,variant:t,size:n,...r},s)=>c.jsx(fK,{ref:s,className:J(POe({variant:t,size:n,className:e})),...r}));px.displayName=fK.displayName;function fR({children:e,className:t,...n}){return c.jsx(B9,{children:c.jsx(wa,{children:c.jsx(Cn,{...n,className:t,children:e})})})}const OOe={"currentPeriod.start":{icon:c.jsx(Lj,{className:"h-3 w-3 text-blue-500"}),label:"Current Start"},"currentPeriod.end":{icon:c.jsx(Lj,{className:"h-3 w-3 text-blue-500"}),label:"Current End"},"comparisonPeriod.start":{icon:c.jsx(os,{className:"h-3 w-3 text-gray-500"}),label:"Previous Start"},"comparisonPeriod.end":{icon:c.jsx(os,{className:"h-3 w-3 text-gray-500"}),label:"Previous End"},trendlineGranularity:{icon:c.jsx(g8,{className:"h-3 w-3 text-green-500"}),label:"Data Period"},trendlineWindow:{icon:c.jsx(dl,{className:"h-3 w-3 text-purple-500"}),label:"Time Range"}},FOe=(e,t,n)=>e>t?c.jsx(Oo,{className:`h-3 w-3 ${n?"text-green-500":"text-red-500"}`}):e<t?c.jsx(Qi,{className:`h-3 w-3 ${n?"text-green-500":"text-red-500"}`}):c.jsx(Oo,{className:"h-3 w-3 text-gray-500"}),$Oe=(e,t)=>e>t?c.jsx(Qi,{className:"h-3 w-3 text-gray-500"}):e<t?c.jsx(Oo,{className:"h-3 w-3 text-gray-500"}):c.jsx(Oo,{className:"h-3 w-3 text-gray-500"}),LOe=(e,t,n)=>e>t?c.jsx(kh,{className:`h-3 w-3 ${n?"text-green-500":"text-red-500"}`}):e<t?c.jsx(cD,{className:`h-3 w-3 ${n?"text-green-500":"text-red-500"}`}):c.jsx(kh,{className:"h-3 w-3 text-gray-500"}),zOe=(e,t)=>e.filter(n=>n.segment==="meta"||n.Segment==="meta").filter(n=>{const r=n.key??n.Key;return!(!t&&(r==="trendlineGranularity"||r==="trendlineWindow"))});function g2({label:e,value:t,icon:n,formatCurrency:r}){return c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[n,c.jsxs("span",{children:[e,":"]})]}),c.jsx("span",{className:"font-mono",children:r(t)})]})}function BOe({metaKey:e,value:t}){const n=OOe[e];return n?c.jsxs("div",{className:"flex items-center justify-between gap-4",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[n.icon,c.jsxs("span",{children:[n.label,":"]})]}),c.jsx("span",{className:"font-mono",children:t})]}):c.jsxs("div",{className:"flex items-center justify-between gap-4",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(xr,{className:"h-3 w-3"}),c.jsxs("span",{children:[e,":"]})]}),c.jsx("span",{className:"font-mono",children:t})]})}function VOe({currentValue:e,comparisonValue:t,isPositive:n,formatCurrency:r}){return c.jsxs("div",{className:"space-y-1",children:[c.jsx(g2,{label:"Current",value:e,icon:FOe(e,t,n),formatCurrency:r}),c.jsx(g2,{label:"Previous",value:t,icon:$Oe(e,t),formatCurrency:r}),c.jsx(g2,{label:"Change",value:e-t,icon:LOe(e,t,n),formatCurrency:r})]})}function HOe({data:e,showTrendline:t}){const n=zOe(e,t);return n.length===0?null:c.jsxs("div",{className:"border-t pt-2",children:[c.jsxs("div",{className:"mb-2 flex items-center gap-1 font-semibold",children:[c.jsx(os,{className:"h-3 w-3"}),"Period Details"]}),c.jsx("div",{className:"space-y-1",children:n.map((r,s)=>c.jsx(BOe,{metaKey:r.key??r.Key,value:r.value??r.Value},s))})]})}function UOe({currentValue:e,comparisonValue:t,isPositive:n,data:r,formatCurrency:s,showTrendline:o=!1,conditionalLabel:i}){return c.jsx(fR,{side:"right",className:"max-w-fit",children:c.jsxs("div",{className:"space-y-2 text-xs",children:[c.jsxs("div",{className:"flex items-center gap-1 font-semibold",children:[c.jsx(g8,{className:"h-3 w-3"}),"Key Metrics"]}),i&&c.jsx("div",{className:`flex items-center gap-1 text-sm font-medium ${n?"text-green-600 dark:text-green-400":"text-red-600 dark:text-red-400"}`,children:i}),c.jsx(VOe,{currentValue:e,comparisonValue:t,isPositive:n,formatCurrency:s}),c.jsx(HOe,{data:r,showTrendline:o})]})})}const WOe=[{id:"us",name:"United States",flag:"🇺🇸",code:"US",region:"North America"},{id:"ca",name:"Canada",flag:"🇨🇦",code:"CA",region:"North America"},{id:"mx",name:"Mexico",flag:"🇲🇽",code:"MX",region:"North America"},{id:"gb",name:"United Kingdom",flag:"🇬🇧",code:"GB",region:"Europe"},{id:"de",name:"Germany",flag:"🇩🇪",code:"DE",region:"Europe"},{id:"fr",name:"France",flag:"🇫🇷",code:"FR",region:"Europe"},{id:"it",name:"Italy",flag:"🇮🇹",code:"IT",region:"Europe"},{id:"es",name:"Spain",flag:"🇪🇸",code:"ES",region:"Europe"},{id:"nl",name:"Netherlands",flag:"🇳🇱",code:"NL",region:"Europe"},{id:"be",name:"Belgium",flag:"🇧🇪",code:"BE",region:"Europe"},{id:"ch",name:"Switzerland",flag:"🇨🇭",code:"CH",region:"Europe"},{id:"at",name:"Austria",flag:"🇦🇹",code:"AT",region:"Europe"},{id:"se",name:"Sweden",flag:"🇸🇪",code:"SE",region:"Europe"},{id:"no",name:"Norway",flag:"🇳🇴",code:"NO",region:"Europe"},{id:"dk",name:"Denmark",flag:"🇩🇰",code:"DK",region:"Europe"},{id:"fi",name:"Finland",flag:"🇫🇮",code:"FI",region:"Europe"},{id:"pl",name:"Poland",flag:"🇵🇱",code:"PL",region:"Europe"},{id:"cz",name:"Czech Republic",flag:"🇨🇿",code:"CZ",region:"Europe"},{id:"hu",name:"Hungary",flag:"🇭🇺",code:"HU",region:"Europe"},{id:"pt",name:"Portugal",flag:"🇵🇹",code:"PT",region:"Europe"},{id:"ie",name:"Ireland",flag:"🇮🇪",code:"IE",region:"Europe"},{id:"gr",name:"Greece",flag:"🇬🇷",code:"GR",region:"Europe"},{id:"jp",name:"Japan",flag:"🇯🇵",code:"JP",region:"Asia"},{id:"cn",name:"China",flag:"🇨🇳",code:"CN",region:"Asia"},{id:"in",name:"India",flag:"🇮🇳",code:"IN",region:"Asia"},{id:"kr",name:"South Korea",flag:"🇰🇷",code:"KR",region:"Asia"},{id:"sg",name:"Singapore",flag:"🇸🇬",code:"SG",region:"Asia"},{id:"hk",name:"Hong Kong",flag:"🇭🇰",code:"HK",region:"Asia"},{id:"tw",name:"Taiwan",flag:"🇹🇼",code:"TW",region:"Asia"},{id:"th",name:"Thailand",flag:"🇹🇭",code:"TH",region:"Asia"},{id:"my",name:"Malaysia",flag:"🇲🇾",code:"MY",region:"Asia"},{id:"id",name:"Indonesia",flag:"🇮🇩",code:"ID",region:"Asia"},{id:"ph",name:"Philippines",flag:"🇵🇭",code:"PH",region:"Asia"},{id:"vn",name:"Vietnam",flag:"🇻🇳",code:"VN",region:"Asia"},{id:"ae",name:"United Arab Emirates",flag:"🇦🇪",code:"AE",region:"Asia"},{id:"sa",name:"Saudi Arabia",flag:"🇸🇦",code:"SA",region:"Asia"},{id:"il",name:"Israel",flag:"🇮🇱",code:"IL",region:"Asia"},{id:"tr",name:"Turkey",flag:"🇹🇷",code:"TR",region:"Asia"},{id:"au",name:"Australia",flag:"🇦🇺",code:"AU",region:"Oceania"},{id:"nz",name:"New Zealand",flag:"🇳🇿",code:"NZ",region:"Oceania"},{id:"br",name:"Brazil",flag:"🇧🇷",code:"BR",region:"South America"},{id:"ar",name:"Argentina",flag:"🇦🇷",code:"AR",region:"South America"},{id:"cl",name:"Chile",flag:"🇨🇱",code:"CL",region:"South America"},{id:"co",name:"Colombia",flag:"🇨🇴",code:"CO",region:"South America"},{id:"pe",name:"Peru",flag:"🇵🇪",code:"PE",region:"South America"},{id:"uy",name:"Uruguay",flag:"🇺🇾",code:"UY",region:"South America"},{id:"ec",name:"Ecuador",flag:"🇪🇨",code:"EC",region:"South America"},{id:"ve",name:"Venezuela",flag:"🇻🇪",code:"VE",region:"South America"},{id:"za",name:"South Africa",flag:"🇿🇦",code:"ZA",region:"Africa"},{id:"ng",name:"Nigeria",flag:"🇳🇬",code:"NG",region:"Africa"},{id:"eg",name:"Egypt",flag:"🇪🇬",code:"EG",region:"Africa"},{id:"ma",name:"Morocco",flag:"🇲🇦",code:"MA",region:"Africa"},{id:"ke",name:"Kenya",flag:"🇰🇪",code:"KE",region:"Africa"},{id:"gh",name:"Ghana",flag:"🇬🇭",code:"GH",region:"Africa"},{id:"et",name:"Ethiopia",flag:"🇪🇹",code:"ET",region:"Africa"},{id:"tz",name:"Tanzania",flag:"🇹🇿",code:"TZ",region:"Africa"},{id:"ru",name:"Russia",flag:"🇷🇺",code:"RU",region:"Europe/Asia"},{id:"ua",name:"Ukraine",flag:"🇺🇦",code:"UA",region:"Europe"},{id:"by",name:"Belarus",flag:"🇧🇾",code:"BY",region:"Europe"},{id:"lt",name:"Lithuania",flag:"🇱🇹",code:"LT",region:"Europe"},{id:"lv",name:"Latvia",flag:"🇱🇻",code:"LV",region:"Europe"},{id:"ee",name:"Estonia",flag:"🇪🇪",code:"EE",region:"Europe"},{id:"ro",name:"Romania",flag:"🇷🇴",code:"RO",region:"Europe"},{id:"bg",name:"Bulgaria",flag:"🇧🇬",code:"BG",region:"Europe"},{id:"hr",name:"Croatia",flag:"🇭🇷",code:"HR",region:"Europe"},{id:"si",name:"Slovenia",flag:"🇸🇮",code:"SI",region:"Europe"},{id:"sk",name:"Slovakia",flag:"🇸🇰",code:"SK",region:"Europe"},{id:"rs",name:"Serbia",flag:"🇷🇸",code:"RS",region:"Europe"},{id:"ba",name:"Bosnia and Herzegovina",flag:"🇧🇦",code:"BA",region:"Europe"},{id:"me",name:"Montenegro",flag:"🇲🇪",code:"ME",region:"Europe"},{id:"mk",name:"North Macedonia",flag:"🇲🇰",code:"MK",region:"Europe"},{id:"al",name:"Albania",flag:"🇦🇱",code:"AL",region:"Europe"},{id:"xk",name:"Kosovo",flag:"🇽🇰",code:"XK",region:"Europe"},{id:"md",name:"Moldova",flag:"🇲🇩",code:"MD",region:"Europe"},{id:"is",name:"Iceland",flag:"🇮🇸",code:"IS",region:"Europe"},{id:"lu",name:"Luxembourg",flag:"🇱🇺",code:"LU",region:"Europe"},{id:"mt",name:"Malta",flag:"🇲🇹",code:"MT",region:"Europe"},{id:"cy",name:"Cyprus",flag:"🇨🇾",code:"CY",region:"Europe"},{id:"mc",name:"Monaco",flag:"🇲🇨",code:"MC",region:"Europe"},{id:"ad",name:"Andorra",flag:"🇦🇩",code:"AD",region:"Europe"},{id:"sm",name:"San Marino",flag:"🇸🇲",code:"SM",region:"Europe"},{id:"va",name:"Vatican City",flag:"🇻🇦",code:"VA",region:"Europe"},{id:"li",name:"Liechtenstein",flag:"🇱🇮",code:"LI",region:"Europe"},{id:"pk",name:"Pakistan",flag:"🇵🇰",code:"PK",region:"Asia"},{id:"bd",name:"Bangladesh",flag:"🇧🇩",code:"BD",region:"Asia"},{id:"lk",name:"Sri Lanka",flag:"🇱🇰",code:"LK",region:"Asia"},{id:"np",name:"Nepal",flag:"🇳🇵",code:"NP",region:"Asia"},{id:"bt",name:"Bhutan",flag:"🇧🇹",code:"BT",region:"Asia"},{id:"mv",name:"Maldives",flag:"🇲🇻",code:"MV",region:"Asia"},{id:"af",name:"Afghanistan",flag:"🇦🇫",code:"AF",region:"Asia"},{id:"ir",name:"Iran",flag:"🇮🇷",code:"IR",region:"Asia"},{id:"iq",name:"Iraq",flag:"🇮🇶",code:"IQ",region:"Asia"},{id:"sy",name:"Syria",flag:"🇸🇾",code:"SY",region:"Asia"},{id:"lb",name:"Lebanon",flag:"🇱🇧",code:"LB",region:"Asia"},{id:"jo",name:"Jordan",flag:"🇯🇴",code:"JO",region:"Asia"},{id:"kw",name:"Kuwait",flag:"🇰🇼",code:"KW",region:"Asia"},{id:"qa",name:"Qatar",flag:"🇶🇦",code:"QA",region:"Asia"},{id:"bh",name:"Bahrain",flag:"🇧🇭",code:"BH",region:"Asia"},{id:"om",name:"Oman",flag:"🇴🇲",code:"OM",region:"Asia"},{id:"ye",name:"Yemen",flag:"🇾🇪",code:"YE",region:"Asia"},{id:"ge",name:"Georgia",flag:"🇬🇪",code:"GE",region:"Asia"},{id:"am",name:"Armenia",flag:"🇦🇲",code:"AM",region:"Asia"},{id:"az",name:"Azerbaijan",flag:"🇦🇿",code:"AZ",region:"Asia"},{id:"kz",name:"Kazakhstan",flag:"🇰🇿",code:"KZ",region:"Asia"},{id:"kg",name:"Kyrgyzstan",flag:"🇰🇬",code:"KG",region:"Asia"},{id:"tj",name:"Tajikistan",flag:"🇹🇯",code:"TJ",region:"Asia"},{id:"tm",name:"Turkmenistan",flag:"🇹🇲",code:"TM",region:"Asia"},{id:"uz",name:"Uzbekistan",flag:"🇺🇿",code:"UZ",region:"Asia"},{id:"mn",name:"Mongolia",flag:"🇲🇳",code:"MN",region:"Asia"},{id:"kp",name:"North Korea",flag:"🇰🇵",code:"KP",region:"Asia"},{id:"mm",name:"Myanmar",flag:"🇲🇲",code:"MM",region:"Asia"},{id:"la",name:"Laos",flag:"🇱🇦",code:"LA",region:"Asia"},{id:"kh",name:"Cambodia",flag:"🇰🇭",code:"KH",region:"Asia"},{id:"bn",name:"Brunei",flag:"🇧🇳",code:"BN",region:"Asia"},{id:"tl",name:"East Timor",flag:"🇹🇱",code:"TL",region:"Asia"},{id:"dz",name:"Algeria",flag:"🇩🇿",code:"DZ",region:"Africa"},{id:"tn",name:"Tunisia",flag:"🇹🇳",code:"TN",region:"Africa"},{id:"ly",name:"Libya",flag:"🇱🇾",code:"LY",region:"Africa"},{id:"sd",name:"Sudan",flag:"🇸🇩",code:"SD",region:"Africa"},{id:"ss",name:"South Sudan",flag:"🇸🇸",code:"SS",region:"Africa"},{id:"td",name:"Chad",flag:"🇹🇩",code:"TD",region:"Africa"},{id:"ne",name:"Niger",flag:"🇳🇪",code:"NE",region:"Africa"},{id:"ml",name:"Mali",flag:"🇲🇱",code:"ML",region:"Africa"},{id:"bf",name:"Burkina Faso",flag:"🇧🇫",code:"BF",region:"Africa"},{id:"sn",name:"Senegal",flag:"🇸🇳",code:"SN",region:"Africa"},{id:"gm",name:"Gambia",flag:"🇬🇲",code:"GM",region:"Africa"},{id:"gw",name:"Guinea-Bissau",flag:"🇬🇼",code:"GW",region:"Africa"},{id:"gn",name:"Guinea",flag:"🇬🇳",code:"GN",region:"Africa"},{id:"sl",name:"Sierra Leone",flag:"🇸🇱",code:"SL",region:"Africa"},{id:"lr",name:"Liberia",flag:"🇱🇷",code:"LR",region:"Africa"},{id:"ci",name:"Ivory Coast",flag:"🇨🇮",code:"CI",region:"Africa"},{id:"tg",name:"Togo",flag:"🇹🇬",code:"TG",region:"Africa"},{id:"bj",name:"Benin",flag:"🇧🇯",code:"BJ",region:"Africa"},{id:"zw",name:"Zimbabwe",flag:"🇿🇼",code:"ZW",region:"Africa"},{id:"zm",name:"Zambia",flag:"🇿🇲",code:"ZM",region:"Africa"}];function Id(){return Id=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Id.apply(null,arguments)}function qOe(e,t=[]){let n=[];function r(o,i){const a=N.createContext(i),l=n.length;n=[...n,i];function u(f){const{scope:h,children:p,...m}=f,g=(h==null?void 0:h[e][l])||a,b=N.useMemo(()=>m,Object.values(m));return N.createElement(g.Provider,{value:b},p)}function d(f,h){const p=(h==null?void 0:h[e][l])||a,m=N.useContext(p);if(m)return m;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${o}\``)}return u.displayName=o+"Provider",[u,d]}const s=()=>{const o=n.map(i=>N.createContext(i));return function(a){const l=(a==null?void 0:a[e])||o;return N.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return s.scopeName=e,[r,YOe(s,...t)]}function YOe(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(o){const i=r.reduce((a,{useScope:l,scopeName:u})=>{const f=l(o)[`__scope${u}`];return{...a,...f}},{});return N.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function GOe(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function KOe(...e){return t=>e.forEach(n=>GOe(n,t))}const hK=N.forwardRef((e,t)=>{const{children:n,...r}=e,s=N.Children.toArray(n),o=s.find(XOe);if(o){const i=o.props.children,a=s.map(l=>l===o?N.Children.count(i)>1?N.Children.only(null):N.isValidElement(i)?i.props.children:null:l);return N.createElement(CE,Id({},r,{ref:t}),N.isValidElement(i)?N.cloneElement(i,void 0,a):null)}return N.createElement(CE,Id({},r,{ref:t}),n)});hK.displayName="Slot";const CE=N.forwardRef((e,t)=>{const{children:n,...r}=e;return N.isValidElement(n)?N.cloneElement(n,{...QOe(r,n.props),ref:t?KOe(t,n.ref):n.ref}):N.Children.count(n)>1?N.Children.only(null):null});CE.displayName="SlotClone";const ZOe=({children:e})=>N.createElement(N.Fragment,null,e);function XOe(e){return N.isValidElement(e)&&e.type===ZOe}function QOe(e,t){const n={...t};for(const r in t){const s=e[r],o=t[r];/^on[A-Z]/.test(r)?s&&o?n[r]=(...a)=>{o(...a),s(...a)}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}const JOe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],pK=JOe.reduce((e,t)=>{const n=N.forwardRef((r,s)=>{const{asChild:o,...i}=r,a=o?hK:t;return N.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),N.createElement(a,Id({},i,{ref:s}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{}),mK="Progress",xS=100,[eFe]=qOe(mK),[tFe,nFe]=eFe(mK),gK=N.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:s,getValueLabel:o=oFe,...i}=e,a=NE(s)?s:xS,l=xK(r,a)?r:null,u=dw(l)?o(l,a):void 0;return N.createElement(tFe,{scope:n,value:l,max:a},N.createElement(pK.div,Id({"aria-valuemax":a,"aria-valuemin":0,"aria-valuenow":dw(l)?l:void 0,"aria-valuetext":u,role:"progressbar","data-state":bK(l,a),"data-value":l??void 0,"data-max":a},i,{ref:t})))});gK.propTypes={max(e,t,n){const r=e[t],s=String(r);return r&&!NE(r)?new Error(iFe(s,n)):null},value(e,t,n){const r=e[t],s=String(r),o=NE(e.max)?e.max:xS;return r!=null&&!xK(r,o)?new Error(aFe(s,n)):null}};const rFe="ProgressIndicator",sFe=N.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...s}=e,o=nFe(rFe,r);return N.createElement(pK.div,Id({"data-state":bK(o.value,o.max),"data-value":(n=o.value)!==null&&n!==void 0?n:void 0,"data-max":o.max},s,{ref:t}))});function oFe(e,t){return`${Math.round(e/t*100)}%`}function bK(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function dw(e){return typeof e=="number"}function NE(e){return dw(e)&&!isNaN(e)&&e>0}function xK(e,t){return dw(e)&&!isNaN(e)&&e<=t&&e>=0}function iFe(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${xS}\`.`}function aFe(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be:
|
|
@@ -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 NXe=bZe(()=>qJ(Ar([Wn({type:ut("text-start"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("text-delta"),id:Le(),delta:Le(),providerMetadata:ir.optional()}),Wn({type:ut("text-end"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("error"),errorText:Le()}),Wn({type:ut("tool-input-start"),toolCallId:Le(),toolName:Le(),providerExecuted:Sr().optional(),dynamic:Sr().optional()}),Wn({type:ut("tool-input-delta"),toolCallId:Le(),inputTextDelta:Le()}),Wn({type:ut("tool-input-available"),toolCallId:Le(),toolName:Le(),input:co(),providerExecuted:Sr().optional(),providerMetadata:ir.optional(),dynamic:Sr().optional()}),Wn({type:ut("tool-input-error"),toolCallId:Le(),toolName:Le(),input:co(),providerExecuted:Sr().optional(),providerMetadata:ir.optional(),dynamic:Sr().optional(),errorText:Le()}),Wn({type:ut("tool-output-available"),toolCallId:Le(),output:co(),providerExecuted:Sr().optional(),dynamic:Sr().optional(),preliminary:Sr().optional()}),Wn({type:ut("tool-output-error"),toolCallId:Le(),errorText:Le(),providerExecuted:Sr().optional(),dynamic:Sr().optional()}),Wn({type:ut("reasoning-start"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-delta"),id:Le(),delta:Le(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-end"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("source-url"),sourceId:Le(),url:Le(),title:Le().optional(),providerMetadata:ir.optional()}),Wn({type:ut("source-document"),sourceId:Le(),mediaType:Le(),title:Le(),filename:Le().optional(),providerMetadata:ir.optional()}),Wn({type:ut("file"),url:Le(),mediaType:Le(),providerMetadata:ir.optional()}),Wn({type:BJ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:Le().optional(),data:co(),transient:Sr().optional()}),Wn({type:ut("start-step")}),Wn({type:ut("finish-step")}),Wn({type:ut("start"),messageId:Le().optional(),messageMetadata:co().optional()}),Wn({type:ut("finish"),messageMetadata:co().optional()}),Wn({type:ut("abort")}),Wn({type:ut("message-metadata"),messageMetadata:co()})])));function jXe(e){return e.type.startsWith("data-")}function eee(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]=eee(o,s):n[r]=s}return n}function kXe(e){const t=["ROOT"];let n=-1,r=null;function s(l,u,d){switch(l){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":s(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function tee(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ow({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ow({text:kXe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Uy(e){return e.type.startsWith("tool-")}function EXe(e){return e.type==="dynamic-tool"}function c_(e){return Uy(e)||EXe(e)}function wL(e){return e.type.split("-").slice(1).join("-")}function _Xe({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 DXe({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(Uy).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=>Uy(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?eee(u.message.metadata,w):w;t!=null&&await gL({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(Uy);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 tee(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:wL(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:wL(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(jXe(a)){(n==null?void 0:n[a.type])!=null&&await gL({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 MXe({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()}}Ox({prefix:"aitxt",size:24});Ox({prefix:"aiobj",size:24});var TXe=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()})}};Ox({prefix:"aiobj",size:24});var RXe={};pXe(RXe,{object:()=>AXe,text:()=>IXe});var IXe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),AXe=({schema:e})=>{const t=fXe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await tee(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 Ow({text:n});if(!s.success)throw new yL({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 _I({value:s.value,schema:t});if(!o.success)throw new yL({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}}},PXe=Uf({name:Le(),version:Le()}),MI=Uf({_meta:mr(Wt({}).loose())}),wb=MI,OXe=Wt({method:Le(),params:mr(MI)}),FXe=Uf({experimental:mr(Wt({}).loose()),logging:mr(Wt({}).loose()),prompts:mr(Uf({listChanged:mr(Sr())})),resources:mr(Uf({subscribe:mr(Sr()),listChanged:mr(Sr())})),tools:mr(Uf({listChanged:mr(Sr())}))});wb.extend({protocolVersion:Le(),capabilities:FXe,serverInfo:PXe,instructions:mr(Le())});var $Xe=wb.extend({nextCursor:mr(Le())}),LXe=Wt({name:Le(),description:mr(Le()),inputSchema:Wt({type:ut("object"),properties:mr(Wt({}).loose())}).loose()}).loose();$Xe.extend({tools:su(LXe)});var zXe=Wt({type:ut("text"),text:Le()}).loose(),BXe=Wt({type:ut("image"),data:PJ(),mimeType:Le()}).loose(),nee=Wt({uri:Le(),mimeType:mr(Le())}).loose(),VXe=nee.extend({text:Le()}),HXe=nee.extend({blob:PJ()}),UXe=Wt({type:ut("resource"),resource:Ar([VXe,HXe])}).loose();wb.extend({content:su(Ar([zXe,BXe,UXe])),isError:Sr().default(!1).optional()}).or(wb.extend({toolResult:co()}));var nC="2.0",WXe=Wt({jsonrpc:ut(nC),id:Ar([Le(),yb().int()])}).merge(OXe).strict(),qXe=Wt({jsonrpc:ut(nC),id:Ar([Le(),yb().int()]),result:wb}).strict(),YXe=Wt({jsonrpc:ut(nC),id:Ar([Le(),yb().int()]),error:Wt({code:yb().int(),message:Le(),data:mr(co())})}).strict(),GXe=Wt({jsonrpc:ut(nC)}).merge(Wt({method:Le(),params:mr(MI)})).strict();Ar([WXe,GXe,qXe,YXe]);async function KXe(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 ZXe=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 Ef(this.body),l=await Ef(this.headers),u=await Ef(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:mL({"Content-Type":"application/json",...h},`ai-sdk/${vL}`,pL()),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 Ef(this.body),a=await Ef(this.headers),l=await Ef(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:mL(f,`ai-sdk/${vL}`,pL()),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)}},TI=class extends ZXe{constructor(e={}){super(e)}processResponseStream(e){return vZe({stream:e,schema:NXe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},XXe=class{constructor({generateId:e=lZe,id:t=e(),transport:n=new TI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new TXe,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 KXe(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=>c_(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=>c_(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:_Xe({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 MXe({stream:DXe({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 QXe({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(c_);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function JXe(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 eQe=JXe;const tQe=zc(eQe);var ree=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Tn=(e,t,n)=>(ree(e,t,"read from private field"),n?n.call(e):t.get(e)),zi=(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)},Fl=(e,t,n,r)=>(ree(e,t,"write to private field"),t.set(e,n),n);function nQe(e,t){return t!=null?tQe(e,t):e}var jo,Wy,qy,Wm,qm,Ym,If,u_,d_,rQe=class{constructor(e=[]){zi(this,jo,void 0),zi(this,Wy,"ready"),zi(this,qy,void 0),zi(this,Wm,new Set),zi(this,qm,new Set),zi(this,Ym,new Set),this.pushMessage=t=>{Fl(this,jo,Tn(this,jo).concat(t)),Tn(this,If).call(this)},this.popMessage=()=>{Fl(this,jo,Tn(this,jo).slice(0,-1)),Tn(this,If).call(this)},this.replaceMessage=(t,n)=>{Fl(this,jo,[...Tn(this,jo).slice(0,t),this.snapshot(n),...Tn(this,jo).slice(t+1)]),Tn(this,If).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?nQe(t,n):t;return Tn(this,Wm).add(r),()=>{Tn(this,Wm).delete(r)}},this["~registerStatusCallback"]=t=>(Tn(this,qm).add(t),()=>{Tn(this,qm).delete(t)}),this["~registerErrorCallback"]=t=>(Tn(this,Ym).add(t),()=>{Tn(this,Ym).delete(t)}),zi(this,If,()=>{Tn(this,Wm).forEach(t=>t())}),zi(this,u_,()=>{Tn(this,qm).forEach(t=>t())}),zi(this,d_,()=>{Tn(this,Ym).forEach(t=>t())}),Fl(this,jo,e)}get status(){return Tn(this,Wy)}set status(e){Fl(this,Wy,e),Tn(this,u_).call(this)}get error(){return Tn(this,qy)}set error(e){Fl(this,qy,e),Tn(this,d_).call(this)}get messages(){return Tn(this,jo)}set messages(e){Fl(this,jo,[...e]),Tn(this,If).call(this)}};jo=new WeakMap;Wy=new WeakMap;qy=new WeakMap;Wm=new WeakMap;qm=new WeakMap;Ym=new WeakMap;If=new WeakMap;u_=new WeakMap;d_=new WeakMap;var Af,SL=class extends XXe{constructor({messages:e,...t}){const n=new rQe(e);super({...t,state:n}),zi(this,Af,void 0),this["~registerMessagesCallback"]=(r,s)=>Tn(this,Af)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Tn(this,Af)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Tn(this,Af)["~registerErrorCallback"](r),Fl(this,Af,n)}};Af=new WeakMap;function see({experimental_throttle:e,resume:t=!1,...n}={}){const r=N.useRef("chat"in n?n.chat:new SL(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new SL(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 sQe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function oQe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function iQe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function aQe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function oee(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:aQe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function iee(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 lQe(){var b;const{authToken:e,tokenProps:t}=qe(),n=ee(x=>x.dashboard.aiScopeTables),r=(b=Qw().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=see({transport:new TI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Ai.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:IW(x)}})}),onToolCall:p,sendAutomaticallyWhen:QXe,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:oee(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=iee(d);return{sendMessage:s,regenerate:a,isLoading:m,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function aee(){var u;const{authToken:e,tokenProps:t}=qe(),n=(u=Qw().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 lee({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(C8,{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 Fw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(aD,{className:r});case"view":return c.jsx(yc,{className:r});case"materialized view":return c.jsx(bae,{className:r});case"model":return c.jsx(o1,{className:r});case"file":return c.jsx(Ni,{className:r});case"dataset":return c.jsx(sl,{className:r});case"upload":return c.jsx(dD,{className:r});case"url":return c.jsx(I8,{className:r});default:return c.jsx(s1,{className:r})}}const cee=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})]}));cee.displayName=ds.Input.displayName;const my=e=>e.label||(e==null?void 0:e.name),CL=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function cQe({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=my(C).toLowerCase(),D=CL(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(my(b[0]))},[b,m]);const x=()=>{if(!m)return;const C=b.find(j=>my(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(PS,{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(cee,{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(kr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick: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(OS,{className:"min-h-60",children:[c.jsx(FS,{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(kr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx($S,{children:b.map((C,j)=>{const D=v(C),k="id"in C?C.id:`${C.connectionId}-${C.name}`,_=my(C);return c.jsxs(LS,{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:Fw(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:CL(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 f_=e=>e.name||e.name,uQe=e=>{const t=f_(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 dQe({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:[Fw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:f_(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:uQe(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(xae,{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:Fw(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:f_(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 uee(e){return e.type==="dataset"&&e.label||e.name}function fQe(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 hQe({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,"]"]}),uee(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 pQe(e){const{tokenProps:t}=qe(),n=ee(l=>l.authToken)||e;ke(l=>l.selectedConnectionId),ke(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=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 mQe(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 gQe(e){var g,b;const{tokenProps:t}=qe(),n=ee(x=>x.authToken)||e,{connections:r}=Ii(e),s=ke(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:p}=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 bQe(e){var g;const{tokenProps:t}=qe(),n=ee(b=>b.authToken)||e,{connections:r}=Ii(e),s=ke(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=ke(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:p}=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 dee(e){const{tokenProps:t}=qe(),n=ee(h=>h.authToken)||e,{connections:r}=Ii(e),s=ke(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=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 xQe(){var S,C,j;const e=ke(D=>D.card.dataSource);ke(D=>D.actions.updateDirectSource);const t=ke(D=>D.actions.updateDataSource),[n,r]=N.useState(""),{selectedConnection:s,error:o}=Ii(),{databases:i,isPending:a,error:l,label:u}=gQe(),{schemas:d,isPending:f,error:h,label:p}=bQe(),{error:m}=dee(),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 yQe(){const e=ke(l=>l.card.dataSource),t=ke(l=>l.actions.updateDataSource),[n,r]=N.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(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(dD,{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 vQe(){const e=ke(f=>f.card.dataSource),t=ke(f=>f.actions.updateDataSource),[n,r]=N.useState(""),[s,o]=N.useState(""),[i,a]=N.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(p=>p.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(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(kr,{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(s1,{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 wQe(e,t){var y,v;const{tokenProps:n}=qe(),r=ee(w=>w.authToken)||t,{connections:s}=Ii(t),o=ke(w=>{var S,C;return(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.connectionId}),i=ke(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.database}),a=ke(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:p,isLoading:m,error:g,refetch:b}=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 $w({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(bd,{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 SQe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Ii(),[i,a]=N.useState(""),[l,u]=N.useState(""),[d,f]=N.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=ur(),{entities:m,isLoading:g,error:b}=wQe("table"),{dataModels:x,isPending:y,error:v}=dee(),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(yQe,{}),e.connectionType==="url"&&c.jsx(vQe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(xQe,{}),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($w,{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($w,{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 CQe({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}=pQe(),m=o?f.filter(C=>s.includes(C.id)):f,{datasets:g,isPending:b,error:x}=mQe(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($w,{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($w,{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 RI({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(CQe,{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(SQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:k})]})}),c.jsx(hQe,{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 NQe({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){$e.error(`You can only attach ${$a} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=YQ(l);if(f.forEach(({file:h,error:p})=>{$e.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>yI(p)));e(h)}catch(h){console.error("Failed to process files:",h),$e.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(nD,{className:"h-4 w-4 text-muted-foreground"})})]})}function jQe({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){$e.error(`You can only attach ${$a} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=YQ(h);if(g.forEach(({file:b,error:x})=>{$e.error(`${b.name}: ${x}`)}),m.length>0)try{const b=await Promise.all(m.map(x=>yI(x)));t(b),$e.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),$e.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(dD,{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 II=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=Op();DNe(),_Ne();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:S}=W1(),{queueMessage:C}=Fp(),{addFileAttachment:j,removeFileAttachment:D,clearFileAttachments:k,getFileAttachments:_}=XM(),M=ZM(l),R=ke(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=LWe(H.nativeEvent);q.length>0&&(H.preventDefault(),q.forEach(async X=>{const Z=await yI(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(jQe,{onFilesDropped:$,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(dQe,{entities:x.selectedEntities,availableEntities:T||[],onRemoveEntity:U,onRemoveEntities:Y}),M.length>0&&c.jsx(zWe,{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(dae,{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(cQe,{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(NQe,{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(_ae,{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(z8,{className:"size-4"})})]})]})]}),c.jsx(RI,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:p,dataSource:R||JS,dialogMode:"aiContext"})]})});II.displayName="ChatInputWithContext";function fee({assistantType:e,className:t}){const n=AW(e),{removeFromQueue:r}=Fp();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 hee({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=AW(e),{dequeueMessage:o}=Fp();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 pee(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 mee(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 gee(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:GQ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const kQe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function EQe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=N.useState(!1),[a,l]=N.useState(Yw),[u,d]=N.useState(!1),[f,h]=N.useState(!1),[p,m]=N.useState(!1),g=n??p,{isLocalDev:b,isConsoleMode:x}=pp(),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=Op(),{setCurrentAIContext:k,updateSelectedEntities:_,setReasoningEffort:M,setShowReasoning:R}=W1(),{clearQueue:O}=Fp(),{clearFileAttachments:T,getFileAttachments:I}=XM(),F=ZM("dashboard"),z=ee(Ve=>Ve.dashboard.aiContext),B=ke(Ve=>Ve.card.dataSource),{assistantProfile:$}=aee(),P=ee(Ve=>Ve.handleOpenAssistantProfile),{sendMessage:V,isLoading:L,messages:A,setMessages:W,status:U,stop:Y,errorMessage:K,clearError:H}=lQe(),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:pt,connectionId:He,cardType:Ze,python:ve,cardConfig:je,dataSource:Te}){if(console.log("handleAddNewFrame",{sql:Ve,data:Ue,cardTitle:pt,connectionId:He,cardType:Ze,python:ve,cardConfig:je,dataSource:Te}),!v)return;const ze={id:jr(),title:pt||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ze==="horizontalBar"?"y":"x"}},type:Ze,sql:Ve,python:ve,dataSource:Te,config:je,connectionId:He},nt={id:jr(),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 pt=[];Ue&&pt.push({type:"text",text:Ue}),F.forEach(He=>{He.data&&pt.push({type:"file",mediaType:He.type,filename:He.name,url:`data:${He.type};base64,${He.data}`})}),V({role:"user",parts:pt}),G(""),T("dashboard"),se({force:!0})};N.useEffect(()=>{var Ve;e&&((Ve=y.current)==null||Ve.focus())},[e]),hee({assistantType:"dashboard",status:U,isLoading:L,sendMessage:V});const{hasActiveTools:ie}=gee(A),{visibleMessages:he,hasMoreMessages:be,totalMessageCount:Ce,loadMoreMessages:Oe,resetMessageWindow:ue}=mee(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:De,isAtBottom:Ie,hasNewMessages:ht,newMessageCount:xe,scrollToBottom:se,handleScroll:de,resetNewMessageCount:we}=pee(he,{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),$e.success("Conversation copied")}catch(Ue){console.error("Failed to copy conversation",Ue),$e.error("Unable to copy conversation")}},[A]);function Ke(){D.selectedEntities.length===0&&k({selectedEntities:(z==null?void 0:z.selectedEntities)||[]})}const Lt=(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(fp,{children:[c.jsx(hp,{asChild:!0,children:c.jsx(lc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(rp,{className:"size-3.5"})})}),c.jsxs(Yd,{align:"end",children:[c.jsx(Qf,{children:"Options"}),c.jsx(vd,{}),c.jsx(Zm,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Zm,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Zm,{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(lc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:X,children:g?c.jsx(tD,{className:"size-4"}):c.jsx(i1,{className:"size-4"})}),c.jsx(lc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),O("dashboard"),H(),ue()},children:c.jsx(a1,{className:"size-4"})}),c.jsx(lc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(vt,{className:"size-4"})})]})]}),c.jsxs(vl,{"data-role":"dashboard-assistant-scroll-area",ref:De,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:de,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[be&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:Oe,className:"text-xs",children:["Load ",Math.min(5,Ce-he.length)," ","more messages (",Ce-he.length," ","hidden)"]})}),c.jsx(ZQ,{showTools:a,showSystemMessage:u,messages:he,onAddToDashboard:ne,onQuickReply:Qe,disableQuickReplies:L}),!ie&&c.jsx(KQ,{status:U,errorMessage:K})]}),c.jsx(Zo,{orientation:"horizontal"})]}),e&&!Ie&&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"}),ht&&xe>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:xe>9?"9+":xe})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&Lt&&c.jsx(XQ,{onClick:Se,placeholders:kQe}),c.jsx("div",{children:Lt&&$&&c.jsx(lee,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Pe})}),c.jsx(fee,{assistantType:"dashboard",className:"mb-3"}),c.jsx(II,{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(RI,{incomingSelectedEntities:(z==null?void 0:z.selectedEntities)||[],open:f,onOpenChange:h,dataSource:B||JS,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 _Qe(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(),$e.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=oR(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),$e.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 DQe(e,t){switch(e.interactionMode){case"drillToDetail":MQe(e,t);break;case"drillThrough":TQe(e,t);break;case"drillToURL":RQe(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 MQe(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 TQe(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 RQe(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 IQe({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(cZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(dZ,{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 AQe(){const e=It(w=>w.interactionStates),t=It(w=>w.setInteractionState),n=It(w=>w.clearLastInteractionEvent),r=It(w=>w.replaceCardWithInsight),s=It(w=>w.setPendingDrillThrough),o=It(w=>w.pendingDrillThrough),i=It(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Yt(),{selectDashboard:u}=Ab(),d=ee(w=>w.dashboard),f=ee(w=>w.filterValues),{data:h,isLoading:p}=Ufe((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[m,g]=N.useState({open:!1,insightId:""}),b=fZ(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:na,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...Ao(),appliedClickFilters:[_],contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:D};t(na,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{DQe(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(IQe,{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 PQe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=OQe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function OQe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function FQe(e){return e?`Back to ${e}`:"Back"}function $Qe(){var x,y,v,w,S;const e=It(C=>C.interactionStates[na]),t=ee(C=>C.actions.goBackFromDrill),n=ee(C=>C.actions.clearDrillContext),{selectDashboard:r}=Ab(),[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})};PQe(f);const b=FQe(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(c8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function bee(){var G;const{showAssistant:e,tokenProps:t}=qe(),{preferences:n,isConsoleMode:r}=pp(),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=od(Q=>Q.setFullscreen),d=od(Q=>Q.setPanelOpen),f=od(Q=>Q.setContainer),h=MW("dashboard"),p=TW(),m=RW("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}=H6(C),[R,O]=N.useState(null);S1(Pt.DASHBOARD);const{setSelectedSheetId:T,setSheetTitle:I,addSheet:F,setSheets:z}=Yt();_Qe(i);const{setActiveAssistantType:B}=W1();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:jr(),title:"New Sheet"};F(Q),T(Q.id)}function V(Q,ne){if(!C)return;R===Q?(M(),O(null),$e.success("Default sheet cleared")):(_(Q),O(Q),$e.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||[]),[he]=ie.splice(parseInt(ae),1);ie.splice(ne,0,he),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(w8,{className:"h-4 w-4"}):c.jsx(S8,{className:"h-4 w-4"})}),v==null?void 0:v.map((ae,ie)=>{const he=S===ae.id,be=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(tb,{enabled:w&&he,text:ae.title,onSave:Ce=>I(ae.id,Ce),children:ae.title},ae.id),!w&&he&&c.jsx("div",{title:be?"Clear default sheet":"Set as default sheet",children:c.jsx(iD,{className:J("ml-1 size-3 cursor-pointer transition-all",be?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:Ce=>{Ce.stopPropagation(),V(ae.id,ae.title||"Sheet")}})}),w&&he&&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(kr,{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(e8e,{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(vl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:q()}),c.jsx(I8e,{open:a,setOpen:l})]})}const Z=N.useCallback(Q=>{f("dashboard",Q)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(AQe,{}),c.jsx($Qe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(RX,{className:J("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(HE,{children:X()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(R8e,{open:g,onTabClick:$,withHandle:!0}),c.jsx(HE,{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(EQe,{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(oD,{className:"h-5 w-5"})})})]})]}):null}function AI({children:e}){return c.jsx(wa,{style:{height:"100%",width:"100%"},children:c.jsx(hse,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(Yn,{delayDuration:0,children:e})})})}function xee({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(I9.Provider,{value:r,children:c.jsx(kR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function yee(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(Sl,{FallbackComponent:hS,children:c.jsx(H_,{dashboardProps:e,children:c.jsx(AI,{children:c.jsx(xee,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(QM,{...e,type:"dashboard",children:c.jsx(bee,{})})})})})})})}function PI(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 vee(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 wee(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 See=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=PI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=ur(),h=ke(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:lU(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){$e.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=JSe(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&&oU();return}const z=nCe(T,I,h);if(!z){$e.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const B=vee(T,z,h);if(!B.isValid){$e.error("Invalid Field Type",{description:B.reason,position:"top-center",duration:3e3});return}const $=m(z);if(iU(T,$))return;const P=cU(T,z,$);if(P){const L=[...$,P];g(z,L),z==="metrics"&&wee(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 Fx(e,t){var Pe,Qe,Nt,Ke,Lt;const{tokenProps:n}=qe(),r=Zs(),s=qe().authToken||e,o=ke(Ne=>Ne.selectedConnectionId),i=ke(Ne=>Ne.card),{queryKey:a}=Ype(i),l=ke(Ne=>Ne.selectedDatamodelId),u=ke(Ne=>Ne.isDevMode),d=ke(Ne=>Ne.selectedDatabaseName),f=ke(Ne=>Ne.selectedSchemaName),h=ke(Ne=>Ne.selectedTableName),p=ke(Ne=>Ne.actions.setSelectedConnectionId),m=ke(Ne=>Ne.actions.setSelectedDatamodelId),g=ke(Ne=>Ne.actions.setSelectedDatabaseName),b=ke(Ne=>Ne.actions.setSelectedSchemaName),x=ke(Ne=>Ne.actions.setSelectedTableName);ke(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}=Ii(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}=uU(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||"",he=I?"":f||"";function be(Ne){x(Ne),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Ce(Ne){b(Ne),x("")}function Oe(Ne){g(Ne==="none"?"":Ne),b(""),x(""),Ne!=="none"&&Ne!==""&&m("")}function ue(Ne){p(Ne)}function De(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 Ie=C==null?void 0:C.connections.map(Ne=>({id:Ne.id,name:Ne.name,type:Ne.type})),ht=(Ke=M==null?void 0:M.datamodels)==null?void 0:Ke.map(Ne=>({id:Ne.id,name:Ne.name})),xe=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})),de=Y==null?void 0:Y.tables.map(Ne=>({id:Ne.table_name,name:Ne.table_name})),we=(Lt=M==null?void 0:M.datamodels.find(Ne=>Ne.id===l))==null?void 0:Lt.name,Se=Xy({schemaName:he,tableName:ie,modelName:we,connectionType:T,databaseName:d||""});return{connectionItems:Ie,selectedConnectionId:o,selectedConnection:k,isConnectionsLoading:j,isConnectionsError:D,modelItems:ht,selectedDatamodelId:l,selectedDatamodelName:we,isModelsLoading:R,isModelsError:O,selectedDatabaseName:d,databaseItems:xe,isDatabasesLoadingOrFetching:z||B,isDatabaseError:$,schemaItems:se,selectedSchemaName:f,isSchemaLoadingOrFetching:L||A,isSchemaError:W,tableItems:de,selectedTableName:h,isTableLoadingOrFetching:K||H,isTableError:q,columns:Z,isColumnsLoadingOrFetching:G||Q,isColumnsError:ne,isNonDbConnection:I,connectionType:T,tableName:ie,formattedTableName:Se,schemaName:he,refetchConnections:S,refetchModels:_,refetchDatabases:P,refetchSchemas:U,refetchTables:X,refetchColumns:ae,handleConnectionChange:ue,handleDatamodelChange:De,handleDatabaseChange:Oe,handleSchemaChange:Ce,handleTableChange:be}}function gy(e){return`${e}-${jr()}`}function NL(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 LQe(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 OI(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 Cee(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Nee(){const e=ke(C=>C.sqlGen),t=ke(C=>C.isDevMode),n=ke(C=>C.card.dataSource),r=ke(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}=OI(n),a=Cee(n),l=ke(C=>C.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:m}=ur(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Fx(),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=I_(j,e);p(k);const _=(D=b==null?void 0:b.find(R=>R.id===l))==null?void 0:D.name,M=R_(k,fi(o||""),fi(s),_||"",g,i||"");M&&(f(M),h(!0))}else if(!t){if(Rb(j.data_type))if(r&&r.length>0){const k={...j,role:"groupby",id:gy(j.column_name),name:j.column_name,type:j.data_type};d(k)}else{const k={...j,role:"metric",id:gy(j.column_name),name:j.column_name,label:NL(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(k)}if(Bc(j.data_type)){const k={...j,role:"groupby",id:gy(j.column_name),name:j.column_name,type:j.data_type,label:LQe(j.column_name,"month"),granularity:"month"};d(k)}if(Vo(j.data_type)){const k={...j,role:"metric",id:gy(j.column_name),name:j.column_name,label:NL(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=Xy({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=Xy({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 jee(){const e=ke(m=>m.selectedConnectionId),t=ke(m=>m.selectedDatamodelId),n=ke(m=>m.selectedDatabaseName),r=ke(m=>m.selectedSchemaName),s=ke(m=>m.selectedTableName),o=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}=Fx();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=Gw({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=`${jg}.${j}.${x}`,S=`${jg}.${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=Tke(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 _=jr(),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:q4(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:q4(m.data_type,S,(b==null?void 0:b.qualifiedFieldName)||x)}),_)}}return{assignFilter:p}}function zQe({column:e}){const[t,n]=N.useState(!1),r=ke(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=OI(r),a=ke(x=>x.selectedDatamodelId),l=ke(x=>x.sqlGen),{modelItems:u,connectionType:d}=Fx(),f=ke(x=>x.actions.setSqlGen),h=ke(x=>x.actions.setCardSql),p=ke(x=>x.actions.setRunSql),m=Cee(r);function g(x,y){var C;if(!m||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=I_(x,l,y),w=(C=u==null?void 0:u.find(j=>j.id===a))==null?void 0:C.name;f(v);const S=R_(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(Ip,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(Ap,{asChild:!0,children:c.jsx(rp,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(ef,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function BQe({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 VQe({field:e,context:t="editor",fieldState:n}){const r=ke(L=>L.isDevMode),s=t==="filter",o=r||s||(n==null?void 0:n.state)==="unreachable"&&!s,i=ee(L=>L.dashboard.filters),a=ee(L=>L.selectedSheetId),l=ee(L=>L.actions.removeFilter),{removeFilterValues:u}=Yt(),{assignFilter:d}=jee(),f=s?Qc(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}=IS({id:e.id,disabled:o}),[_,M]=N.useState(!1),R=ke(L=>L.card),{handleFieldClick:O}=See(R),{handleDevModeFieldClick:T,isNumberField:I}=Nee(),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:[ib(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(BQe,{field:e,fieldState:n})})]})}),r&&!s&&I(e)&&c.jsx("div",{onClick:L=>L.stopPropagation(),children:c.jsx(zQe,{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(B8,{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(Rae,{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(Wb,{open:b,onOpenChange:x,children:c.jsxs(mp,{children:[c.jsxs(gp,{children:[c.jsx(xp,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(yp,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(bp,{children:[c.jsx(wp,{children:"Cancel"}),c.jsx(vp,{onClick:F,children:"Remove Filter"})]})]})})]})}const HQe="SEMAPHOR_CALCULATED_FIELD",UQe=["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 kee(e){return!!e.expression}function WQe(e){return!!e.expression}function qQe(e){return!!e.expression}var Eee=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(Eee||{}),kl="Accordion",YQe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[FI,GQe,KQe]=l1(kl),[rC]=_r(kl,[KQe,gZ]),$I=gZ(),_ee=N.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(FI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(JQe,{...o,ref:t}):c.jsx(QQe,{...s,ref:t})})});_ee.displayName=kl;var[Dee,ZQe]=rC(kl),[Mee,XQe]=rC(kl,{collapsible:!1}),QQe=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(Dee,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:N.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(Mee,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(Tee,{...i,ref:t})})})}),JQe=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(Dee,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(Mee,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(Tee,{...o,ref:t})})})}),[eJe,sC]=rC(kl),Tee=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=GQe(n),f=Hd(s)==="ltr",h=Ee(e.onKeyDown,p=>{var D;if(!YQe.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(eJe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(FI.Slot,{scope:n,children:c.jsx(Be.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Lw="AccordionItem",[tJe,LI]=rC(Lw),Ree=N.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=sC(Lw,n),i=ZQe(Lw,n),a=$I(n),l=nr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(tJe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(yZ,{"data-orientation":o.orientation,"data-state":$ee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Ree.displayName=Lw;var Iee="AccordionHeader",Aee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=sC(kl,n),o=LI(Iee,n);return c.jsx(Be.h3,{"data-orientation":s.orientation,"data-state":$ee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Aee.displayName=Iee;var h_="AccordionTrigger",Pee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=sC(kl,n),o=LI(h_,n),i=XQe(h_,n),a=$I(n);return c.jsx(FI.ItemSlot,{scope:n,children:c.jsx(r$e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Pee.displayName=h_;var Oee="AccordionContent",Fee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=sC(kl,n),o=LI(Oee,n),i=$I(n);return c.jsx(s$e,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});Fee.displayName=Oee;function $ee(e){return e?"open":"closed"}var nJe=_ee,rJe=Ree,sJe=Aee,Lee=Pee,zee=Fee;const Bee=nJe,zI=E.forwardRef(({className:e,...t},n)=>c.jsx(rJe,{ref:n,className:J("border-b",e),...t}));zI.displayName="AccordionItem";const BI=E.forwardRef(({className:e,children:t,...n},r)=>c.jsx(sJe,{className:"flex",children:c.jsxs(Lee,{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"})]})}));BI.displayName=Lee.displayName;const VI=E.forwardRef(({className:e,children:t,...n},r)=>c.jsx(zee,{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})}));VI.displayName=zee.displayName;function oJe({context:e="editor"}={}){var _,M,R,O;const[t,n]=N.useState(""),[r,s]=N.useState("all");ke(T=>T.isDevMode);const o=ke(T=>T.card.dataSource),i=ke(T=>T.card.config),a=ke(T=>T.card),{autoJoinMetadata:l}=fa(a),{columns:u=[],columnGroups:d=[],isLoading:f,error:h}=AM(),p=(o==null?void 0:o.mode)==="semanticDomain"?o.semanticDomainId:void 0,{data:m}=PI(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,Nee();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"&&kee(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:O_(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(Mc,{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(o1,{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(np,{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(Z_,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:D})]})]})})]}),c.jsxs(vl,{className:"py-2",children:[c.jsx(Bee,{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(zI,{value:T,className:"border-none",children:[c.jsx(BI,{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(VI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:I.fields.map(z=>{const B=PM(z,{joinabilityMap:(m==null?void 0:m.joinabilityMap)||null,selectedFields:g,cardConfig:i,autoJoinMetadata:l});return c.jsx(VQe,{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 Vee({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(oJe,{context:e})," "]})}function Hee(){const e=ke(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}=OI(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 iJe(){Hee();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=ke(l=>l.card.dataSource);return N.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function aJe(){const e=ee(n=>n.actions.setShowFilters),{hasEntities:t}=iJe();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(pZ,{})})]}),!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(TS,{collisionDetection:ES,children:c.jsx(RS,{items:[],strategy:BR,children:c.jsx(Vee,{context:"filter"})})})})]})}function lJe(){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(_R,{filter:r}),c.jsx(CS,{filter:r})]},r.id))}):null}function cJe(){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(lJe,{}),c.jsx(bee,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(aJe,{})})]})}const uJe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-C_kxUkyD.js"))),dJe=N.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-E4AXmvCQ.js"))),fJe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-BCOS2K2w.js"))),hJe=N.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-C4CDYpm_.js")).then(e=>({default:e.ResourceManagementPanel})));function pJe({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(Sl,{FallbackComponent:hS,children:c.jsxs(H_,{dashboardProps:n,children:[c.jsx(ife,{}),c.jsx(AI,{children:c.jsxs(xee,{preferences:a,children:[o&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(fJe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(uJe,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(hJe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(QM,{...n,type:"dashboard",children:[s&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(dJe,{})}),c.jsx(cJe,{})]})})]})]})]})})]})})}var mJe=Object.defineProperty,gJe=(e,t,n)=>t in e?mJe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,by=(e,t,n)=>gJe(e,typeof t!="symbol"?t+"":t,n);const bJe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},xJe={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}},yJe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},vJe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},wJe={stringify:e=>e,parse:e=>e},ej={string:wJe,number:vJe,boolean:bJe,function:xJe,json:yJe};function SJe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const xy=Symbol.for("r2wc.render"),yy=Symbol.for("r2wc.connected"),xu=Symbol.for("r2wc.context"),Ta=Symbol.for("r2wc.props");function CJe(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=SJe(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(),by(this,o,!0),by(this,s),by(this,r,{}),by(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?ej[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[yy]=!0,this[xy]()}disconnectedCallback(){this[yy]=!1,this[xu]&&n.unmount(this[xu]),delete this[xu]}attributeChangedCallback(m,g,b){const x=f[m],y=l[x],v=y?ej[y]:null;x in l&&v!=null&&v.parse&&b&&(this[Ta][x]=v.parse(b,m,this),this[xy]())}[(o=yy,s=xu,r=Ta,xy)](){this[yy]&&(this[xu]?n.update(this[xu],this[Ta]):this[xu]=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?ej[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,m,this);this.getAttribute(m)!==y&&this.setAttribute(m,y)}else this[xy]()}})}return h}function NJe(e,t,n){const r=hj(e),s=N.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function jJe({root:e,ReactComponent:t},n){const r=N.createElement(t,n);e.render(r)}function kJe({root:e}){e.unmount()}function EJe(e,t={}){return CJe(e,t,{mount:NJe,update:jJe,unmount:kJe})}const _Je={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"},DJe=EJe(yee,{props:_Je});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 jL(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 kL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?jL(Object(n),!0).forEach(function(r){MJe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):jL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function TJe(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 RJe(e,t){if(e==null)return{};var n=TJe(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 IJe(e,t){return AJe(e)||PJe(e,t)||OJe(e,t)||FJe()}function AJe(e){if(Array.isArray(e))return e}function PJe(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 OJe(e,t){if(e){if(typeof e=="string")return EL(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 EL(e,t)}}function EL(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 FJe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
1066
|
+
`)}})}});var NXe=bZe(()=>qJ(Ar([Wn({type:ut("text-start"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("text-delta"),id:Le(),delta:Le(),providerMetadata:ir.optional()}),Wn({type:ut("text-end"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("error"),errorText:Le()}),Wn({type:ut("tool-input-start"),toolCallId:Le(),toolName:Le(),providerExecuted:Sr().optional(),dynamic:Sr().optional()}),Wn({type:ut("tool-input-delta"),toolCallId:Le(),inputTextDelta:Le()}),Wn({type:ut("tool-input-available"),toolCallId:Le(),toolName:Le(),input:co(),providerExecuted:Sr().optional(),providerMetadata:ir.optional(),dynamic:Sr().optional()}),Wn({type:ut("tool-input-error"),toolCallId:Le(),toolName:Le(),input:co(),providerExecuted:Sr().optional(),providerMetadata:ir.optional(),dynamic:Sr().optional(),errorText:Le()}),Wn({type:ut("tool-output-available"),toolCallId:Le(),output:co(),providerExecuted:Sr().optional(),dynamic:Sr().optional(),preliminary:Sr().optional()}),Wn({type:ut("tool-output-error"),toolCallId:Le(),errorText:Le(),providerExecuted:Sr().optional(),dynamic:Sr().optional()}),Wn({type:ut("reasoning-start"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-delta"),id:Le(),delta:Le(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-end"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("source-url"),sourceId:Le(),url:Le(),title:Le().optional(),providerMetadata:ir.optional()}),Wn({type:ut("source-document"),sourceId:Le(),mediaType:Le(),title:Le(),filename:Le().optional(),providerMetadata:ir.optional()}),Wn({type:ut("file"),url:Le(),mediaType:Le(),providerMetadata:ir.optional()}),Wn({type:BJ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:Le().optional(),data:co(),transient:Sr().optional()}),Wn({type:ut("start-step")}),Wn({type:ut("finish-step")}),Wn({type:ut("start"),messageId:Le().optional(),messageMetadata:co().optional()}),Wn({type:ut("finish"),messageMetadata:co().optional()}),Wn({type:ut("abort")}),Wn({type:ut("message-metadata"),messageMetadata:co()})])));function jXe(e){return e.type.startsWith("data-")}function eee(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]=eee(o,s):n[r]=s}return n}function kXe(e){const t=["ROOT"];let n=-1,r=null;function s(l,u,d){switch(l){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":s(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function tee(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ow({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ow({text:kXe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Uy(e){return e.type.startsWith("tool-")}function EXe(e){return e.type==="dynamic-tool"}function c_(e){return Uy(e)||EXe(e)}function wL(e){return e.type.split("-").slice(1).join("-")}function _Xe({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 DXe({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(Uy).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=>Uy(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?eee(u.message.metadata,w):w;t!=null&&await gL({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(Uy);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 tee(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:wL(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:wL(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(jXe(a)){(n==null?void 0:n[a.type])!=null&&await gL({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 MXe({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()}}Ox({prefix:"aitxt",size:24});Ox({prefix:"aiobj",size:24});var TXe=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()})}};Ox({prefix:"aiobj",size:24});var RXe={};pXe(RXe,{object:()=>AXe,text:()=>IXe});var IXe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),AXe=({schema:e})=>{const t=fXe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await tee(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 Ow({text:n});if(!s.success)throw new yL({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 _I({value:s.value,schema:t});if(!o.success)throw new yL({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}}},PXe=Uf({name:Le(),version:Le()}),MI=Uf({_meta:mr(Wt({}).loose())}),wb=MI,OXe=Wt({method:Le(),params:mr(MI)}),FXe=Uf({experimental:mr(Wt({}).loose()),logging:mr(Wt({}).loose()),prompts:mr(Uf({listChanged:mr(Sr())})),resources:mr(Uf({subscribe:mr(Sr()),listChanged:mr(Sr())})),tools:mr(Uf({listChanged:mr(Sr())}))});wb.extend({protocolVersion:Le(),capabilities:FXe,serverInfo:PXe,instructions:mr(Le())});var $Xe=wb.extend({nextCursor:mr(Le())}),LXe=Wt({name:Le(),description:mr(Le()),inputSchema:Wt({type:ut("object"),properties:mr(Wt({}).loose())}).loose()}).loose();$Xe.extend({tools:su(LXe)});var zXe=Wt({type:ut("text"),text:Le()}).loose(),BXe=Wt({type:ut("image"),data:PJ(),mimeType:Le()}).loose(),nee=Wt({uri:Le(),mimeType:mr(Le())}).loose(),VXe=nee.extend({text:Le()}),HXe=nee.extend({blob:PJ()}),UXe=Wt({type:ut("resource"),resource:Ar([VXe,HXe])}).loose();wb.extend({content:su(Ar([zXe,BXe,UXe])),isError:Sr().default(!1).optional()}).or(wb.extend({toolResult:co()}));var nC="2.0",WXe=Wt({jsonrpc:ut(nC),id:Ar([Le(),yb().int()])}).merge(OXe).strict(),qXe=Wt({jsonrpc:ut(nC),id:Ar([Le(),yb().int()]),result:wb}).strict(),YXe=Wt({jsonrpc:ut(nC),id:Ar([Le(),yb().int()]),error:Wt({code:yb().int(),message:Le(),data:mr(co())})}).strict(),GXe=Wt({jsonrpc:ut(nC)}).merge(Wt({method:Le(),params:mr(MI)})).strict();Ar([WXe,GXe,qXe,YXe]);async function KXe(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 ZXe=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 Ef(this.body),l=await Ef(this.headers),u=await Ef(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:mL({"Content-Type":"application/json",...h},`ai-sdk/${vL}`,pL()),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 Ef(this.body),a=await Ef(this.headers),l=await Ef(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:mL(f,`ai-sdk/${vL}`,pL()),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)}},TI=class extends ZXe{constructor(e={}){super(e)}processResponseStream(e){return vZe({stream:e,schema:NXe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},XXe=class{constructor({generateId:e=lZe,id:t=e(),transport:n=new TI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new TXe,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 KXe(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=>c_(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=>c_(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:_Xe({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 MXe({stream:DXe({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 QXe({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(c_);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function JXe(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 eQe=JXe;const tQe=zc(eQe);var ree=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Tn=(e,t,n)=>(ree(e,t,"read from private field"),n?n.call(e):t.get(e)),zi=(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)},Fl=(e,t,n,r)=>(ree(e,t,"write to private field"),t.set(e,n),n);function nQe(e,t){return t!=null?tQe(e,t):e}var jo,Wy,qy,Wm,qm,Ym,If,u_,d_,rQe=class{constructor(e=[]){zi(this,jo,void 0),zi(this,Wy,"ready"),zi(this,qy,void 0),zi(this,Wm,new Set),zi(this,qm,new Set),zi(this,Ym,new Set),this.pushMessage=t=>{Fl(this,jo,Tn(this,jo).concat(t)),Tn(this,If).call(this)},this.popMessage=()=>{Fl(this,jo,Tn(this,jo).slice(0,-1)),Tn(this,If).call(this)},this.replaceMessage=(t,n)=>{Fl(this,jo,[...Tn(this,jo).slice(0,t),this.snapshot(n),...Tn(this,jo).slice(t+1)]),Tn(this,If).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?nQe(t,n):t;return Tn(this,Wm).add(r),()=>{Tn(this,Wm).delete(r)}},this["~registerStatusCallback"]=t=>(Tn(this,qm).add(t),()=>{Tn(this,qm).delete(t)}),this["~registerErrorCallback"]=t=>(Tn(this,Ym).add(t),()=>{Tn(this,Ym).delete(t)}),zi(this,If,()=>{Tn(this,Wm).forEach(t=>t())}),zi(this,u_,()=>{Tn(this,qm).forEach(t=>t())}),zi(this,d_,()=>{Tn(this,Ym).forEach(t=>t())}),Fl(this,jo,e)}get status(){return Tn(this,Wy)}set status(e){Fl(this,Wy,e),Tn(this,u_).call(this)}get error(){return Tn(this,qy)}set error(e){Fl(this,qy,e),Tn(this,d_).call(this)}get messages(){return Tn(this,jo)}set messages(e){Fl(this,jo,[...e]),Tn(this,If).call(this)}};jo=new WeakMap;Wy=new WeakMap;qy=new WeakMap;Wm=new WeakMap;qm=new WeakMap;Ym=new WeakMap;If=new WeakMap;u_=new WeakMap;d_=new WeakMap;var Af,SL=class extends XXe{constructor({messages:e,...t}){const n=new rQe(e);super({...t,state:n}),zi(this,Af,void 0),this["~registerMessagesCallback"]=(r,s)=>Tn(this,Af)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Tn(this,Af)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Tn(this,Af)["~registerErrorCallback"](r),Fl(this,Af,n)}};Af=new WeakMap;function see({experimental_throttle:e,resume:t=!1,...n}={}){const r=N.useRef("chat"in n?n.chat:new SL(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new SL(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 sQe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function oQe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function iQe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function aQe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function oee(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:aQe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function iee(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 lQe(){var b;const{authToken:e,tokenProps:t}=qe(),n=ee(x=>x.dashboard.aiScopeTables),r=(b=Qw().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=see({transport:new TI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Ai.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:IW(x)}})}),onToolCall:p,sendAutomaticallyWhen:QXe,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:oee(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=iee(d);return{sendMessage:s,regenerate:a,isLoading:m,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function aee(){var u;const{authToken:e,tokenProps:t}=qe(),n=(u=Qw().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 lee({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(C8,{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 Fw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(aD,{className:r});case"view":return c.jsx(yc,{className:r});case"materialized view":return c.jsx(bae,{className:r});case"model":return c.jsx(o1,{className:r});case"file":return c.jsx(Ni,{className:r});case"dataset":return c.jsx(sl,{className:r});case"upload":return c.jsx(dD,{className:r});case"url":return c.jsx(I8,{className:r});default:return c.jsx(s1,{className:r})}}const cee=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})]}));cee.displayName=ds.Input.displayName;const my=e=>e.label||(e==null?void 0:e.name),CL=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function cQe({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=my(C).toLowerCase(),D=CL(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(my(b[0]))},[b,m]);const x=()=>{if(!m)return;const C=b.find(j=>my(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(PS,{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(cee,{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(kr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick: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(OS,{className:"min-h-60",children:[c.jsx(FS,{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(kr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx($S,{children:b.map((C,j)=>{const D=v(C),k="id"in C?C.id:`${C.connectionId}-${C.name}`,_=my(C);return c.jsxs(LS,{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:Fw(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:CL(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 f_=e=>e.name||e.name,uQe=e=>{const t=f_(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 dQe({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:[Fw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:f_(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:uQe(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(xae,{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:Fw(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:f_(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 uee(e){return e.type==="dataset"&&e.label||e.name}function fQe(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 hQe({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,"]"]}),uee(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 pQe(e){const{tokenProps:t}=qe(),n=ee(l=>l.authToken)||e;ke(l=>l.selectedConnectionId),ke(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=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 mQe(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 gQe(e){var g,b;const{tokenProps:t}=qe(),n=ee(x=>x.authToken)||e,{connections:r}=Ii(e),s=ke(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:p}=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 bQe(e){var g;const{tokenProps:t}=qe(),n=ee(b=>b.authToken)||e,{connections:r}=Ii(e),s=ke(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=ke(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:p}=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 dee(e){const{tokenProps:t}=qe(),n=ee(h=>h.authToken)||e,{connections:r}=Ii(e),s=ke(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=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 xQe(){var S,C,j;const e=ke(D=>D.card.dataSource);ke(D=>D.actions.updateDirectSource);const t=ke(D=>D.actions.updateDataSource),[n,r]=N.useState(""),{selectedConnection:s,error:o}=Ii(),{databases:i,isPending:a,error:l,label:u}=gQe(),{schemas:d,isPending:f,error:h,label:p}=bQe(),{error:m}=dee(),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 yQe(){const e=ke(l=>l.card.dataSource),t=ke(l=>l.actions.updateDataSource),[n,r]=N.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(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(dD,{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 vQe(){const e=ke(f=>f.card.dataSource),t=ke(f=>f.actions.updateDataSource),[n,r]=N.useState(""),[s,o]=N.useState(""),[i,a]=N.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(p=>p.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(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(kr,{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(s1,{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 wQe(e,t){var y,v;const{tokenProps:n}=qe(),r=ee(w=>w.authToken)||t,{connections:s}=Ii(t),o=ke(w=>{var S,C;return(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.connectionId}),i=ke(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.database}),a=ke(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:p,isLoading:m,error:g,refetch:b}=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 $w({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(bd,{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 SQe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Ii(),[i,a]=N.useState(""),[l,u]=N.useState(""),[d,f]=N.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=ur(),{entities:m,isLoading:g,error:b}=wQe("table"),{dataModels:x,isPending:y,error:v}=dee(),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(yQe,{}),e.connectionType==="url"&&c.jsx(vQe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(xQe,{}),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($w,{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($w,{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 CQe({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}=pQe(),m=o?f.filter(C=>s.includes(C.id)):f,{datasets:g,isPending:b,error:x}=mQe(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($w,{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($w,{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 RI({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(CQe,{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(SQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:k})]})}),c.jsx(hQe,{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 NQe({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){$e.error(`You can only attach ${$a} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=YQ(l);if(f.forEach(({file:h,error:p})=>{$e.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>yI(p)));e(h)}catch(h){console.error("Failed to process files:",h),$e.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(nD,{className:"h-4 w-4 text-muted-foreground"})})]})}function jQe({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){$e.error(`You can only attach ${$a} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=YQ(h);if(g.forEach(({file:b,error:x})=>{$e.error(`${b.name}: ${x}`)}),m.length>0)try{const b=await Promise.all(m.map(x=>yI(x)));t(b),$e.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),$e.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(dD,{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 II=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=Op();DNe(),_Ne();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:S}=W1(),{queueMessage:C}=Fp(),{addFileAttachment:j,removeFileAttachment:D,clearFileAttachments:k,getFileAttachments:_}=XM(),M=ZM(l),R=ke(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=LWe(H.nativeEvent);q.length>0&&(H.preventDefault(),q.forEach(async X=>{const Z=await yI(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(jQe,{onFilesDropped:$,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(dQe,{entities:x.selectedEntities,availableEntities:T||[],onRemoveEntity:U,onRemoveEntities:Y}),M.length>0&&c.jsx(zWe,{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(dae,{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(cQe,{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(NQe,{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(_ae,{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(z8,{className:"size-4"})})]})]})]}),c.jsx(RI,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:p,dataSource:R||JS,dialogMode:"aiContext"})]})});II.displayName="ChatInputWithContext";function fee({assistantType:e,className:t}){const n=AW(e),{removeFromQueue:r}=Fp();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 hee({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=AW(e),{dequeueMessage:o}=Fp();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 pee(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 mee(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 gee(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:GQ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const kQe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function EQe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=N.useState(!1),[a,l]=N.useState(Yw),[u,d]=N.useState(!1),[f,h]=N.useState(!1),[p,m]=N.useState(!1),g=n??p,{isLocalDev:b,isConsoleMode:x}=pp(),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=Op(),{setCurrentAIContext:k,updateSelectedEntities:_,setReasoningEffort:M,setShowReasoning:R}=W1(),{clearQueue:O}=Fp(),{clearFileAttachments:T,getFileAttachments:I}=XM(),F=ZM("dashboard"),z=ee(Ve=>Ve.dashboard.aiContext),B=ke(Ve=>Ve.card.dataSource),{assistantProfile:$}=aee(),P=ee(Ve=>Ve.handleOpenAssistantProfile),{sendMessage:V,isLoading:L,messages:A,setMessages:W,status:U,stop:Y,errorMessage:K,clearError:H}=lQe(),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:pt,connectionId:He,cardType:Ze,python:ve,cardConfig:je,dataSource:Te}){if(console.log("handleAddNewFrame",{sql:Ve,data:Ue,cardTitle:pt,connectionId:He,cardType:Ze,python:ve,cardConfig:je,dataSource:Te}),!v)return;const ze={id:jr(),title:pt||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ze==="horizontalBar"?"y":"x"}},type:Ze,sql:Ve,python:ve,dataSource:Te,config:je,connectionId:He},nt={id:jr(),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 pt=[];Ue&&pt.push({type:"text",text:Ue}),F.forEach(He=>{He.data&&pt.push({type:"file",mediaType:He.type,filename:He.name,url:`data:${He.type};base64,${He.data}`})}),V({role:"user",parts:pt}),G(""),T("dashboard"),se({force:!0})};N.useEffect(()=>{var Ve;e&&((Ve=y.current)==null||Ve.focus())},[e]),hee({assistantType:"dashboard",status:U,isLoading:L,sendMessage:V});const{hasActiveTools:ie}=gee(A),{visibleMessages:he,hasMoreMessages:be,totalMessageCount:Ce,loadMoreMessages:Oe,resetMessageWindow:ue}=mee(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:De,isAtBottom:Ie,hasNewMessages:ht,newMessageCount:xe,scrollToBottom:se,handleScroll:de,resetNewMessageCount:we}=pee(he,{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),$e.success("Conversation copied")}catch(Ue){console.error("Failed to copy conversation",Ue),$e.error("Unable to copy conversation")}},[A]);function Ke(){D.selectedEntities.length===0&&k({selectedEntities:(z==null?void 0:z.selectedEntities)||[]})}const Lt=(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(fp,{children:[c.jsx(hp,{asChild:!0,children:c.jsx(lc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(rp,{className:"size-3.5"})})}),c.jsxs(Yd,{align:"end",children:[c.jsx(Qf,{children:"Options"}),c.jsx(vd,{}),c.jsx(Zm,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Zm,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Zm,{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(lc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:X,children:g?c.jsx(tD,{className:"size-4"}):c.jsx(i1,{className:"size-4"})}),c.jsx(lc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),O("dashboard"),H(),ue()},children:c.jsx(a1,{className:"size-4"})}),c.jsx(lc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(vt,{className:"size-4"})})]})]}),c.jsxs(vl,{"data-role":"dashboard-assistant-scroll-area",ref:De,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:de,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[be&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:Oe,className:"text-xs",children:["Load ",Math.min(5,Ce-he.length)," ","more messages (",Ce-he.length," ","hidden)"]})}),c.jsx(ZQ,{showTools:a,showSystemMessage:u,messages:he,onAddToDashboard:ne,onQuickReply:Qe,disableQuickReplies:L}),!ie&&c.jsx(KQ,{status:U,errorMessage:K})]}),c.jsx(Zo,{orientation:"horizontal"})]}),e&&!Ie&&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"}),ht&&xe>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:xe>9?"9+":xe})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&Lt&&c.jsx(XQ,{onClick:Se,placeholders:kQe}),c.jsx("div",{children:Lt&&$&&c.jsx(lee,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Pe})}),c.jsx(fee,{assistantType:"dashboard",className:"mb-3"}),c.jsx(II,{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(RI,{incomingSelectedEntities:(z==null?void 0:z.selectedEntities)||[],open:f,onOpenChange:h,dataSource:B||JS,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 _Qe(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(),$e.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=oR(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),$e.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 DQe(e,t){switch(e.interactionMode){case"drillToDetail":MQe(e,t);break;case"drillThrough":TQe(e,t);break;case"drillToURL":RQe(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 MQe(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 TQe(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 RQe(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 IQe({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(cZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(dZ,{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 AQe(){const e=It(w=>w.interactionStates),t=It(w=>w.setInteractionState),n=It(w=>w.clearLastInteractionEvent),r=It(w=>w.replaceCardWithInsight),s=It(w=>w.setPendingDrillThrough),o=It(w=>w.pendingDrillThrough),i=It(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Yt(),{selectDashboard:u}=Ab(),d=ee(w=>w.dashboard),f=ee(w=>w.filterValues),{data:h,isLoading:p}=Ufe((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[m,g]=N.useState({open:!1,insightId:""}),b=fZ(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:na,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...Ao(),appliedClickFilters:[_],contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:D};t(na,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{DQe(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(IQe,{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 PQe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=OQe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function OQe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function FQe(e){return e?`Back to ${e}`:"Back"}function $Qe(){var x,y,v,w,S;const e=It(C=>C.interactionStates[na]),t=ee(C=>C.actions.goBackFromDrill),n=ee(C=>C.actions.clearDrillContext),{selectDashboard:r}=Ab(),[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})};PQe(f);const b=FQe(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(c8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function bee(){var G;const{showAssistant:e,tokenProps:t}=qe(),{preferences:n,isConsoleMode:r}=pp(),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=od(Q=>Q.setFullscreen),d=od(Q=>Q.setPanelOpen),f=od(Q=>Q.setContainer),h=MW("dashboard"),p=TW(),m=RW("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}=H6(C),[R,O]=N.useState(null);S1(Pt.DASHBOARD);const{setSelectedSheetId:T,setSheetTitle:I,addSheet:F,setSheets:z}=Yt();_Qe(i);const{setActiveAssistantType:B}=W1();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:jr(),title:"New Sheet"};F(Q),T(Q.id)}function V(Q,ne){if(!C)return;R===Q?(M(),O(null),$e.success("Default sheet cleared")):(_(Q),O(Q),$e.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||[]),[he]=ie.splice(parseInt(ae),1);ie.splice(ne,0,he),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(w8,{className:"h-4 w-4"}):c.jsx(S8,{className:"h-4 w-4"})}),v==null?void 0:v.map((ae,ie)=>{const he=S===ae.id,be=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(tb,{enabled:w&&he,text:ae.title,onSave:Ce=>I(ae.id,Ce),children:ae.title},ae.id),!w&&he&&c.jsx("div",{title:be?"Clear default sheet":"Set as default sheet",children:c.jsx(iD,{className:J("ml-1 size-3 cursor-pointer transition-all",be?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:Ce=>{Ce.stopPropagation(),V(ae.id,ae.title||"Sheet")}})}),w&&he&&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(kr,{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(e8e,{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(vl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:q()}),c.jsx(I8e,{open:a,setOpen:l})]})}const Z=N.useCallback(Q=>{f("dashboard",Q)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(AQe,{}),c.jsx($Qe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(RX,{className:J("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(HE,{children:X()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(R8e,{open:g,onTabClick:$,withHandle:!0}),c.jsx(HE,{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(EQe,{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(oD,{className:"h-5 w-5"})})})]})]}):null}function AI({children:e}){return c.jsx(wa,{style:{height:"100%",width:"100%"},children:c.jsx(hse,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(Yn,{delayDuration:0,children:e})})})}function xee({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(I9.Provider,{value:r,children:c.jsx(kR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function yee(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(Sl,{FallbackComponent:hS,children:c.jsx(H_,{dashboardProps:e,children:c.jsx(AI,{children:c.jsx(xee,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(QM,{...e,type:"dashboard",children:c.jsx(bee,{})})})})})})})}function PI(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 vee(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 wee(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 See=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=PI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=ur(),h=ke(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:lU(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){$e.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=JSe(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&&oU();return}const z=nCe(T,I,h);if(!z){$e.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const B=vee(T,z,h);if(!B.isValid){$e.error("Invalid Field Type",{description:B.reason,position:"top-center",duration:3e3});return}const $=m(z);if(iU(T,$))return;const P=cU(T,z,$);if(P){const L=[...$,P];g(z,L),z==="metrics"&&wee(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 Fx(e,t){var Pe,Qe,Nt,Ke,Lt;const{tokenProps:n}=qe(),r=Zs(),s=qe().authToken||e,o=ke(Ne=>Ne.selectedConnectionId),i=ke(Ne=>Ne.card),{queryKey:a}=Ype(i),l=ke(Ne=>Ne.selectedDatamodelId),u=ke(Ne=>Ne.isDevMode),d=ke(Ne=>Ne.selectedDatabaseName),f=ke(Ne=>Ne.selectedSchemaName),h=ke(Ne=>Ne.selectedTableName),p=ke(Ne=>Ne.actions.setSelectedConnectionId),m=ke(Ne=>Ne.actions.setSelectedDatamodelId),g=ke(Ne=>Ne.actions.setSelectedDatabaseName),b=ke(Ne=>Ne.actions.setSelectedSchemaName),x=ke(Ne=>Ne.actions.setSelectedTableName);ke(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}=Ii(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}=uU(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||"",he=I?"":f||"";function be(Ne){x(Ne),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Ce(Ne){b(Ne),x("")}function Oe(Ne){g(Ne==="none"?"":Ne),b(""),x(""),Ne!=="none"&&Ne!==""&&m("")}function ue(Ne){p(Ne)}function De(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 Ie=C==null?void 0:C.connections.map(Ne=>({id:Ne.id,name:Ne.name,type:Ne.type})),ht=(Ke=M==null?void 0:M.datamodels)==null?void 0:Ke.map(Ne=>({id:Ne.id,name:Ne.name})),xe=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})),de=Y==null?void 0:Y.tables.map(Ne=>({id:Ne.table_name,name:Ne.table_name})),we=(Lt=M==null?void 0:M.datamodels.find(Ne=>Ne.id===l))==null?void 0:Lt.name,Se=Xy({schemaName:he,tableName:ie,modelName:we,connectionType:T,databaseName:d||""});return{connectionItems:Ie,selectedConnectionId:o,selectedConnection:k,isConnectionsLoading:j,isConnectionsError:D,modelItems:ht,selectedDatamodelId:l,selectedDatamodelName:we,isModelsLoading:R,isModelsError:O,selectedDatabaseName:d,databaseItems:xe,isDatabasesLoadingOrFetching:z||B,isDatabaseError:$,schemaItems:se,selectedSchemaName:f,isSchemaLoadingOrFetching:L||A,isSchemaError:W,tableItems:de,selectedTableName:h,isTableLoadingOrFetching:K||H,isTableError:q,columns:Z,isColumnsLoadingOrFetching:G||Q,isColumnsError:ne,isNonDbConnection:I,connectionType:T,tableName:ie,formattedTableName:Se,schemaName:he,refetchConnections:S,refetchModels:_,refetchDatabases:P,refetchSchemas:U,refetchTables:X,refetchColumns:ae,handleConnectionChange:ue,handleDatamodelChange:De,handleDatabaseChange:Oe,handleSchemaChange:Ce,handleTableChange:be}}function gy(e){return`${e}-${jr()}`}function NL(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 LQe(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 OI(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 Cee(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Nee(){const e=ke(C=>C.sqlGen),t=ke(C=>C.isDevMode),n=ke(C=>C.card.dataSource),r=ke(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}=OI(n),a=Cee(n),l=ke(C=>C.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:m}=ur(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Fx(),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=I_(j,e);p(k);const _=(D=b==null?void 0:b.find(R=>R.id===l))==null?void 0:D.name,M=R_(k,fi(o||""),fi(s),_||"",g,i||"");M&&(f(M),h(!0))}else if(!t){if(Rb(j.data_type))if(r&&r.length>0){const k={...j,role:"groupby",id:gy(j.column_name),name:j.column_name,type:j.data_type};d(k)}else{const k={...j,role:"metric",id:gy(j.column_name),name:j.column_name,label:NL(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(k)}if(Bc(j.data_type)){const k={...j,role:"groupby",id:gy(j.column_name),name:j.column_name,type:j.data_type,label:LQe(j.column_name,"month"),granularity:"month"};d(k)}if(Vo(j.data_type)){const k={...j,role:"metric",id:gy(j.column_name),name:j.column_name,label:NL(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=Xy({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=Xy({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 jee(){const e=ke(m=>m.selectedConnectionId),t=ke(m=>m.selectedDatamodelId),n=ke(m=>m.selectedDatabaseName),r=ke(m=>m.selectedSchemaName),s=ke(m=>m.selectedTableName),o=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}=Fx();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=Gw({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=`${jg}.${j}.${x}`,S=`${jg}.${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=Tke(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 _=jr(),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:q4(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:q4(m.data_type,S,(b==null?void 0:b.qualifiedFieldName)||x)}),_)}}return{assignFilter:p}}function zQe({column:e}){const[t,n]=N.useState(!1),r=ke(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=OI(r),a=ke(x=>x.selectedDatamodelId),l=ke(x=>x.sqlGen),{modelItems:u,connectionType:d}=Fx(),f=ke(x=>x.actions.setSqlGen),h=ke(x=>x.actions.setCardSql),p=ke(x=>x.actions.setRunSql),m=Cee(r);function g(x,y){var C;if(!m||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=I_(x,l,y),w=(C=u==null?void 0:u.find(j=>j.id===a))==null?void 0:C.name;f(v);const S=R_(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(Ip,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(Ap,{asChild:!0,children:c.jsx(rp,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(ef,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function BQe({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 VQe({field:e,context:t="editor",fieldState:n}){const r=ke(L=>L.isDevMode),s=t==="filter",o=r||s||(n==null?void 0:n.state)==="unreachable"&&!s,i=ee(L=>L.dashboard.filters),a=ee(L=>L.selectedSheetId),l=ee(L=>L.actions.removeFilter),{removeFilterValues:u}=Yt(),{assignFilter:d}=jee(),f=s?Qc(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}=IS({id:e.id,disabled:o}),[_,M]=N.useState(!1),R=ke(L=>L.card),{handleFieldClick:O}=See(R),{handleDevModeFieldClick:T,isNumberField:I}=Nee(),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:[ib(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(BQe,{field:e,fieldState:n})})]})}),r&&!s&&I(e)&&c.jsx("div",{onClick:L=>L.stopPropagation(),children:c.jsx(zQe,{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(B8,{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(Rae,{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(Wb,{open:b,onOpenChange:x,children:c.jsxs(mp,{children:[c.jsxs(gp,{children:[c.jsx(xp,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(yp,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(bp,{children:[c.jsx(wp,{children:"Cancel"}),c.jsx(vp,{onClick:F,children:"Remove Filter"})]})]})})]})}const HQe="SEMAPHOR_CALCULATED_FIELD",UQe=["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 kee(e){return!!e.expression}function WQe(e){return!!e.expression}function qQe(e){return!!e.expression}var Eee=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(Eee||{}),kl="Accordion",YQe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[FI,GQe,KQe]=l1(kl),[rC]=_r(kl,[KQe,gZ]),$I=gZ(),_ee=N.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(FI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(JQe,{...o,ref:t}):c.jsx(QQe,{...s,ref:t})})});_ee.displayName=kl;var[Dee,ZQe]=rC(kl),[Mee,XQe]=rC(kl,{collapsible:!1}),QQe=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(Dee,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:N.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(Mee,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(Tee,{...i,ref:t})})})}),JQe=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(Dee,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(Mee,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(Tee,{...o,ref:t})})})}),[eJe,sC]=rC(kl),Tee=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=GQe(n),f=Hd(s)==="ltr",h=Ee(e.onKeyDown,p=>{var D;if(!YQe.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(eJe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(FI.Slot,{scope:n,children:c.jsx(Be.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Lw="AccordionItem",[tJe,LI]=rC(Lw),Ree=N.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=sC(Lw,n),i=ZQe(Lw,n),a=$I(n),l=nr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(tJe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(yZ,{"data-orientation":o.orientation,"data-state":$ee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Ree.displayName=Lw;var Iee="AccordionHeader",Aee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=sC(kl,n),o=LI(Iee,n);return c.jsx(Be.h3,{"data-orientation":s.orientation,"data-state":$ee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Aee.displayName=Iee;var h_="AccordionTrigger",Pee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=sC(kl,n),o=LI(h_,n),i=XQe(h_,n),a=$I(n);return c.jsx(FI.ItemSlot,{scope:n,children:c.jsx(r$e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Pee.displayName=h_;var Oee="AccordionContent",Fee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=sC(kl,n),o=LI(Oee,n),i=$I(n);return c.jsx(s$e,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});Fee.displayName=Oee;function $ee(e){return e?"open":"closed"}var nJe=_ee,rJe=Ree,sJe=Aee,Lee=Pee,zee=Fee;const Bee=nJe,zI=E.forwardRef(({className:e,...t},n)=>c.jsx(rJe,{ref:n,className:J("border-b",e),...t}));zI.displayName="AccordionItem";const BI=E.forwardRef(({className:e,children:t,...n},r)=>c.jsx(sJe,{className:"flex",children:c.jsxs(Lee,{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"})]})}));BI.displayName=Lee.displayName;const VI=E.forwardRef(({className:e,children:t,...n},r)=>c.jsx(zee,{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})}));VI.displayName=zee.displayName;function oJe({context:e="editor"}={}){var _,M,R,O;const[t,n]=N.useState(""),[r,s]=N.useState("all");ke(T=>T.isDevMode);const o=ke(T=>T.card.dataSource),i=ke(T=>T.card.config),a=ke(T=>T.card),{autoJoinMetadata:l}=fa(a),{columns:u=[],columnGroups:d=[],isLoading:f,error:h}=AM(),p=(o==null?void 0:o.mode)==="semanticDomain"?o.semanticDomainId:void 0,{data:m}=PI(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,Nee();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"&&kee(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:O_(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(Mc,{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(o1,{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(np,{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(Z_,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:D})]})]})})]}),c.jsxs(vl,{className:"py-2",children:[c.jsx(Bee,{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(zI,{value:T,className:"border-none",children:[c.jsx(BI,{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(VI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:I.fields.map(z=>{const B=PM(z,{joinabilityMap:(m==null?void 0:m.joinabilityMap)||null,selectedFields:g,cardConfig:i,autoJoinMetadata:l});return c.jsx(VQe,{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 Vee({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(oJe,{context:e})," "]})}function Hee(){const e=ke(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}=OI(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 iJe(){Hee();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=ke(l=>l.card.dataSource);return N.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function aJe(){const e=ee(n=>n.actions.setShowFilters),{hasEntities:t}=iJe();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(pZ,{})})]}),!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(TS,{collisionDetection:ES,children:c.jsx(RS,{items:[],strategy:BR,children:c.jsx(Vee,{context:"filter"})})})})]})}function lJe(){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(_R,{filter:r}),c.jsx(CS,{filter:r})]},r.id))}):null}function cJe(){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(lJe,{}),c.jsx(bee,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(aJe,{})})]})}const uJe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-CZkFeNrk.js"))),dJe=N.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-Cm5Mc4Um.js"))),fJe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-BlEVRs4V.js"))),hJe=N.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-CaktfbhQ.js")).then(e=>({default:e.ResourceManagementPanel})));function pJe({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(Sl,{FallbackComponent:hS,children:c.jsxs(H_,{dashboardProps:n,children:[c.jsx(ife,{}),c.jsx(AI,{children:c.jsxs(xee,{preferences:a,children:[o&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(fJe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(uJe,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(hJe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(QM,{...n,type:"dashboard",children:[s&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(dJe,{})}),c.jsx(cJe,{})]})})]})]})]})})]})})}var mJe=Object.defineProperty,gJe=(e,t,n)=>t in e?mJe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,by=(e,t,n)=>gJe(e,typeof t!="symbol"?t+"":t,n);const bJe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},xJe={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}},yJe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},vJe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},wJe={stringify:e=>e,parse:e=>e},ej={string:wJe,number:vJe,boolean:bJe,function:xJe,json:yJe};function SJe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const xy=Symbol.for("r2wc.render"),yy=Symbol.for("r2wc.connected"),xu=Symbol.for("r2wc.context"),Ta=Symbol.for("r2wc.props");function CJe(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=SJe(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(),by(this,o,!0),by(this,s),by(this,r,{}),by(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?ej[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[yy]=!0,this[xy]()}disconnectedCallback(){this[yy]=!1,this[xu]&&n.unmount(this[xu]),delete this[xu]}attributeChangedCallback(m,g,b){const x=f[m],y=l[x],v=y?ej[y]:null;x in l&&v!=null&&v.parse&&b&&(this[Ta][x]=v.parse(b,m,this),this[xy]())}[(o=yy,s=xu,r=Ta,xy)](){this[yy]&&(this[xu]?n.update(this[xu],this[Ta]):this[xu]=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?ej[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,m,this);this.getAttribute(m)!==y&&this.setAttribute(m,y)}else this[xy]()}})}return h}function NJe(e,t,n){const r=hj(e),s=N.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function jJe({root:e,ReactComponent:t},n){const r=N.createElement(t,n);e.render(r)}function kJe({root:e}){e.unmount()}function EJe(e,t={}){return CJe(e,t,{mount:NJe,update:jJe,unmount:kJe})}const _Je={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"},DJe=EJe(yee,{props:_Je});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 jL(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 kL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?jL(Object(n),!0).forEach(function(r){MJe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):jL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function TJe(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 RJe(e,t){if(e==null)return{};var n=TJe(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 IJe(e,t){return AJe(e)||PJe(e,t)||OJe(e,t)||FJe()}function AJe(e){if(Array.isArray(e))return e}function PJe(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 OJe(e,t){if(e){if(typeof e=="string")return EL(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 EL(e,t)}}function EL(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 FJe(){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 $Je(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _L(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 DL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?_L(Object(n),!0).forEach(function(r){$Je(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_L(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function LJe(){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 Gm(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 zw(e){return{}.toString.call(e).includes("Object")}function zJe(e){return!Object.keys(e).length}function Sb(e){return typeof e=="function"}function BJe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function VJe(e,t){return zw(t)||bc("changeType"),Object.keys(t).some(function(n){return!BJe(e,n)})&&bc("changeField"),t}function HJe(e){Sb(e)||bc("selectorType")}function UJe(e){Sb(e)||zw(e)||bc("handlerType"),zw(e)&&Object.values(e).some(function(t){return!Sb(t)})&&bc("handlersType")}function WJe(e){e||bc("initialIsRequired"),zw(e)||bc("initialType"),zJe(e)&&bc("initialContent")}function qJe(e,t){throw new Error(e[t]||e.default)}var YJe={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"},bc=Gm(qJe)(YJe),vy={changes:VJe,selector:HJe,handler:UJe,initial:WJe};function GJe(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};vy.initial(e),vy.handler(t);var n={current:e},r=Gm(XJe)(n,t),s=Gm(ZJe)(n),o=Gm(vy.changes)(e),i=Gm(KJe)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return vy.selector(u),u(n.current)}function l(u){LJe(r,s,o,i)(u)}return[a,l]}function KJe(e,t){return Sb(t)?t(e.current):t}function ZJe(e,t){return e.current=DL(DL({},e.current),t),t}function XJe(e,t,n){return Sb(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 QJe={create:GJe},JJe={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs"}};function eet(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 tet(e){return{}.toString.call(e).includes("Object")}function net(e){return e||ML("configIsRequired"),tet(e)||ML("configType"),e.urls?(ret(),{paths:{vs:e.urls.monacoBase}}):e}function ret(){console.warn(Uee.deprecation)}function set(e,t){throw new Error(e[t]||e.default)}var Uee={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
|
|