react-semaphor 0.1.280 → 0.1.281

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/dist/chunks/{dashboard-controls-Cm_n6Dce.js → dashboard-controls-CLd_NTpW.js} +1 -1
  2. package/dist/chunks/{dashboard-controls-I3SWzXID.js → dashboard-controls-D3R8Z79V.js} +4 -4
  3. package/dist/chunks/{dashboard-filter-controls-button-DXXJnFns.js → dashboard-filter-controls-button-DLjcoN1G.js} +1 -1
  4. package/dist/chunks/{dashboard-filter-controls-button-DuifafhB.js → dashboard-filter-controls-button-zj4HH2IS.js} +3 -3
  5. package/dist/chunks/{dashboard-json-C0_fJrmP.js → dashboard-json-BcdeYcFr.js} +1 -1
  6. package/dist/chunks/{dashboard-json--iZU90D2.js → dashboard-json-CPyonfsi.js} +1 -1
  7. package/dist/chunks/{dashboard-summary-settings-dialog-BzWnRhFU.js → dashboard-summary-settings-dialog-BYQfaQGZ.js} +1 -1
  8. package/dist/chunks/{dashboard-summary-settings-dialog-DOofgrKU.js → dashboard-summary-settings-dialog-Cpb9FCXf.js} +1 -1
  9. package/dist/chunks/{edit-dashboard-visual-CEb2cSMS.js → edit-dashboard-visual-CsTmOttj.js} +2 -2
  10. package/dist/chunks/{edit-dashboard-visual-DEuJScSB.js → edit-dashboard-visual-NyBBQhsY.js} +1 -1
  11. package/dist/chunks/{index-BzQ2UBDI.js → index-CsX3UmQg.js} +72 -68
  12. package/dist/chunks/{index-ZpmXTndp.js → index-DvAOngur.js} +2 -2
  13. package/dist/chunks/{resource-management-panel-DNez0W3b.js → resource-management-panel-BxJ99bHx.js} +2 -2
  14. package/dist/chunks/{resource-management-panel-DMHJbuqI.js → resource-management-panel-lglhpWpc.js} +1 -1
  15. package/dist/chunks/{use-create-flow-overlay-state-BvBTFIgX.js → use-create-flow-overlay-state-BjV5Q6Lb.js} +2 -2
  16. package/dist/chunks/{use-create-flow-overlay-state-BdoJfJmU.js → use-create-flow-overlay-state-BrmQZdh2.js} +1 -1
  17. package/dist/chunks/{use-visual-utils-D4Lp-wat.js → use-visual-utils-C54WwvId.js} +1 -1
  18. package/dist/chunks/{use-visual-utils-C2syL_qa.js → use-visual-utils-C7wVd3rs.js} +1 -1
  19. package/dist/dashboard/index.cjs +1 -1
  20. package/dist/dashboard/index.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +5 -5
  23. package/dist/style.css +1 -1
  24. package/dist/surfboard/index.cjs +1 -1
  25. package/dist/surfboard/index.js +2 -2
  26. package/package.json +1 -1
@@ -1299,7 +1299,7 @@ Defaulting to \`null\`.`}var ure=ire,A7e=lre;const sE=F.forwardRef(({className:e
1299
1299
  </html>`}function xre({rendererCode:e,title:t,payload:n,className:r,layoutMode:s="content",disablePointerEvents:o=!1,onRuntimeError:i}){var y;const[a,c]=w.useState(!1),[u,d]=w.useState(xUe),[f,h]=w.useState(!1),m=w.useRef(null),p=w.useMemo(()=>`dynamic-visual-${Math.random().toString(36).slice(2)}`,[]),g=w.useMemo(()=>wUe(p),[p]),b=w.useMemo(()=>`dynamic-visual-shell-${e}`,[e]),x=(y=n.metadata)==null?void 0:y.artifactId;return w.useEffect(()=>{h(!1)},[e]),w.useEffect(()=>{a&&h(!1),c(!1)},[x,a,e]),w.useEffect(()=>{function v(C){var N;const S=C.data;if(!(!S||C.source!==((N=m.current)==null?void 0:N.contentWindow)||S.frameId!==p)){if(S.type==="semaphor-dynamic-visual-ready"){h(!0);return}if(S.type==="semaphor-dynamic-visual-height"&&typeof S.height=="number"&&s==="content"){const j=Math.max(yUe,Math.ceil(S.height));d(k=>k===j?k:j);return}S.type==="semaphor-dynamic-visual-error"&&(c(!0),i==null||i(typeof S.message=="string"?S.message:"runtime-error"))}}return window.addEventListener("message",v),()=>window.removeEventListener("message",v)},[p,s,i]),w.useEffect(()=>{var v;!f||!((v=m.current)!=null&&v.contentWindow)||m.current.contentWindow.postMessage({type:"semaphor-dynamic-visual-render",frameId:p,rendererCode:e,payload:n},"*")},[p,n,e,f]),a?l.jsx("div",{className:Q("flex items-center justify-center rounded-md border border-dashed border-border/60 bg-muted/20 p-4 text-sm text-muted-foreground",s==="fill"?"h-full min-h-0":"min-h-[360px]"),children:"The dynamic visual could not be rendered in the iframe host."}):l.jsx("div",{className:Q("relative overflow-hidden rounded-md bg-background",s==="fill"?"h-full min-h-0":"min-h-[360px]",r),children:l.jsx("iframe",{ref:m,title:t,className:Q("block w-full border-0 bg-transparent",s==="fill"&&"h-full min-h-0",o&&"pointer-events-none"),sandbox:"allow-scripts",scrolling:s==="fill"?"auto":"no",srcDoc:g,loading:"lazy",style:{height:s==="fill"?"100%":`${u}px`},onLoad:()=>{h(!0)},onError:()=>{c(!0),i==null||i("iframe-load-error")}},b)})}function Sb(e,t,n){const r=e.getPropertyValue(t).trim();return r?`hsl(${r})`:n}function LO(){if(typeof document>"u")return{mode:"light",background:"hsl(0 0% 100%)",foreground:"hsl(240 10% 3.9%)",muted:"hsl(240 3.8% 46.1%)",border:"hsl(240 5.9% 90%)",accent:"hsl(240 5.9% 10%)"};const e=document.documentElement,t=window.getComputedStyle(e);return{mode:e.classList.contains("dark")?"dark":"light",background:Sb(t,"--semaphor-background","hsl(0 0% 100%)"),foreground:Sb(t,"--semaphor-foreground","hsl(240 10% 3.9%)"),muted:Sb(t,"--semaphor-muted-foreground","hsl(240 3.8% 46.1%)"),border:Sb(t,"--semaphor-border","hsl(240 5.9% 90%)"),accent:Sb(t,"--semaphor-primary","hsl(240 5.9% 10%)")}}function aE({card:e,records:t,sql:n,python:r,title:s,fallback:o,className:i,showFallbackBadge:a=!0,layoutMode:c="content",disablePointerEvents:u=!1}){var N,j,k,T,E;const[d,f]=w.useState(!1),[h,m]=w.useState(null),[p,g]=w.useState(null),b=lN((N=e.dynamicCardPreferences)==null?void 0:N.rendererCode),x=Qd(t||[],MZ),y=Qd(LO()),v=w.useMemo(()=>{var _,M,P;return{records:x,title:s||((_=e.dynamicCardPreferences)==null?void 0:_.title)||e.title,theme:y,metadata:{provenance:(M=e.dynamicCardPreferences)==null?void 0:M.provenance,sql:n,python:r,cardConfig:e.config,rowCount:x.length,artifactId:(P=e.dynamicCardPreferences)==null?void 0:P.artifactId}}},[e.config,(j=e.dynamicCardPreferences)==null?void 0:j.artifactId,(k=e.dynamicCardPreferences)==null?void 0:k.provenance,(T=e.dynamicCardPreferences)==null?void 0:T.title,e.title,y,r,x,n,s]),C=w.useMemo(()=>{var _;return[((_=e.dynamicCardPreferences)==null?void 0:_.artifactId)||"no-artifact",b||"no-renderer",Ahe(v)].join("::")},[(E=e.dynamicCardPreferences)==null?void 0:E.artifactId,v,b]);w.useEffect(()=>{d&&C&&C!==p&&(f(!1),m(null))},[C,p,d]);const S=d||!b;return l.jsx("div",{className:Q("relative h-full w-full",c==="fill"&&"min-h-0 overflow-hidden",i),children:S?l.jsxs(l.Fragment,{children:[a&&l.jsxs("div",{className:"absolute right-3 top-3 z-10 inline-flex items-center gap-1 rounded-full border border-amber-500/30 bg-amber-50/95 px-2.5 py-1 text-[11px] font-medium text-amber-900 shadow-sm",title:h||void 0,children:[l.jsx(Ih,{className:"h-3 w-3"}),"Showing fallback visual"]}),o]}):l.jsx(xre,{rendererCode:b,title:v.title||e.title,payload:v,layoutMode:c,disablePointerEvents:u,onRuntimeError:_=>{g(C),m(_||"runtime-error"),f(!0)}})})}function CUe({isOpen:e,onClose:t,frame:n,card:r,data:s}){var M;const[o,i]=w.useState(!1),a=ee(P=>P.isDownloadingPdf),c=ee(P=>P.themeStyle),u=r&&fl(r)==="dynamic"?Wx(r):r,{isError:d,isLoading:f,isFetching:h,data:m,handleDatapointClick:p,pagination:g,comparisonMetadata:b}=z0(r),{customCards:x,placeholders:y}=rt(),{data:v}=$0(u||r),C=Ig(u||r,m),S=w.useMemo(()=>(m==null?void 0:m.records)||[],[m==null?void 0:m.records]),N=w.useMemo(()=>{var P;if(!(!u||!((P=m==null?void 0:m.records)!=null&&P.length)||["kpi","text","table","detailTable","pivotTable","aggregateTable","custom"].includes(u.type)))return xg({card:u,data:m.records,cardType:u.type,queryConfig:u.queryConfig,customCfg:u.customCfg,preferences:u.preferences,topoJson:v})},[m==null?void 0:m.records,u,v,c]),j=()=>{var D,A,L,$,B,V,R;const P=m||s;if(P!=null&&P.records&&P.records.length>0)if((r==null?void 0:r.type)==="aggregateTable"){const U=P.records.find(W=>W.isGrandTotal),O=P.records.filter(W=>!W.isGrandTotal),I=KJ(O,U,P.groupByColumns||[],P.pivotSchema||[],r,(A=(D=r==null?void 0:r.preferences)==null?void 0:D.tablePrefs)==null?void 0:A.columnSettingsMap);nS(I,`${(r==null?void 0:r.title)||"export"}.csv`)}else if((r==null?void 0:r.type)==="pivotTable"&&C)tee(C.data,r,`${(r==null?void 0:r.title)||"export"}.csv`,{includeHeaders:!0,includeSubtotals:!0,includeGrandTotal:!0,showRowTotals:(L=C.options)==null?void 0:L.showRowTotals});else if((r==null?void 0:r.type)==="table"||(r==null?void 0:r.type)==="detailTable"){const U=((B=($=r==null?void 0:r.preferences)==null?void 0:$.tablePrefs)==null?void 0:B.columnSettingsMap)||{},O=((R=(V=r==null?void 0:r.preferences)==null?void 0:V.tablePrefs)==null?void 0:R.columnVisibility)||{},W=Object.keys(P.records[0]||{}).filter(X=>O[X]!==!1);tOe(P.records,U,W,`${(r==null?void 0:r.title)||"export"}.csv`,void 0,Intl.DateTimeFormat().resolvedOptions().timeZone,!!(r!=null&&r.sql),r)}else{const U=[],O=Object.keys(P.records[0]);U.push(O.join(","));for(const W of P.records){const X=O.map(Z=>`"${(""+W[Z]).replace(/"/g,'""')}"`);U.push(X.join(","))}const I=U.join(`
1300
1300
  `);nS(I,`${(r==null?void 0:r.title)||"export"}.csv`)}},k=()=>{i(!0)},T=(r==null?void 0:r.type)==="table"||(r==null?void 0:r.type)==="aggregateTable"||(r==null?void 0:r.type)==="detailTable",E=((M=r==null?void 0:r.preferences)==null?void 0:M.allowDownload)!==!1,_=()=>{if(!r)return null;const P=r,D=fl(P)==="dynamic"?Wx(P):P;if(d)return l.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[l.jsx(GA,{className:"size-8 text-destructive"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Error fetching data. Check your card settings."})]});if(f||h)return l.jsx("div",{className:"flex h-full w-full items-center justify-center",children:l.jsx(ad,{size:"md",color:"muted","aria-label":"Loading data"})});if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&fl(P)!=="dynamic")return y!=null&&y.NoRecords?l.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:y.NoRecords}):l.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[l.jsx(JA,{className:"size-8 text-muted-foreground"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});function A(){var L;if(D.type==="kpi")return l.jsx("div",{className:"flex h-full items-center justify-center",children:l.jsx("div",{className:"w-full max-w-xl rounded-md border border-border",children:l.jsx(ph,{card:D,data:(m==null?void 0:m.records)||[],isPending:f||h,isError:d,comparisonMetadata:b})})});if(D.type==="table"||D.type==="detailTable")return l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(hh,{card:D,data:S,comparisonMetadata:b,paginationMetadata:g,onPaginationChange:()=>{},isLoading:f||h})});if(D.type==="pivotTable"&&C)return l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(dv,{card:D,data:C.data,options:C.options,onAggregationChange:()=>{},onAggregationLabelChange:()=>{}})});if(D.type==="aggregateTable")return l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(Yj,{card:D,data:(m==null?void 0:m.records)||[],groupByColumns:m==null?void 0:m.groupByColumns,pivotSchema:m==null?void 0:m.pivotSchema,paginationMetadata:g,onPaginationChange:()=>{},onAggregationChange:()=>{},isLoading:f||h})});if(D.type==="text")return l.jsx(Fo,{className:"overflow-y-auto break-words pr-2",children:l.jsx($p,{isLoading:f||h,card:D,data:(m==null?void 0:m.records)||[]})});if(aN(D)&&((L=D.customCardPreferences)!=null&&L.url))return l.jsx(Ra,{FallbackComponent:My,children:l.jsx(mS,{frame:n,card:D})});if(N)return l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(ev,{cfg:N,onChartClick:()=>{},onDatapointClick:p})});if(x&&x.length>0){const $=x.find(B=>B.cardId===D.id);if($&&$.content){const B=$.content;return l.jsx(B,{card:D})}}return null}return fl(P)==="dynamic"?l.jsx(aE,{card:P,records:S,title:P.title,sql:P.sql,python:P.python,layoutMode:"fill",fallback:A()}):A()};return l.jsxs(l.Fragment,{children:[l.jsx(zr,{open:e,onOpenChange:t,children:l.jsxs(Tr,{className:"flex h-[80vh] w-[80vw] max-w-[80vw] flex-col gap-0 p-0 [&>button]:hidden",children:[l.jsxs(_r,{className:"shrink-0 border-b px-6 py-4",children:[l.jsx(Ir,{className:"text-lg font-semibold",children:(r==null?void 0:r.title)||"Visual"}),l.jsxs(ss,{className:"sr-only",children:["Expanded view of ",(r==null?void 0:r.title)||"visual"," card showing detailed data and export options"]})]}),l.jsxs("div",{className:"flex items-center gap-2 border-b px-6 py-3",children:[E&&l.jsxs(re,{variant:"ghost",size:"sm",onClick:j,title:"Download CSV",children:[l.jsx(ka,{className:"mr-2 h-4 w-4"}),"CSV"]}),T&&l.jsxs(re,{variant:"ghost",size:"sm",onClick:k,disabled:a,title:"Download PDF",children:[l.jsx(Th,{className:"mr-2 h-4 w-4"}),"PDF"]}),l.jsx(re,{variant:"ghost",size:"icon",onClick:t,className:"ml-auto h-8 w-8",children:l.jsx(Mt,{className:"h-4 w-4"})})]}),l.jsx("div",{className:"flex flex-1 overflow-hidden p-6",children:_()})]})}),o&&l.jsx(FP,{isOpen:o,onClose:()=>i(!1),frame:n,card:r,data:m||s})]})}function SUe(e,t){return`legacy_${e.mode||"interaction"}_${t}`}function W8(e,t){if(e)return e.map(n=>t.get(n)||n)}function q8(e,t){return!e&&!t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Gd(e){return(e||[]).map((t,n)=>({...t,id:t.id||SUe(t,n)}))}function P1(e,t){return e.map(n=>n.mode!=="clickFilter"?n:{...n,applyToCardIds:W8(n.applyToCardIds,t),excludeCardIds:W8(n.excludeCardIds,t)})}function lT(e,t){return t?e.map(n=>{if(n.mode!=="clickFilter"||!n.id)return n;const r=t[n.id];if(!r)return n;const s=Object.prototype.hasOwnProperty.call(r,"applyToCardIds"),o=Object.prototype.hasOwnProperty.call(r,"excludeCardIds");return{...n,...s?{applyToCardIds:r.applyToCardIds===null?void 0:r.applyToCardIds}:{},...o?{excludeCardIds:r.excludeCardIds===null?void 0:r.excludeCardIds}:{}}}):e}function Y8(e,t){if(!e)return;const n=new Set(t),r={};return Object.entries(e).forEach(([s,o])=>{if(!n.has(s))return;const i=Object.prototype.hasOwnProperty.call(o,"applyToCardIds"),a=Object.prototype.hasOwnProperty.call(o,"excludeCardIds");!i&&!a||(r[s]=o)}),Object.keys(r).length>0?r:void 0}function NUe(e,t){const n=new Map(t.filter(r=>r.id).map(r=>[r.id,r]));return e.map(r=>{if(r.mode!=="clickFilter"||!r.id)return r;const s=n.get(r.id);return!s||s.mode!=="clickFilter"?{...r,applyToCardIds:void 0,excludeCardIds:void 0}:{...r,applyToCardIds:s.applyToCardIds,excludeCardIds:s.excludeCardIds}})}function jUe(e,t){const n=new Map(t.filter(s=>s.id).map(s=>[s.id,s])),r={};return e.forEach(s=>{if(s.mode!=="clickFilter"||!s.id)return;const o=n.get(s.id),i=o&&o.mode==="clickFilter"?o.applyToCardIds:void 0,a=o&&o.mode==="clickFilter"?o.excludeCardIds:void 0,c=!q8(s.applyToCardIds,i),u=!q8(s.excludeCardIds,a);if(!c&&!u)return;const d={};c&&(d.applyToCardIds=s.applyToCardIds===void 0?null:s.applyToCardIds),u&&(d.excludeCardIds=s.excludeCardIds===void 0?null:s.excludeCardIds),r[s.id]=d}),r}function EUe(){return{id:wr()}}function yre(e){var o;const t=e.activeCardId,n=new Map,r=e.cards.map(i=>{const a=i.id,c=wr();return n.set(a,c),{...i,id:c}});let s=(o=r[0])==null?void 0:o.id;return t&&n.has(t)&&(s=n.get(t)),{...e,id:wr(),cards:r,activeCardId:s}}function kUe(e){var i;const t=new Map,n=e.activeCardId,s=e.cards.map(a=>{const c=wr();return t.set(a.id,c),{...a,id:c,linkedSourceCardId:a.id,linkedInteractionTargetOverrides:void 0}}).map(a=>{var d;const c=Gd((d=a.interactionConfig)==null?void 0:d.interactions),u=P1(c,t);return{...a,interactionConfig:{...a.interactionConfig,interactions:u}}}),o=n&&t.get(n)||((i=s[0])==null?void 0:i.id);return{...e,id:wr(),cards:s,activeCardId:o}}function TUe({emails:e,onChange:t}){const[n,r]=w.useState(""),[s,o]=w.useState(null),i=d=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d),a=()=>{if(o(null),!n.trim()){o("Please enter at least one email address");return}const d=n.split(/[,;]/).map(m=>m.trim()).filter(m=>m),f=d.filter(m=>!i(m));if(f.length>0){o(`Invalid email${f.length>1?"s":""}: ${f.join(", ")}`);return}const h=d.filter(m=>!e.includes(m));if(h.length===0){o("Email address already added");return}t([...e,...h]),r("")},c=d=>{t(e.filter(f=>f!==d))},u=d=>{d.key==="Enter"&&(d.preventDefault(),a())};return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex gap-2",children:[l.jsx(lt,{type:"text",placeholder:"email@company.com, team@company.com",value:n,onChange:d=>{r(d.target.value),o(null)},onKeyPress:u,className:Q(s&&"border-destructive")}),l.jsxs(re,{type:"button",size:"sm",onClick:a,disabled:!n.trim(),children:[l.jsx($r,{className:"h-4 w-4 mr-1"}),"Add"]})]}),s&&l.jsxs("div",{className:"flex items-center gap-2 text-sm text-destructive",children:[l.jsx($c,{className:"h-4 w-4"}),s]}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Enter email addresses for external recipients. Separate multiple emails with commas."})]}),e.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"text-sm font-medium",children:["Added Emails (",e.length,")"]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(d=>l.jsxs(Xe,{variant:"secondary",className:"pl-3 pr-1 py-1 flex items-center gap-1",children:[l.jsx("span",{className:"text-xs",children:d}),l.jsx("button",{type:"button",onClick:()=>c(d),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:l.jsx(Mt,{className:"h-3 w-3"})})]},d))})]})]})}function vre({audienceType:e,viewerType:t,mode:n="scope-aware",className:r}){const s=SMe(e,{viewerType:t,mode:n});return s?l.jsx(Xe,{variant:"outline",className:r,children:s}):null}function _Ue({tenantUserIds:e,orgUserIds:t,onChangeTenantUsers:n,onChangeOrgUsers:r}){const[s,o]=w.useState(""),[i,a]=w.useState("");w.useEffect(()=>{const x=setTimeout(()=>{a(s)},300);return()=>clearTimeout(x)},[s]);const{users:c,userContext:u,isLoading:d,error:f}=WF({search:i,limit:50}),h=new Set([...e,...t]),m=c.map(x=>({id:x.id,name:x.name,email:x.email,type:x.type})),p=m.filter(x=>h.has(x.id)),g=x=>{const y=h.has(x.id);x.type==="tenant"?n(y?e.filter(v=>v!==x.id):[...e,x.id]):x.type==="organization"&&r(y?t.filter(v=>v!==x.id):[...t,x.id])},b=(x,y)=>{y==="tenant"?n(e.filter(v=>v!==x)):y==="organization"&&r(t.filter(v=>v!==x))};return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"relative",children:[l.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),l.jsx(lt,{type:"text",placeholder:"Search users by name or email...",value:s,onChange:x=>o(x.target.value),className:"pl-9"})]}),h.size>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"text-sm font-medium",children:["Selected Users (",h.size,")"]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:p.map(x=>l.jsxs(Xe,{variant:"secondary",className:"pl-2 pr-1 py-1 flex items-center gap-1",children:[x.type==="organization"?l.jsx(Lc,{className:"h-3 w-3"}):l.jsx(zc,{className:"h-3 w-3"}),l.jsx("span",{className:"text-xs",children:x.name}),l.jsx("button",{type:"button",onClick:()=>b(x.id,x.type),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:l.jsx(Mt,{className:"h-3 w-3"})})]},x.id))})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm text-muted-foreground",children:s?"Search Results":"Available Users"}),d?l.jsx("div",{className:"flex items-center justify-center py-8",children:l.jsx(Mn,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):f?l.jsx("div",{className:"text-sm text-destructive py-4 text-center",children:"Failed to load users. Please try again."}):m.length===0?l.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center",children:s?"No users found":"No users available"}):l.jsx(Fo,{className:"h-[300px] rounded-md border p-2",children:l.jsx("div",{className:"space-y-1",children:m.map(x=>{const y=h.has(x.id);return l.jsxs("div",{className:Q("flex items-center gap-3 rounded-md p-2 hover:bg-muted/50 cursor-pointer",y&&"bg-primary/10"),onClick:()=>g(x),children:[l.jsx(Jt,{checked:y,onCheckedChange:()=>g(x),onClick:v=>v.stopPropagation()}),l.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[x.type==="organization"?l.jsx(Lc,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}):l.jsx(zc,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm font-medium truncate",children:x.name}),l.jsx("div",{className:"text-xs text-muted-foreground truncate",children:x.email})]}),l.jsx(vre,{audienceType:x.type,viewerType:u==null?void 0:u.type,className:"text-xs"})]})]},x.id)})})})]})]})}function IUe({groupIds:e,onChange:t}){const[n,r]=w.useState(""),{currentUser:s}=Lo(),{groups:o,isLoading:i,error:a}=qF({search:n,type:"all",limit:50}),c=o.filter(m=>(s==null?void 0:s.type)==="organization"?!0:(s==null?void 0:s.type)==="tenant"?m.type==="TENANT_GROUP"&&m.tenantId===s.tenantId:!1).map(m=>({id:m.id,name:m.name,description:m.description,type:m.type,memberCount:m.memberCount})),u=c.filter(m=>m.name.toLowerCase().includes(n.toLowerCase())||m.description&&m.description.toLowerCase().includes(n.toLowerCase())),d=c.filter(m=>e.includes(m.id)),f=m=>{e.includes(m)?t(e.filter(p=>p!==m)):t([...e,m])},h=m=>{t(e.filter(p=>p!==m))};return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"relative",children:[l.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),l.jsx(lt,{type:"text",placeholder:"Search groups by name...",value:n,onChange:m=>r(m.target.value),className:"pl-9"})]}),d.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",d.length,")"]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:d.map(m=>l.jsxs(Xe,{variant:"secondary",className:"pl-2 pr-1 py-1 flex items-center gap-1",children:[m.type==="ORG_GROUP"?l.jsx(Lc,{className:"h-3 w-3"}):l.jsx(ps,{className:"h-3 w-3"}),l.jsx("span",{className:"text-xs",children:m.name}),m.memberCount!==void 0&&l.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",m.memberCount,")"]}),l.jsx("button",{type:"button",onClick:()=>h(m.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:l.jsx(Mt,{className:"h-3 w-3"})})]},m.id))})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm text-muted-foreground",children:n?"Search Results":"Available Groups"}),i?l.jsx("div",{className:"flex items-center justify-center py-8",children:l.jsx(Mn,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):a?l.jsx("div",{className:"text-sm text-destructive py-4 text-center",children:"Failed to load groups. Please try again."}):u.length===0?l.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center",children:n?"No groups found":"No groups available"}):l.jsx(Fo,{className:"h-[300px] rounded-md border p-2",children:l.jsx("div",{className:"space-y-1",children:u.map(m=>{const p=e.includes(m.id);return l.jsxs("div",{className:Q("flex items-center gap-3 rounded-md p-2 hover:bg-muted/50 cursor-pointer",p&&"bg-primary/10"),onClick:()=>f(m.id),children:[l.jsx(Jt,{checked:p,onCheckedChange:()=>f(m.id),onClick:g=>g.stopPropagation()}),l.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[m.type==="ORG_GROUP"?l.jsx(Lc,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}):l.jsx(ps,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm font-medium truncate",children:m.name}),m.description&&l.jsx("div",{className:"text-xs text-muted-foreground truncate",children:m.description})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[m.memberCount!==void 0&&l.jsxs(Xe,{variant:"outline",className:"text-xs",children:[m.memberCount," members"]}),l.jsx(vre,{audienceType:m.type==="ORG_GROUP"?"organization":"tenant",viewerType:s==null?void 0:s.type,className:"text-xs"})]})]})]},m.id)})})})]})]})}const wre=w.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},s)=>l.jsx(Ph,{ref:s,align:t,sideOffset:n,className:Q("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}));wre.displayName=Ph.displayName;function MUe({value:e,onChange:t,className:n,triggerAccessory:r}){const[s,o]=w.useState(!1),[i,a]=w.useState("emails"),c=e.emails.length+e.tenantUserIds.length+e.orgUserIds.length+e.groupIds.length,u=e.tenantUserIds.length+e.orgUserIds.length,d=m=>{t({...e,...m})},f=(m,p)=>{switch(p){case"email":d({emails:e.emails.filter(g=>g!==m)});break;case"tenantUser":d({tenantUserIds:e.tenantUserIds.filter(g=>g!==m)});break;case"orgUser":d({orgUserIds:e.orgUserIds.filter(g=>g!==m)});break;case"group":d({groupIds:e.groupIds.filter(g=>g!==m)});break}},h=()=>{const m=[];e.emails.length>0&&m.push(`${e.emails.length} email${e.emails.length!==1?"s":""}`);const p=e.tenantUserIds.length+e.orgUserIds.length;return p>0&&m.push(`${p} user${p!==1?"s":""}`),e.groupIds.length>0&&m.push(`${e.groupIds.length} group${e.groupIds.length!==1?"s":""}`),m.join(", ")};return l.jsxs("div",{className:Q("space-y-1.5",n),children:[l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsxs(Gr,{open:s,onOpenChange:o,modal:!0,children:[l.jsx(Kr,{asChild:!0,children:l.jsxs(re,{variant:"outline",size:"sm",className:"w-full justify-start",children:[l.jsx(KU,{className:"mr-2 h-4 w-4"}),c>0?l.jsxs("span",{children:["Add more recipients (",h(),")"]}):"Add recipients"]})}),l.jsx(wre,{className:"z-[51] w-[500px] p-0",align:"start",side:"bottom",sideOffset:4,children:l.jsxs("div",{className:"p-4",children:[l.jsxs("div",{className:"mb-4",children:[l.jsx("h4",{className:"text-sm font-medium",children:"Select Recipients"}),l.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Choose who should receive the scheduled reports"})]}),l.jsxs(As,{value:i,onValueChange:m=>a(m),children:[l.jsxs(ys,{className:"grid w-full grid-cols-3",children:[l.jsxs(on,{value:"emails",className:"flex items-center gap-2 text-xs",children:[l.jsx(Q_,{className:"h-3 w-3"}),l.jsx("span",{children:"Emails"}),e.emails.length>0&&l.jsx(Xe,{variant:"secondary",className:"ml-1 h-4 px-1 text-xs",children:e.emails.length})]}),l.jsxs(on,{value:"users",className:"flex items-center gap-2 text-xs",children:[l.jsx(ps,{className:"h-3 w-3"}),l.jsx("span",{children:"Users"}),e.tenantUserIds.length+e.orgUserIds.length>0&&l.jsx(Xe,{variant:"secondary",className:"ml-1 h-4 px-1 text-xs",children:e.tenantUserIds.length+e.orgUserIds.length})]}),l.jsxs(on,{value:"groups",className:"flex items-center gap-2 text-xs",children:[l.jsx(h3,{className:"h-3 w-3"}),l.jsx("span",{children:"Groups"}),e.groupIds.length>0&&l.jsx(Xe,{variant:"secondary",className:"ml-1 h-4 px-1 text-xs",children:e.groupIds.length})]})]}),l.jsxs("div",{className:"mt-4 max-h-[300px] overflow-y-auto",children:[l.jsx(sr,{value:"emails",className:"mt-0",children:l.jsx(TUe,{emails:e.emails,onChange:m=>d({emails:m})})}),l.jsx(sr,{value:"users",className:"mt-0",children:l.jsx(_Ue,{tenantUserIds:e.tenantUserIds,orgUserIds:e.orgUserIds,onChangeTenantUsers:m=>d({tenantUserIds:m}),onChangeOrgUsers:m=>d({orgUserIds:m})})}),l.jsx(sr,{value:"groups",className:"mt-0",children:l.jsx(IUe,{groupIds:e.groupIds,onChange:m=>d({groupIds:m})})})]})]}),l.jsx("div",{className:"mt-4 border-t pt-4",children:l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("p",{className:"text-xs text-muted-foreground",children:c>0?`${c} recipient${c!==1?"s":""} selected`:"No recipients selected"}),l.jsx(re,{size:"sm",onClick:()=>o(!1),className:"h-7",children:"Done"})]})})]})})]}),r&&l.jsx("div",{className:"shrink-0",children:r})]}),c>0&&l.jsx("div",{className:"space-y-1",children:l.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.emails.map(m=>l.jsxs(Xe,{variant:"outline",className:"gap-1 border-dashed pr-1 text-muted-foreground",children:[l.jsx(Q_,{className:"h-3 w-3"}),l.jsx("span",{className:"max-w-[150px] truncate text-xs",children:m}),l.jsx("button",{onClick:p=>{p.stopPropagation(),f(m,"email")},className:"ml-1 rounded-sm hover:bg-secondary-foreground/20",children:l.jsx(Mt,{className:"h-3 w-3"})})]},m)),u>0&&l.jsxs(Xe,{variant:"outline",className:"gap-1 border-dashed text-muted-foreground",children:[l.jsx(ps,{className:"h-3 w-3"}),u," user",u!==1?"s":""]}),e.groupIds.length>0&&l.jsxs(Xe,{variant:"outline",className:"gap-1 border-dashed text-muted-foreground",children:[l.jsx(h3,{className:"h-3 w-3"}),e.groupIds.length," group",e.groupIds.length!==1?"s":""]})]})})]})}var Cre={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},G8=w.createContext&&w.createContext(Cre),DUe=["attr","size","title"];function AUe(e,t){if(e==null)return{};var n=RUe(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 RUe(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 yS(){return yS=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},yS.apply(this,arguments)}function K8(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 vS(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?K8(Object(n),!0).forEach(function(r){FUe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):K8(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function FUe(e,t,n){return t=PUe(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function PUe(e){var t=OUe(e,"string");return typeof t=="symbol"?t:t+""}function OUe(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 Sre(e){return e&&e.map((t,n)=>w.createElement(t.tag,vS({key:n},t.attr),Sre(t.child)))}function Bh(e){return t=>w.createElement(LUe,yS({attr:vS({},e.attr)},t),Sre(e.child))}function LUe(e){var t=n=>{var{attr:r,size:s,title:o}=e,i=AUe(e,DUe),a=s||n.size||"1em",c;return n.className&&(c=n.className),e.className&&(c=(c?c+" ":"")+e.className),w.createElement("svg",yS({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,i,{className:c,style:vS(vS({color:e.color||n.color},n.style),e.style),height:a,width:a,xmlns:"http://www.w3.org/2000/svg"}),o&&w.createElement("title",null,o),e.children)};return G8!==void 0?w.createElement(G8.Consumer,null,n=>t(n)):t(Cre)}function Nre(e){return Bh({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 jre(e){return Bh({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 $O(e){return Bh({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 lE(e){return Bh({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 Ere(e){return Bh({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 zO(e){return Bh({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 cE(e){return l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 48 48",...e,children:l.jsxs("g",{stroke:"currentColor",strokeWidth:"3.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none",children:[l.jsx("line",{x1:"12",y1:"6",x2:"12",y2:"42"}),l.jsx("line",{x1:"12",y1:"12",x2:"32",y2:"12"}),l.jsx("line",{x1:"12",y1:"24",x2:"32",y2:"24"}),l.jsx("line",{x1:"12",y1:"36",x2:"32",y2:"36"}),l.jsx("line",{x1:"42",y1:"9",x2:"42",y2:"15"}),l.jsx("line",{x1:"44",y1:"21",x2:"44",y2:"27"}),l.jsx("line",{x1:"42",y1:"33",x2:"42",y2:"39"})]})})}const uE=[{id:"tableBuilder",icon:_pe,label:"Table Builder"},{id:"table",icon:Om,label:"Table"},{id:"detailTable",icon:UA,label:"Detail Table"},{id:"pivotTable",icon:Om,label:"Pivot Table"},{id:"aggregateTable",icon:Om,label:"Aggregate Table"},{id:"bar",icon:dN,label:"Bar Chart"},{id:"line",icon:p0,label:"Line Chart"},{id:"area",icon:K_,label:"Area Chart"},{id:"stackedArea",icon:K_,label:"Stacked Area Chart"},{id:"stackedBar",icon:RA,label:"Stacked Bar Chart"},{id:"combo",icon:DU,label:"Combo Chart"},{id:"stackedLine",icon:Ere,label:"Stacked Line Chart"},{id:"scatter",icon:OA,label:"Scatter Chart"},{id:"bubble",icon:jre,label:"Bubble Chart"},{id:"pie",icon:PA,label:"Pie Chart"},{id:"doughnut",icon:zA,label:"Doughnut Chart"},{id:"funnel",icon:$O,label:"Funnel Chart"},{id:"radar",icon:HU,label:"Radar Chart"},{id:"polarArea",icon:Nre,label:"Polar Area Chart"},{id:"tornado",icon:QA,label:"Tornado Chart"},{id:"range",icon:FA,label:"Range Chart"},{id:"bullet",icon:cE,label:"Bullet Chart"},{id:"treemap",icon:lE,label:"Treemap"},{id:"heatmap",icon:gN,label:"Heatmap"},{id:"kpi",icon:zO,label:"KPI"},{id:"text",icon:_U,label:"Text"},{id:"map",icon:BU,label:"Map"}],kre=e=>{const t=e.toLowerCase();for(const n of uE)if(n.id==="doughnut"){if(t.includes("doughnut")||t.includes("donut")){const r=n.icon;return w.createElement(r,{className:"h-4 w-4"})}}else if(t.includes(n.id.toLowerCase())){const r=n.icon;return w.createElement(r,{className:"h-4 w-4"})}return null},VO=(e,t="h-4 w-4")=>{const n=uE.find(r=>r.id===e);if(n){const r=n.icon;return w.createElement(r,{className:t})}return w.createElement(DU,{className:t})};function $Ue({open:e,onOpenChange:t,dashboardId:n,onSelect:r,existingAttachments:s}){const[o,i]=w.useState(new Map),a=ee(g=>g.dashboard),c=w.useMemo(()=>(a==null?void 0:a.sheets)||[],[a]),u=ee(g=>g.selectedSheetId),d=c.find(g=>g.id===u),f=w.useMemo(()=>{var b;const g=[];if(g.push({id:"dashboard-full",title:`${(a==null?void 0:a.title)||"Dashboard"} (All Sheets)`,type:"dashboard",icon:l.jsx(X_,{className:"h-4 w-4"}),supportedFormats:["pdf"]}),c.length>1&&d&&g.push({id:`dashboard-${d.id}`,title:`${(a==null?void 0:a.title)||"Dashboard"} (${d.title})`,type:"dashboard",icon:l.jsx(ka,{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(C=>{if(C.type==="text")return;const S=VO(C.type),N=AP(C.type);x.push({id:C.id,title:C.title||`${C.type} Chart`,type:"visual",visualId:C.id,cardType:C.type,icon:S,supportedFormats:N})})}),g.push(...x)}return g},[a,c,d]);w.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,C;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((C=b.settings)!=null&&C.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=RP(g.cardType):x=g.supportedFormats.includes("csv")?"csv":"pdf",b.set(g.id,{item:g,format:x})}i(b)},m=(g,b)=>{const x=o.get(g);if(x){const y=new Map(o);y.set(g,{...x,format:b}),i(y)}},p=()=>{const g=[];o.forEach(({item:b,format:x})=>{const y={type:b.type,visualId:b.visualId,cardType:b.cardType,title:b.title,format:x,supportedFormats:b.supportedFormats,settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0}};b.type==="dashboard"&&(b.id==="dashboard-full"?y.settings.sheetSelection="all":d&&(y.settings.sheetSelection="current",y.settings.currentSheetId=d.id,y.settings.currentSheetName=d.title)),x==="csv"&&(y.settings.delimiter=",",y.settings.includeHeaders=!0,y.settings.useFormattedValues=!0),g.push(y)}),r(g),t(!1)};return l.jsx(zr,{open:e,onOpenChange:t,children:l.jsxs(Tr,{className:"max-w-2xl",children:[l.jsx(_r,{children:l.jsx(Ir,{children:"Select Attachment"})}),l.jsx("div",{className:"space-y-4",children:l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx(ge,{children:"Select items to attach:"}),o.size>0&&l.jsxs("span",{className:"text-sm text-muted-foreground",children:[o.size," selected"]})]}),l.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 l.jsxs("div",{className:Q("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:[l.jsx(Jt,{checked:b,onCheckedChange:()=>h(g)}),l.jsx("div",{className:"flex-shrink-0",children:g.icon}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-sm font-medium",children:g.title}),l.jsx("div",{className:"text-xs text-muted-foreground",children:g.type==="dashboard"?"Dashboard":"Visual"})]}),b&&l.jsxs(pt,{value:x,onValueChange:v=>m(g.id,v),children:[l.jsx(ft,{className:"h-7 w-20 text-xs",children:l.jsx(gt,{})}),l.jsxs(ht,{children:[g.supportedFormats.includes("pdf")&&l.jsx(Ie,{value:"pdf",children:"PDF"}),g.supportedFormats.includes("csv")&&l.jsx(Ie,{value:"csv",children:"CSV"})]})]})]},g.id)})})]})}),l.jsxs(Ds,{children:[l.jsx(re,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),l.jsxs(re,{onClick:p,disabled:o.size===0,children:[l.jsx(qr,{className:"mr-2 h-4 w-4"}),"Add"," ",o.size>1?`${o.size} Attachments`:"Attachment"]})]})]})})}function zUe({open:e,onOpenChange:t,attachment:n,onSave:r}){const[s,o]=w.useState(n.settings);w.useEffect(()=>{o(n.settings)},[n]);const i=()=>{r({...n,settings:s}),t(!1)};return l.jsx(zr,{open:e,onOpenChange:t,children:l.jsxs(Tr,{className:"max-w-md",children:[l.jsx(_r,{children:l.jsx(Ir,{children:"Export Settings"})}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx(ge,{className:"text-sm font-medium",children:n.title}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:[n.type==="dashboard"?"Dashboard":"Visual"," • ",n.format.toUpperCase()]})]}),l.jsx(Vs,{}),n.format==="pdf"&&l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"page-size",children:"Page Size"}),l.jsxs(pt,{value:s.pageSize||"letter",onValueChange:a=>o({...s,pageSize:a}),children:[l.jsx(ft,{id:"page-size",children:l.jsx(gt,{})}),l.jsxs(ht,{children:[l.jsx(Ie,{value:"letter",children:'Letter (8.5" × 11")'}),l.jsx(Ie,{value:"a4",children:"A4 (210mm × 297mm)"}),l.jsx(Ie,{value:"legal",children:'Legal (8.5" × 14")'}),l.jsx(Ie,{value:"a3",children:"A3 (297mm × 420mm)"}),l.jsx(Ie,{value:"tabloid",children:'Tabloid (11" × 17")'})]})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"orientation",children:"Orientation"}),l.jsxs(pt,{value:s.orientation||"portrait",onValueChange:a=>o({...s,orientation:a}),children:[l.jsx(ft,{id:"orientation",children:l.jsx(gt,{})}),l.jsxs(ht,{children:[l.jsx(Ie,{value:"portrait",children:"Portrait"}),l.jsx(Ie,{value:"landscape",children:"Landscape"})]})]})]}),l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Jt,{id:"include-filters",checked:s.includeFilters!==!1,onCheckedChange:a=>o({...s,includeFilters:a})}),l.jsx(ge,{htmlFor:"include-filters",className:"text-sm font-normal cursor-pointer",children:"Include applied filters"})]}),l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Jt,{id:"include-timestamp",checked:s.includeTimestamp!==!1,onCheckedChange:a=>o({...s,includeTimestamp:a})}),l.jsx(ge,{htmlFor:"include-timestamp",className:"text-sm font-normal cursor-pointer",children:"Include timestamp"})]})]})]}),n.format==="csv"&&l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"delimiter",children:"Delimiter"}),l.jsxs(pt,{value:s.delimiter||",",onValueChange:a=>o({...s,delimiter:a}),children:[l.jsx(ft,{id:"delimiter",children:l.jsx(gt,{})}),l.jsxs(ht,{children:[l.jsx(Ie,{value:",",children:"Comma (,)"}),l.jsx(Ie,{value:";",children:"Semicolon (;)"}),l.jsx(Ie,{value:"\\t",children:"Tab"})]})]})]}),l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Jt,{id:"include-headers",checked:s.includeHeaders!==!1,onCheckedChange:a=>o({...s,includeHeaders:a})}),l.jsx(ge,{htmlFor:"include-headers",className:"text-sm font-normal cursor-pointer",children:"Include column headers"})]}),l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Jt,{id:"use-formatted",checked:s.useFormattedValues!==!1,onCheckedChange:a=>o({...s,useFormattedValues:a})}),l.jsx(ge,{htmlFor:"use-formatted",className:"text-sm font-normal cursor-pointer",children:"Use formatted values"})]})]}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Formatted values preserve number formatting, dates, and currency symbols. Raw values export the underlying data."})]})]}),l.jsxs(Ds,{children:[l.jsx(re,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),l.jsx(re,{onClick:i,children:"Save Settings"})]})]})})}function VUe({attachments:e,onRemove:t,onUpdate:n}){const[r,s]=w.useState({open:!1,index:null}),o=(d,f)=>{const h=e[d],m={...h,format:f,settings:{...h.settings,...f==="csv"?{delimiter:",",includeHeaders:!0,useFormattedValues:!0}:{}}};n(d,m)},i=d=>d==="csv"?l.jsx(LU,{className:"h-4 w-4"}):l.jsx(ka,{className:"h-4 w-4"}),a=d=>d==="csv"?"text-green-600":"text-red-600",c=d=>{s({open:!0,index:d})},u=d=>{r.index!==null&&n(r.index,d),s({open:!1,index:null})};return l.jsxs("div",{className:"space-y-2",children:[e.map((d,f)=>{var h,m,p;return l.jsxs("div",{className:"flex items-center gap-2.5 rounded-md border bg-background p-2.5",children:[l.jsx("div",{className:Q("flex-shrink-0",a(d.format)),children:i(d.format)}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-sm font-medium",children:d.title}),l.jsxs("div",{className:"text-xs text-muted-foreground/80",children:[d.type==="dashboard"?"Dashboard":"Visual",((h=d.settings)==null?void 0:h.sheetSelection)==="all"&&" • All sheets",((m=d.settings)==null?void 0:m.sheetSelection)==="current"&&((p=d.settings)==null?void 0:p.currentSheetName)&&` • ${d.settings.currentSheetName}`]})]}),d.supportedFormats&&d.supportedFormats.length>1?l.jsxs(pt,{value:d.format,onValueChange:g=>o(f,g),children:[l.jsx(ft,{className:"h-7 w-20",children:l.jsx(gt,{})}),l.jsxs(ht,{children:[d.supportedFormats.includes("pdf")&&l.jsx(Ie,{value:"pdf",children:"PDF"}),d.supportedFormats.includes("csv")&&l.jsx(Ie,{value:"csv",children:"CSV"})]})]}):l.jsx(Xe,{variant:"secondary",className:"h-6 text-[11px] uppercase tracking-wide",children:d.format}),l.jsx(re,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>c(f),children:l.jsx(eg,{className:"h-4 w-4"})}),l.jsx(re,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-destructive",onClick:()=>t(f),children:l.jsx(Mt,{className:"h-4 w-4"})})]},f)}),r.open&&r.index!==null&&l.jsx(zUe,{open:r.open,onOpenChange:d=>s({...r,open:d}),attachment:e[r.index],onSave:u})]})}const BO=[{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"}],BM=[{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"}],Yw=[...BM,{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 BUe({value:e,onChange:t,className:n}){var i;const r=w.useMemo(()=>Intl.DateTimeFormat().resolvedOptions().timeZone,[]),s=w.useMemo(()=>{var c;const a=Yw.find(u=>u.value===e);return a?a.label:e===r?`${(c=e.split("/").pop())==null?void 0:c.replace(/_/g," ")}`:e},[e,r]),o=w.useMemo(()=>{var c;const a=Yw.find(u=>u.value===e);return a?`${a.label} (${a.offset})`:e===r?`${(c=e.split("/").pop())==null?void 0:c.replace(/_/g," ")} (Browser)`:e},[e,r]);return l.jsx("div",{className:Q("relative",n),children:l.jsxs(pt,{value:e||r,onValueChange:t,children:[l.jsx(ft,{className:"w-full",title:o,children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(pN,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"truncate",children:s})]})}),l.jsxs(ht,{className:"w-full max-h-[300px]",children:[r&&!Yw.find(a=>a.value===r)&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"px-2 py-1.5 text-xs font-medium text-muted-foreground",children:"Your timezone"}),l.jsx(Ie,{value:r,children:l.jsxs("div",{className:"flex items-center justify-between w-full",children:[l.jsx("span",{children:(i=r.split("/").pop())==null?void 0:i.replace(/_/g," ")}),l.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:"(Browser)"})]})}),l.jsx("div",{className:"my-1 h-px bg-border"})]}),l.jsx("div",{className:"px-2 py-1.5 text-xs font-medium text-muted-foreground",children:"Common timezones"}),BM.map(a=>l.jsx(Ie,{value:a.value,children:l.jsxs("div",{className:"flex items-center justify-between w-full",children:[l.jsx("span",{children:a.label}),l.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:a.offset})]})},a.value)),l.jsx("div",{className:"my-1 h-px bg-border"}),l.jsx("div",{className:"px-2 py-1.5 text-xs font-medium text-muted-foreground",children:"Other timezones"}),Yw.filter(a=>!BM.find(c=>c.value===a.value)).map(a=>l.jsx(Ie,{value:a.value,children:l.jsxs("div",{className:"flex items-center justify-between w-full",children:[l.jsx("span",{children:a.label}),l.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:a.offset})]})},a.value))]})]})})}function UUe({value:e,onChange:t,className:n}){const r=w.useMemo(()=>{const o=[];for(let i=0;i<24;i++)for(let a=0;a<60;a+=30){const c=`${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:c,label:f})}return o},[]),s=w.useMemo(()=>{const o=r.find(i=>i.value===e);return(o==null?void 0:o.label)||e},[e,r]);return l.jsxs(pt,{value:e,onValueChange:t,children:[l.jsx(ft,{className:Q("w-full",n),children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Yu,{className:"h-4 w-4 text-muted-foreground"}),l.jsx(gt,{placeholder:"Select time",children:s})]})}),l.jsx(ht,{className:"max-h-[300px]",children:r.map(o=>l.jsx(Ie,{className:"hover:bg-muted",value:o.value,children:o.label},o.value))})]})}function HUe({value:e=[],onChange:t,disabled:n=!1,className:r}){const s=h=>{if(n)return;const m=e.includes(h)?e.filter(p=>p!==h):[...e,h];t(m.sort())},o=()=>{n||t([1,2,3,4,5])},i=()=>{n||t([0,6])},a=()=>{n||t([0,1,2,3,4,5,6])},c=()=>{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 l.jsxs("div",{className:Q("space-y-3",r),children:[l.jsxs("div",{className:"flex flex-wrap gap-2",children:[l.jsx(re,{type:"button",variant:u?"default":"outline",size:"sm",onClick:o,disabled:n,className:"h-7 text-xs",children:"Weekdays"}),l.jsx(re,{type:"button",variant:d?"default":"outline",size:"sm",onClick:i,disabled:n,className:"h-7 text-xs",children:"Weekends"}),l.jsx(re,{type:"button",variant:f?"default":"outline",size:"sm",onClick:a,disabled:n,className:"h-7 text-xs",children:"Every day"}),e.length>0&&l.jsx(re,{type:"button",variant:"ghost",size:"sm",onClick:c,disabled:n,className:"h-7 text-xs",children:"Clear"})]}),l.jsx("div",{className:"grid grid-cols-7 gap-2",children:BO.map(h=>l.jsxs("div",{className:Q("flex flex-col items-center space-y-2",n&&"opacity-50"),children:[l.jsx(ge,{htmlFor:`weekday-${h.value}`,className:Q("text-xs font-medium cursor-pointer select-none",n&&"cursor-not-allowed"),children:h.shortLabel}),l.jsx(Jt,{id:`weekday-${h.value}`,checked:e.includes(h.value),onCheckedChange:()=>s(h.value),disabled:n,className:"h-5 w-5"}),l.jsx("span",{className:"text-[10px] text-muted-foreground",children:h.label.slice(0,3)})]},h.value))}),e.length>0&&l.jsxs("div",{className:"text-xs text-muted-foreground",children:["Selected: ",WUe(e)]})]})}function WUe(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=>BO[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 qUe(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 YUe(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 GUe(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=>BO[a].label);return i.length===1?i[0]:i.length===2?`${i[0]} and ${i[1]}`:i.join(", ")}function KUe(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 ZUe(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 Tre(e){if(typeof e=="string"){const r=e.trim();if(!r)return"No recipients";if(r.startsWith("{")||r.startsWith("["))try{const o=JSON.parse(r);if(o&&typeof o=="object"&&!Array.isArray(o)){const i={emails:Array.isArray(o.emails)?o.emails.filter(a=>typeof a=="string"&&a.trim()):[],tenantUserIds:Array.isArray(o.tenantUserIds)?o.tenantUserIds.filter(a=>typeof a=="string"&&a.trim()):[],orgUserIds:Array.isArray(o.orgUserIds)?o.orgUserIds.filter(a=>typeof a=="string"&&a.trim()):[],groupIds:Array.isArray(o.groupIds)?o.groupIds.filter(a=>typeof a=="string"&&a.trim()):[]};return Tre(i)}}catch{}const s=r.split(/[,;]/).map(o=>o.trim()).filter(Boolean);return`${s.length} recipient${s.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 XUe({schedules:e,onDelete:t,onEdit:n,isDeleting:r,isUpdating:s=null,isLoading:o=!1}){const[i,a]=w.useState(null),c=!!(r||s),u=f=>{a(f)},d=()=>{i&&(t(i),a(null))};return o?l.jsx("div",{className:"flex items-center justify-center py-8",children:l.jsx(Mn,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.length===0?l.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[l.jsx(js,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),l.jsx("p",{className:"text-sm",children:"No active schedules"}),l.jsx("p",{className:"mt-1 text-xs",children:"Create a schedule to start receiving reports"})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"space-y-3",children:l.jsx("div",{className:"space-y-2.5",children:e.map(f=>l.jsx(QUe,{schedule:f,onEdit:n?()=>n(f):void 0,onDelete:()=>u(f.id),isDeleting:r===f.id,isUpdating:s===f.id,isMutating:c},f.id))})}),l.jsx(qc,{open:!!i,onOpenChange:()=>a(null),children:l.jsxs(Pl,{children:[l.jsxs(Ol,{children:[l.jsx($l,{children:"Delete Schedule?"}),l.jsx(zl,{children:"This will permanently delete this schedule. You will no longer receive these reports."})]}),l.jsxs(Ll,{children:[l.jsx(Bl,{children:"Cancel"}),l.jsx(Vl,{className:"bg-destructive/90 hover:bg-destructive",onClick:d,children:"Delete Schedule"})]})]})})]})}function QUe({schedule:e,onEdit:t,onDelete:n,isDeleting:r,isUpdating:s,isMutating:o}){var p,g,b;const i=x=>{const y=C=>Array.isArray(C)?C.filter(S=>typeof S=="string"&&!!S.trim()):[],v=C=>{if(!C||typeof C!="object"||Array.isArray(C))return null;const S=C;return"emails"in S||"tenantUserIds"in S||"orgUserIds"in S||"groupIds"in S?{emails:y(S.emails),tenantUserIds:y(S.tenantUserIds),orgUserIds:y(S.orgUserIds),groupIds:y(S.groupIds)}:null};if(typeof x=="string"){const C=x.trim();if(!C||!C.startsWith("{")&&!C.startsWith("["))return null;try{return v(JSON.parse(C))}catch{return null}}return v(x)},c=(()=>{const x=i(e.recipients);if(x)return{summary:Tre(x),details:null};if(typeof e.recipients=="string"){const y=e.recipients?e.recipients.split(/[,;]/).filter(Boolean):[];return{summary:`${y.length} recipient${y.length!==1?"s":""}`,details:y.length===1?y[0]:null}}return{summary:"No recipients",details:null}})(),u=e.endDate&&new Date(e.endDate)<new Date,d=new Date(e.nextRun),f=d<new Date&&!u,h=r||s,m=o&&!h;return l.jsx("div",{className:Q("rounded-md border bg-card p-3 transition-colors",u&&"opacity-60"),children:l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex-1 space-y-2",children:[l.jsx("div",{className:"flex-1 min-w-0",children:l.jsx("p",{className:"text-sm font-medium",children:e.subject||"Untitled"})}),l.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[l.jsx(Q_,{className:"h-3 w-3"}),l.jsx("span",{children:c.details||c.summary})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[l.jsx(qA,{className:"h-3 w-3"}),l.jsx("span",{children:"Attachments"})]}),l.jsx("div",{className:"flex flex-wrap items-start gap-1.5",children:(p=e.reportParams)!=null&&p.attachments&&e.reportParams.attachments.length>0?e.reportParams.attachments.map((x,y)=>{var S,N;const v=(S=x.title)==null?void 0:S.includes("(All Sheets)"),C=((N=x.settings)==null?void 0:N.sheetSelection)==="all"&&!v;return l.jsxs(Xe,{variant:"outline",className:"h-6 text-xs",children:[x.type==="dashboard"?l.jsx(f3,{className:"mr-1 h-3 w-3"}):x.type==="visual"?l.jsx(ka,{className:"mr-1 h-3 w-3"}):l.jsx(X_,{className:"mr-1 h-3 w-3"}),x.title,C&&" (All Sheets)"]},y)}):l.jsxs(l.Fragment,{children:[(e.dashboardName||e.reportName)&&l.jsxs(Xe,{variant:"outline",className:"h-6 text-xs",children:[e.reportType==="VISUAL"?l.jsx(ka,{className:"mr-1 h-3 w-3"}):l.jsx(f3,{className:"mr-1 h-3 w-3"}),e.dashboardName||e.reportName]}),((g=e.reportParams)==null?void 0:g.sheetSelection)==="all"&&l.jsxs(Xe,{variant:"outline",className:"h-6 text-xs",children:[l.jsx(X_,{className:"mr-1 h-3 w-3"}),"All Sheets"]})]})})]}),l.jsxs("div",{className:"grid gap-1.5 text-xs",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[l.jsx(Yu,{className:"h-3 w-3"}),l.jsxs("span",{children:[rC(e.frequency),e.frequency==="weekly"&&e.weekdays&&l.jsxs(l.Fragment,{children:[" on ",GUe(e.weekdays)]})," at ",YUe(e.time)||e.time||"Time not set",e.timezone&&e.timezone!=="UTC"&&l.jsxs(l.Fragment,{children:[" ","(",(b=e.timezone.split("/").pop())==null?void 0:b.replace(/_/g," "),")"]})]})]}),(e.startDate||e.endDate)&&l.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[l.jsx(js,{className:"h-3 w-3"}),l.jsx("span",{children:ZUe(e.startDate?String(e.startDate):void 0,e.endDate?String(e.endDate):void 0)})]}),e.skipDates&&e.skipDates.length>0&&l.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[l.jsx($c,{className:"h-3 w-3"}),l.jsxs("span",{children:["Skipping: ",KUe(e.skipDates)]})]}),l.jsxs("div",{className:Q("flex items-center gap-1.5 font-medium",u?"text-muted-foreground line-through":f?"text-orange-500":"text-foreground"),children:[l.jsx(Yu,{className:"h-3 w-3"}),l.jsx("span",{children:u?"Schedule expired":l.jsxs(l.Fragment,{children:["Next: ",ot.format(d,"MMM d, yyyy")," at"," ",ot.format(d,"h:mm a"),f&&" (processing)"]})})]})]})]}),l.jsx("div",{className:"flex items-center",children:h?l.jsx(Mn,{className:"h-4 w-4 animate-spin text-muted-foreground"}):l.jsxs(pd,{children:[l.jsx(gd,{asChild:!0,children:l.jsx(re,{variant:"ghost",size:"sm",disabled:m,className:"h-8 w-8 p-0","aria-label":"Schedule actions",children:l.jsx(OU,{className:"h-4 w-4"})})}),l.jsxs(Hc,{align:"end",children:[l.jsxs(zs,{disabled:!t,onClick:x=>{x.preventDefault(),t==null||t()},children:[l.jsx(yN,{className:"mr-2 h-4 w-4"}),"Edit schedule"]}),l.jsxs(zs,{onClick:x=>{x.preventDefault(),n()},className:"text-destructive focus:text-destructive",children:[l.jsx(La,{className:"mr-2 h-4 w-4"}),"Delete schedule"]})]})]})})]})})}function cT(e,t){if(e instanceof Error&&e.message.trim().length>0)return e.message;if(e&&typeof e=="object"){const n=e;if(typeof n.error=="string"&&n.error.trim().length>0)return n.error;if(typeof n.message=="string"&&n.message.trim().length>0)return n.message}return t}function vs(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function _re(e){return e.sheetSelection==="all"?e.filterValues||[]:tS(e.filters,e.filterValues,e.selectedSheetId)}function JUe(e){const t=e.settings.sheetSelection==="all"?"all":"current",n=t==="current"?typeof e.settings.currentSheetId=="string"?e.settings.currentSheetId:e.selectedSheetId??void 0:void 0;return{sheetSelection:t,selectedSheetId:n,sheetFilterValues:_re({filters:e.filters,filterValues:e.filterValues,selectedSheetId:n,sheetSelection:t})}}function eHe(e){const{attachment:t,authToken:n,sheetContext:r}=e,s={...t.settings,sheetFilterValues:r.sheetFilterValues},o=TP(n,{sheetSelection:r.sheetSelection,selectedSheetId:r.selectedSheetId});return{...t,settings:{...s,...r.sheetSelection==="all"?{currentSheetId:void 0}:{},sheetFilterValues:o.filterValues||[],...r.sheetSelection==="current"&&!vs(s,"currentSheetId")&&o.selectedSheetId?{currentSheetId:o.selectedSheetId}:{},filterValues:vs(s,"filterValues")?s.filterValues:o.filterValues||[],controlValues:vs(s,"controlValues")?s.controlValues:o.defaultControlValues}}}function tHe(e){const{attachment:t,sheetContext:n,runtimeContext:r}=e,s={...t.settings,sheetFilterValues:n.sheetFilterValues},{dashboard:o,inlineFilterValuesMap:i,interactionStates:a,filters:c,filterValues:u,dashboardControls:d,controlValues:f,cardControlValuesMap:h,dashboardPrintParams:m}=r;if(t.type!=="visual"||!t.visualId||!o)return{...t,settings:s};const p=vs(s,"inlineFilterValues")?s.inlineFilterValues:i==null?void 0:i[t.visualId],g=vs(s,"filterValues")||vs(s,"inlineFilterValues")?{}:a,b=VJ({dashboard:o,cardId:t.visualId,interactionStates:g,currentDashboardId:o.id,filters:c,filterValues:u,inlineFilterValuesMap:{...i,[t.visualId]:Array.isArray(p)?p:[]},dashboardControls:d,dashboardControlValues:f,cardControlValuesMap:h});if(!b)return{...t,settings:{...s,filterValues:vs(s,"filterValues")?s.filterValues:n.sheetFilterValues,controlValues:vs(s,"controlValues")?s.controlValues:(m==null?void 0:m.defaultControlValues)||f}};if(vs(s,"filterValues")&&vs(s,"controlValues")&&vs(s,"controlDefinitions")&&vs(s,"cardControlDefinitions")&&vs(s,"controlBindings"))return{...t,settings:s};const{queryContext:y}=b;return{...t,settings:{...s,filterValues:vs(s,"filterValues")?s.filterValues:y.cardFilterValues,controlValues:vs(s,"controlValues")?s.controlValues:y.controlValues,controlDefinitions:vs(s,"controlDefinitions")?s.controlDefinitions:y.controlDefinitions,cardControlDefinitions:vs(s,"cardControlDefinitions")?s.cardControlDefinitions:y.cardControlDefinitions,controlBindings:vs(s,"controlBindings")?s.controlBindings:y.controlBindings}}}function Z8(e){const{attachment:t,runtimeContext:n}=e,r=JUe({settings:t.settings,filters:n.filters,filterValues:n.filterValues,selectedSheetId:n.selectedSheetId});return t.type==="dashboard"?eHe({attachment:t,authToken:n.authToken,sheetContext:r}):tHe({attachment:t,sheetContext:r,runtimeContext:n})}function nHe(e={}){const{reportType:t,dashboardId:n,visualId:r,pageSettings:s,enabled:o=!0}=e,[i,a]=w.useState(!1),[c,u]=w.useState(null),[d,f]=w.useState(null),[h,m]=w.useState(null),{authToken:p,tokenProps:g}=rt(),b=ee(R=>{var U;return(U=R.dashboard)==null?void 0:U.id}),x=ee(R=>{var U;return(U=R.dashboard)==null?void 0:U.title}),y=ee(R=>R.dashboard),v=ee(R=>R.dashboard.filters),C=ee(R=>R.dashboard.controls),S=ee(R=>R.filterValues),N=ee(R=>R.controlValues),j=ee(R=>R.cardControlValuesMap),k=ee(R=>R.inlineFilterValuesMap),T=ee(R=>R.selectedSheetId),E=Vt(R=>R.interactionStates),_=n||b,{data:M=[],isLoading:P,isError:D,refetch:A}=Qt({queryKey:["schedules","with-details"],queryFn:async()=>{const R=`${g.apiServiceUrl}/v1/schedules`;return await or(R,(p==null?void 0:p.accessToken)||"",{includeRecipientDetails:"true"})},enabled:!!(p!=null&&p.accessToken)&&!!(g!=null&&g.apiServiceUrl)&&o,staleTime:5*60*1e3,gcTime:10*60*1e3}),L=w.useCallback(R=>{var G,J,ne,be,te,ce,se;qUe(R.time,R.frequency,R.weekdays);const U=t==="DASHBOARD"?(ne=(J=(G=R.reportParams)==null?void 0:G.attachments)==null?void 0:J.find(ue=>ue.type==="dashboard"))==null?void 0:ne.settings:void 0,O=(U==null?void 0:U.sheetSelection)==="all"||((be=R.reportParams)==null?void 0:be.sheetSelection)==="all"?"all":"current",I=O==="current"?(U==null?void 0:U.currentSheetId)??((te=R.reportParams)==null?void 0:te.currentSheetId)??T:void 0,W=_re({filters:v,filterValues:S,selectedSheetId:I,sheetSelection:O}),X={authToken:p,filters:v,filterValues:S,selectedSheetId:T,dashboard:y,dashboardControls:C,controlValues:N,cardControlValuesMap:j,inlineFilterValuesMap:k,interactionStates:E},Z=t==="DASHBOARD"?TP(p,{sheetSelection:O,selectedSheetId:I}):void 0,{authToken:H,...K}=Z||{},z=mM((Z==null?void 0:Z.filterValues)||W||[]),q=(ce=R.reportParams)!=null&&ce.attachments?R.reportParams.attachments.map(ue=>Z8({attachment:ue,runtimeContext:{...X,dashboardPrintParams:Z}})):void 0,Y={recipients:R.recipients,recipientsString:void 0,subject:R.subject||x||"Scheduled Report",message:R.message,frequency:R.frequency,time:R.time,timezone:R.timezone,dashboardId:_,weekdays:R.weekdays,skipDates:R.skipDates,startDate:R.startDate,endDate:R.endDate,reportParams:(se=R.reportParams)!=null&&se.attachments?{...R.reportParams,attachments:q}:R.reportParams||{}};if(t){if(t==="DASHBOARD")Y.reportParams||(Y.reportParams={}),Y.dashboardParams={...K,filterLine:z};else if(t==="VISUAL"&&r){const ue=Z8({attachment:{type:"visual",visualId:r,title:R.subject||"Visual Report",format:"pdf",settings:{...s}},runtimeContext:{...X,dashboardPrintParams:Z}});Y.reportParams={attachments:[{...ue,settings:{...ue.settings,filterLine:mM(ue.settings.filterValues||[])}}]}}}return Y},[p,y,_,x,C,N,j,k,E,s,t,v,S,T,r]),$=w.useCallback(async R=>{a(!0),u(null);try{const U=L(R),O=`${g.apiServiceUrl}/v1/schedules`,I=await Is(O,(p==null?void 0:p.accessToken)||"",U);return qe.success("Schedule created successfully!",{description:`Reports will be sent ${R.frequency} at ${R.time}`}),await A(),a(!1),I}catch(U){console.error("Failed to create schedule:",U);const O=cT(U,"Failed to create schedule");throw u(O),a(!1),qe.error("Failed to create schedule",{description:O}),U}},[p==null?void 0:p.accessToken,L,g.apiServiceUrl,A]),B=w.useCallback(async(R,U)=>{m(R),u(null);try{const O=L(U),I=`${g.apiServiceUrl}/v1/schedules`,W=await Is(`${I}/${R}`,(p==null?void 0:p.accessToken)||"",O,"PATCH");return qe.success("Schedule updated successfully!",{description:`Reports will be sent ${U.frequency} at ${U.time}`}),await A(),m(null),W}catch(O){console.error("Failed to update schedule:",O);const I=cT(O,"Failed to update schedule");throw u(I),m(null),qe.error("Failed to update schedule",{description:I}),O}},[p==null?void 0:p.accessToken,L,A,g.apiServiceUrl]),V=w.useCallback(async R=>{f(R);try{const U=`${g.apiServiceUrl}/v1/schedules`;if(!(await fetch(`${U}/${R}`,{method:"DELETE",headers:{Authorization:`Bearer ${(p==null?void 0:p.accessToken)||""}`,"Content-Type":"application/json"}})).ok)throw new Error("Failed to delete schedule");qe.success("Schedule deleted successfully"),await A(),f(null)}catch(U){throw console.error("Failed to delete schedule:",U),f(null),qe.error("Failed to delete schedule",{description:cT(U,"Please try again")}),U}},[p,A,g.apiServiceUrl]);return{schedules:M,isLoading:P,isError:D,createSchedule:$,updateSchedule:B,deleteSchedule:V,refetch:A,isSubmitting:i,submitError:c,deletingId:d,updatingId:h}}const uT=`Hello,
1301
1301
 
1302
- Your scheduled email is ready. The attachments you requested are included for your review.`,Gw=[1,2,3,4,5],dT="09:00",rHe=["daily","weekly","biweekly","monthly"],Ym={emails:[],tenantUserIds:[],orgUserIds:[],groupIds:[]};function fT(e){if(!e)return;if(e instanceof Date){const s=new Date(e.getTime());return Number.isNaN(s.getTime())?void 0:s}const t=String(e).trim(),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(n){const s=Number(n[1]),o=Number(n[2])-1,i=Number(n[3]),a=new Date(s,o,i);return Number.isNaN(a.getTime())?void 0:a}const r=new Date(t);return Number.isNaN(r.getTime())?void 0:r}function sHe(e){const t=r=>Array.isArray(r)?r.filter(s=>typeof s=="string"&&!!s.trim()):[],n=r=>{if(!r||typeof r!="object"||Array.isArray(r))return null;const s=r;return"emails"in s||"tenantUserIds"in s||"orgUserIds"in s||"groupIds"in s?{emails:t(s.emails),tenantUserIds:t(s.tenantUserIds),orgUserIds:t(s.orgUserIds),groupIds:t(s.groupIds)}:null};if(typeof e=="string"){const r=e.trim();if(!r)return{...Ym};if(r.startsWith("{")||r.startsWith("["))try{const o=n(JSON.parse(r));if(o)return o}catch{}const s=r.split(/[,;]/).map(o=>o.trim()).filter(Boolean);return{...Ym,emails:s}}return n(e)??{...Ym}}function oHe(e){return rHe.includes(e)?e:"daily"}function iHe(e,t){var i,a,c,u,d,f,h,m,p,g,b,x,y,v,C,S,N,j,k,T,E;const n=((a=(i=e.reportParams)==null?void 0:i.attachments)==null?void 0:a.map(_=>({type:_.type,visualId:_.visualId,cardType:_.cardType,title:_.title,format:_.format,settings:_.settings||{}})))??[];if(n.length>0)return n;const r=e.reportName||e.dashboardName||e.subject||`${t} Report`,s=(c=e.reportParams)==null?void 0:c.format,o=typeof s=="string"&&["pdf","csv","png"].includes(s.toLowerCase())?s.toLowerCase():"pdf";return[{type:e.reportType==="VISUAL"?"visual":"dashboard",visualId:e.visualId,title:r,format:o,settings:{pageSize:((d=(u=e.reportParams)==null?void 0:u.pdfOptions)==null?void 0:d.pageSize)||"letter",orientation:((h=(f=e.reportParams)==null?void 0:f.pdfOptions)==null?void 0:h.orientation)||"portrait",includeFilters:((p=(m=e.reportParams)==null?void 0:m.pdfOptions)==null?void 0:p.includeFilters)??!0,includeTimestamp:((b=(g=e.reportParams)==null?void 0:g.pdfOptions)==null?void 0:b.includeTimestamp)??!0,delimiter:((y=(x=e.reportParams)==null?void 0:x.csvOptions)==null?void 0:y.delimiter)??",",includeHeaders:((C=(v=e.reportParams)==null?void 0:v.csvOptions)==null?void 0:C.includeHeaders)??!0,useFormattedValues:((N=(S=e.reportParams)==null?void 0:S.csvOptions)==null?void 0:N.useFormattedValues)??!0,sheetSelection:(j=e.reportParams)==null?void 0:j.sheetSelection,currentSheetId:(k=e.reportParams)==null?void 0:k.currentSheetId,currentSheetName:(T=e.reportParams)==null?void 0:T.currentSheetName,tablePreferences:(E=e.reportParams)==null?void 0:E.tablePreferences}}]}function Ire({open:e,onOpenChange:t,dashboardId:n,dashboardName:r="Dashboard",preSelectedVisual:s}){const[o,i]=w.useState("schedule"),[a,c]=w.useState({...Ym}),[u,d]=w.useState(`${r} Report`),[f,h]=w.useState(uT),[m,p]=w.useState(s?[s]:[]),[g,b]=w.useState(!1),[x,y]=w.useState(!1),[v,C]=w.useState(!1),[S,N]=w.useState(null),{currentUser:j}=Lo(),k=ee(fe=>fe.dashboard),T=w.useMemo(()=>(k==null?void 0:k.sheets)||[],[k==null?void 0:k.sheets]),E=ee(fe=>fe.selectedSheetId),_=T.find(fe=>fe.id===E),[M,P]=w.useState("daily"),[D,A]=w.useState(dT),[L,$]=w.useState(Intl.DateTimeFormat().resolvedOptions().timeZone),[B,V]=w.useState(Gw),[R,U]=w.useState(!0),[O,I]=w.useState(new Date),[W,X]=w.useState(!0),[Z,H]=w.useState(),{schedules:K,isLoading:z,createSchedule:q,updateSchedule:Y,deleteSchedule:G,isSubmitting:J,deletingId:ne,updatingId:be,refetch:te}=nHe({enabled:e}),ce=!!S,se=J||S!==null&&be===S;w.useEffect(()=>{if(e&&!x){if(j){const fe={...Ym};j.type==="tenant"&&j.id?fe.tenantUserIds=[j.id]:j.type==="organization"&&j.id&&(fe.orgUserIds=[j.id]),c(fe)}if(s)p([s]);else if(k&&_){const fe={type:"dashboard",title:T.length>1?`${k.title} (${_.title})`:`${k.title} (All Sheets)`,format:"pdf",settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0,sheetSelection:T.length>1?"current":"all",currentSheetId:T.length>1?_.id:void 0,currentSheetName:T.length>1?_.title:void 0}};p([fe])}else if(k){const fe={type:"dashboard",title:`${k.title} (All Sheets)`,format:"pdf",settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0,sheetSelection:"all"}};p([fe])}y(!0)}},[e,j,k,_,T,x,s]),w.useEffect(()=>{e||(y(!1),C(!1),N(null),i("schedule"))},[e]);const ue=fe=>{p(fe),b(!1)},Re=fe=>{p(m.filter((Oe,ye)=>ye!==fe))},je=(fe,Oe)=>{const ye=[...m];ye[fe]=Oe,p(ye)},ke=()=>{c({...Ym}),d(`${r} Report`),h(uT),p([]),P("daily"),A(dT),$(Intl.DateTimeFormat().resolvedOptions().timeZone),V(Gw),U(!0),I(new Date),X(!0),H(void 0),N(null)},me=fe=>{const Oe=oHe(fe.frequency),ye=Array.isArray(fe.weekdays)?fe.weekdays:void 0,Ce=!!(ye!=null&&ye.length),$e=fT(fe.startDate),ze=!!$e;c(sHe(fe.recipients)),d(fe.subject||`${r} Report`),h(typeof fe.message=="string"&&fe.message.length>0?fe.message:uT),p(iHe(fe,r)),P(Oe),A(fe.time||dT),$(fe.timezone||Intl.DateTimeFormat().resolvedOptions().timeZone),V(ye&&ye.length>0?ye:Gw),U(Ce),I($e||fT(fe.nextRun)||new Date),X(ze),H(fT(fe.endDate)),N(fe.id),C(!!(fe.subject||fe.message)),i("schedule")},Me=()=>{ke(),i("active")},Se=async()=>{const fe={recipients:a,subject:u,message:f,frequency:M,time:D,timezone:L,weekdays:M==="weekly"&&R?B:void 0,startDate:W?ot.format(O,"yyyy-MM-dd"):void 0,endDate:Z?ot.format(Z,"yyyy-MM-dd"):void 0,reportParams:{attachments:m.map(Oe=>({type:Oe.type,visualId:Oe.visualId,cardType:Oe.cardType,title:Oe.title,format:Oe.format,settings:Oe.settings}))}};try{S?(await Y(S,fe),N(null)):(await q(fe),ke()),i("active")}catch(Oe){console.error("Failed to save schedule:",Oe)}},ie=async fe=>{try{await G(fe)}catch(Oe){console.error("Failed to delete schedule:",Oe)}},Ne=(a.emails.length>0||a.tenantUserIds.length>0||a.orgUserIds.length>0||a.groupIds.length>0)&&u&&m.length>0,de=fe=>{fe||y(!1),t(fe)};return l.jsxs(l.Fragment,{children:[l.jsx(zr,{open:e,onOpenChange:de,children:l.jsxs(Tr,{className:"max-h-[90vh] max-w-2xl",children:[l.jsxs(_r,{children:[l.jsx(Ir,{children:"Schedule Export"}),l.jsx(ss,{className:"sr-only",children:"Create and manage scheduled exports for your dashboard"})]}),l.jsxs(As,{value:o,onValueChange:fe=>i(fe),className:"w-full",children:[l.jsxs(ys,{className:"grid w-full grid-cols-2",children:[l.jsxs(on,{value:"schedule",className:"flex items-center gap-2",children:[l.jsx($r,{className:"h-4 w-4"}),"Schedule"]}),l.jsxs(on,{value:"active",className:"flex items-center gap-2",children:[l.jsx(UA,{className:"h-4 w-4"}),"Active Schedules",K&&K.length>0&&l.jsx(Xe,{variant:"secondary",className:"ml-1 h-5 px-1",children:K.length})]})]}),l.jsxs(sr,{value:"schedule",className:"mt-4 max-h-[calc(80vh-200px)] space-y-3 overflow-y-auto pr-1",children:[l.jsxs("div",{className:"space-y-3 rounded-md border bg-muted/20 p-3",children:[l.jsxs("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"date",className:"text-xs text-muted-foreground",children:"First occurrence"}),l.jsxs(Gr,{modal:!0,children:[l.jsx(Kr,{asChild:!0,children:l.jsxs(re,{variant:"outline",className:Q("w-full justify-start text-left font-normal",!O&&"text-muted-foreground"),children:[l.jsx(js,{className:"mr-2 h-4 w-4 shrink-0"}),O?ot.format(O,"PPP"):"Pick a date"]})}),l.jsx(Zr,{className:"z-[51] w-auto p-0",align:"start",children:l.jsx(Nx,{mode:"single",selected:O,onSelect:fe=>{fe&&(I(fe),X(!0))},disabled:fe=>fe<new Date(new Date().setHours(0,0,0,0)),initialFocus:!0})})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"time",className:"text-xs text-muted-foreground",children:"Time"}),l.jsx(UUe,{value:D,onChange:A})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"timezone",className:"text-xs text-muted-foreground",children:"Timezone"}),l.jsx(BUe,{value:L,onChange:$})]})]}),l.jsxs("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"frequency",className:"text-xs text-muted-foreground",children:"Repeats"}),l.jsxs(pt,{value:M,onValueChange:fe=>{const Oe=fe;Oe==="weekly"&&M!=="weekly"&&(U(!0),B.length||V(Gw)),P(Oe)},children:[l.jsx(ft,{children:l.jsx(gt,{})}),l.jsxs(ht,{children:[l.jsx(Ie,{className:"hover:bg-muted",value:"daily",children:"Daily"}),l.jsx(Ie,{className:"hover:bg-muted",value:"weekly",children:"Weekly"}),l.jsx(Ie,{className:"hover:bg-muted",value:"biweekly",children:"Biweekly"}),l.jsx(Ie,{className:"hover:bg-muted",value:"monthly",children:"Monthly"})]})]}),M==="weekly"&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{className:"text-xs text-muted-foreground",children:"On days"}),l.jsx(HUe,{value:B,onChange:fe=>{V(fe),U(!0)}})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"end-date",className:"text-xs text-muted-foreground",children:"End date (optional)"}),l.jsxs(Gr,{modal:!0,children:[l.jsx(Kr,{asChild:!0,children:l.jsxs(re,{variant:"outline",className:Q("w-full justify-start text-left font-normal",!Z&&"text-muted-foreground"),children:[l.jsx(js,{className:"mr-2 h-4 w-4"}),Z?ot.format(Z,"PPP"):"No end date"]})}),l.jsx(Zr,{className:"z-[51] w-auto p-0",align:"start",children:l.jsx(Nx,{mode:"single",selected:Z,onSelect:H,disabled:fe=>fe<=O,initialFocus:!0})})]})]})]})]}),l.jsx("div",{className:"space-y-1.5",children:l.jsx(MUe,{value:a,onChange:c,triggerAccessory:l.jsx(re,{type:"button",variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>b(!0),title:"Select attachments","aria-label":"Select attachments",children:l.jsx(qA,{className:"h-4 w-4"})})})}),l.jsx("div",{className:"space-y-1.5",children:m.length>0?l.jsx(VUe,{attachments:m,onRemove:Re,onUpdate:je}):l.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-xs text-muted-foreground",children:"No attachments selected"})}),l.jsx(Vs,{className:"my-1"}),l.jsxs(oo,{open:v,onOpenChange:C,children:[l.jsx(io,{asChild:!0,children:l.jsxs(re,{variant:"ghost",className:"h-8 w-full justify-between px-2 text-left text-muted-foreground hover:text-foreground",children:["Email Content",l.jsx(pr,{className:Q("h-4 w-4 transition-transform",v&&"rotate-180")})]})}),l.jsxs(ao,{className:"mt-1.5 space-y-3 rounded-md border p-3",children:[l.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional. If unchanged, the default subject and message are used."}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"subject",children:"Subject"}),l.jsx(lt,{id:"subject",value:u,onChange:fe=>d(fe.target.value),placeholder:"Enter email subject"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"message",children:"Message"}),l.jsx(yi,{className:"ring-inset focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",id:"message",value:f,onChange:fe=>h(fe.target.value),placeholder:"Enter email message",rows:4})]})]})]})]}),l.jsx(sr,{value:"active",className:"mt-4 max-h-[calc(80vh-200px)] overflow-y-auto",children:K&&K.length>0?l.jsx(XUe,{schedules:K,onEdit:me,onDelete:ie,isDeleting:ne,isUpdating:be,isLoading:z,onRefresh:te}):l.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[l.jsx(Yu,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),l.jsx("p",{className:"text-sm font-medium",children:"No active schedules"}),l.jsx("p",{className:"mt-1 text-xs",children:'Switch to the "Schedule" tab to add your first schedule'})]})})]}),o==="schedule"&&l.jsxs(Ds,{className:"mt-1",children:[l.jsx(re,{variant:"outline",onClick:()=>ce?Me():de(!1),disabled:se,children:ce?"Cancel Edit":"Cancel"}),l.jsx(re,{onClick:Se,disabled:!Ne||se,children:se?l.jsx(l.Fragment,{children:ce?"Saving...":"Scheduling..."}):l.jsxs(l.Fragment,{children:[l.jsx(KA,{className:"mr-2 h-4 w-4"}),ce?"Save Changes":"Schedule"]})})]})]})}),g&&l.jsx($Ue,{open:g,onOpenChange:b,dashboardId:n,onSelect:ue,existingAttachments:m})]})}const hT="/api";function aHe(e){const t=e.replace(/\/+$/,"");if(!t||t===hT)return"/";if(t.endsWith(hT)){const n=t.slice(0,-hT.length);return n?`${n}/`:"/"}return`${t}/`}function lHe(e){if(!e)return null;try{const t=new URL(e),n=t.hostname.startsWith("api.")?t.hostname.slice(4):t.hostname,r=`${t.protocol}//${n}${t.port?`:${t.port}`:""}`;return new URL(aHe(t.pathname),r).toString()}catch{return null}}function cHe({apiServiceUrl:e,dashboardId:t,cardId:n,params:r}){if(!t||!n)return null;const s=lHe(e);if(!s)return null;const o=new URL(`view/dashboard/${encodeURIComponent(t)}/visual/${encodeURIComponent(n)}`,s);return r&&(o.search=r.toString()),o.toString()}function UM(e){if(Array.isArray(e))return e.map(t=>UM(t)).join(", ");if(e==null)return"--";if(typeof e=="string")return e;if(typeof e=="object")try{return JSON.stringify(e)}catch{return"[object]"}return String(e)}function uHe(e){return e.split(/[_\s-]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}function dHe(e){const t=e.unit,n=r=>`${t}${r===1?"":"s"}`;return e.mode==="last"?`Last ${e.n} ${n(e.n)} (relative)`:e.mode==="this"?`This ${t}${e.toDate?" to date":""} (relative)`:e.mode==="previous"?`Previous ${t} (relative)`:`Between ${e.from} and ${e.to} ${n(Math.max(e.from,e.to))} ago (relative)`}function fHe(e,t){if(!e||typeof e!="object"||Array.isArray(e)){const f=UM(e);return{key:`filter_${t+1}`,value:f,summary:f}}const n=e,r=[n.name,n.field,n.fieldName,n.column,n.id].find(f=>typeof f=="string"&&f.trim().length>0),s=[n.operation,n.operator].find(f=>typeof f=="string"&&f.trim().length>0),o=n.relativeMeta,a=[o&&typeof o=="object"?dHe(o):void 0,n.values,n.value,n.selectedValues].find(f=>f!==void 0),c=r||`filter_${t+1}`,u=UM(a),d=s?`${c} ${s} ${u}`:`${c} = ${u}`;return{key:c,value:s?`${s} ${u}`:u,summary:d}}function hHe(e){var n;if(!e||e.type!=="dashboard_metric")return[];const t=(n=e.executionSnapshot.filterContext)==null?void 0:n.active_filters;return Array.isArray(t)?t.map((r,s)=>fHe(r,s)):[]}function mT(e){const t=e.trim().toLowerCase();return t==="day"?"Daily":t==="week"?"Weekly":t==="month"?"Monthly":t==="quarter"?"Quarterly":t==="year"?"Yearly":uHe(e)}function pT(e){if(!e||e.type!=="dashboard_metric")return"--";const t=e.executionSnapshot.queryConfig,n=t.granularity;if(typeof n=="string"&&n.trim().length>0)return mT(n);const r=t.trendlineGranularity;if(typeof r=="string"&&r.trim().length>0)return mT(r);const s=t.groupByColumns;if(Array.isArray(s))for(const o of s){if(!o||typeof o!="object"||Array.isArray(o))continue;const i=o.granularity;if(typeof i=="string"&&i.trim().length>0)return mT(i)}return"--"}function mHe(e){return e?e.type==="saved_metric"?e.title||e.visualId:e.title||e.cardId:"Select a metric source"}function pHe(e){return e===0?"Sunday":e===1?"Monday":e===void 0?"--":String(e)}function gHe(e,t){if(typeof e!="number"||!Number.isFinite(e))return"--";const n=Oa(t==null?void 0:t.format);return n!=null&&n.type&&n.type!=="auto"?kn(e,n.type,n):kn(e,"number",{maximumFractionDigits:Math.abs(e)>=100?0:2})}function bHe({source:e,currentValue:t,timezone:n,connectionName:r,dashboardName:s,expanded:o,onToggleExpanded:i}){const a=w.useMemo(()=>hHe(e),[e]),c=w.useMemo(()=>a.length===0?"No active filters":a.slice(0,2).map(m=>m.summary).join(" · "),[a]),u=(e==null?void 0:e.type)==="dashboard_metric"?e.executionSnapshot.calendarContext:void 0,d=(e==null?void 0:e.type)==="dashboard_metric"?`${pT(e)} · ${(u==null?void 0:u.tz)||n} · ${r||"Unknown connection"}`:`${e?"Saved metric source":"No metric selected"} · ${n}`,f=(e==null?void 0:e.type)==="dashboard_metric"?"Dashboard card":"Saved metric",h=gHe(t,e);return l.jsxs(xi,{className:"overflow-hidden border-border/70 bg-gradient-to-b from-background to-muted/20 shadow-sm",children:[l.jsxs(Na,{className:"space-y-3 p-4 pb-3",children:[l.jsxs("div",{className:"flex items-start justify-between gap-3",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Watch Context"}),l.jsx("p",{className:"text-base font-semibold leading-tight text-foreground",children:mHe(e)})]}),l.jsx(Xe,{variant:"secondary",className:"shrink-0 border border-border/60",children:f})]}),l.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[l.jsxs("div",{className:"rounded-md border bg-background/80 px-3 py-2",children:[l.jsx("p",{className:"text-xs text-muted-foreground",children:"Current value"}),l.jsx("p",{className:"text-xl font-semibold tracking-tight text-foreground",children:h})]}),l.jsxs("div",{className:"rounded-md border bg-background/80 px-3 py-2",children:[l.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters"}),l.jsx("p",{className:"truncate text-sm text-foreground",title:c,children:c})]})]}),l.jsxs("div",{className:"flex flex-wrap gap-2",children:[l.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border bg-background px-2.5 py-1 text-xs text-muted-foreground",children:[l.jsx(p0,{className:"h-3.5 w-3.5"}),pT(e)]}),l.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border bg-background px-2.5 py-1 text-xs text-muted-foreground",children:[l.jsx(IU,{className:"h-3.5 w-3.5"}),(u==null?void 0:u.tz)||n]}),l.jsxs("span",{className:"inline-flex max-w-full items-center gap-1 rounded-full border bg-background px-2.5 py-1 text-xs text-muted-foreground",title:d,children:[l.jsx(pl,{className:"h-3.5 w-3.5"}),l.jsx("span",{className:"truncate",children:r||"Unknown connection"})]})]})]}),(e==null?void 0:e.type)==="dashboard_metric"?l.jsxs(Ea,{className:"space-y-3 px-4 pb-4 pt-0",children:[l.jsx(re,{type:"button",variant:"outline",size:"sm",className:"h-8 rounded-full px-3 text-xs",onClick:i,children:o?l.jsxs(l.Fragment,{children:[l.jsx(Mf,{className:"mr-1 h-3.5 w-3.5"}),"Hide details"]}):l.jsxs(l.Fragment,{children:[l.jsx(pr,{className:"mr-1 h-3.5 w-3.5"}),"View details"]})}),o?l.jsxs("div",{className:"space-y-3 rounded-md border bg-background/90 p-3 text-xs",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"inline-flex items-center gap-1 text-foreground",children:[l.jsx(Ic,{className:"h-3.5 w-3.5"}),l.jsx("p",{className:"font-semibold",children:"Active filters"})]}),a.length===0?l.jsx("p",{className:"text-muted-foreground",children:"No active filters"}):l.jsx("div",{className:"space-y-1.5",children:a.map((m,p)=>l.jsxs("div",{className:"grid grid-cols-[minmax(0,150px)_1fr] gap-2 rounded-sm border bg-muted/20 px-2 py-1.5",children:[l.jsx("p",{className:"truncate font-medium text-foreground",children:m.key}),l.jsx("p",{className:"truncate text-muted-foreground",children:m.value})]},`${m.key}-${p}`))})]}),l.jsxs("dl",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Aggregation"}),l.jsx("dd",{className:"font-medium text-foreground",children:pT(e)})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Timezone"}),l.jsx("dd",{className:"font-medium text-foreground",children:(u==null?void 0:u.tz)||n})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Week starts"}),l.jsx("dd",{className:"font-medium text-foreground",children:pHe(u==null?void 0:u.weekStart)})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Connection"}),l.jsx("dd",{className:"font-medium text-foreground",children:r||e.executionSnapshot.connectionId})]}),l.jsxs("div",{className:"space-y-0.5 sm:col-span-2",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Dashboard"}),l.jsx("dd",{className:"font-medium text-foreground",children:s||e.dashboardId})]})]}),l.jsx("div",{className:"rounded-md border bg-muted/30 px-3 py-2 text-muted-foreground",children:"This alert evaluates against a frozen snapshot of the card configuration."})]}):null]}):null]})}function xHe({candidates:e,selected:t,onToggle:n}){return e.length?l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(r=>l.jsx(Xe,{variant:t.includes(r.id)?"default":"outline",className:`cursor-pointer select-none ${t.includes(r.id),""}`,onClick:()=>n(r.id),children:r.label},r.id))}):l.jsx("p",{className:"text-xs text-muted-foreground",children:"No driver suggestions available for this signal."})}function yHe({wizard:e}){var o;const{state:t}=e,[n,r]=w.useState(!1);if(t.prefillLoading)return l.jsx("div",{className:"flex items-center justify-center py-12",children:l.jsxs("div",{className:"flex flex-col items-center gap-3",children:[l.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading signal context..."})]})});if(t.prefillError)return l.jsx("div",{className:"rounded border border-destructive/50 bg-destructive/10 p-4",children:l.jsx("p",{className:"text-sm text-destructive",children:t.prefillError})});if(!t.prefillData)return l.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No signal context available."});const{prefillData:s}=t;return l.jsxs("div",{className:"flex flex-col gap-5",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-semibold",children:"What should Semaphor watch?"}),l.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Start with the business change you care about, then add the context your team will need to investigate it quickly."})]}),l.jsxs("div",{className:"space-y-3",children:[l.jsx(bHe,{source:s.source,currentValue:s.currentValue,timezone:((o=s.calendarContext)==null?void 0:o.tz)??Intl.DateTimeFormat().resolvedOptions().timeZone,connectionName:s.connectionName??void 0,dashboardName:s.dashboardName??void 0,expanded:n,onToggleExpanded:()=>r(i=>!i)}),s.snapshotWarning&&s.snapshotWarning!=="invalid"&&l.jsx("p",{className:"text-xs text-amber-700",children:s.snapshotWarning==="stale"?"Snapshot is older than expected. Values may not reflect the latest data.":"Execution snapshot not available."})]}),s.driverCandidates.length>0&&l.jsxs("div",{children:[l.jsx("p",{className:"mb-2 text-sm font-medium",children:"Contributing factors"}),l.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"Select insights to explain what changed."}),l.jsx(xHe,{candidates:s.driverCandidates,selected:t.selectedDrivers,onToggle:e.toggleDriver})]}),l.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[l.jsx("span",{className:"text-xs text-muted-foreground",children:"Step 1 of 3"}),l.jsx(re,{onClick:e.nextStep,size:"sm",children:"Continue"})]})]})}const nx={low_noise:{label:"Low Noise",description:"Only major changes surface",relativeChangeThreshold:15,consecutiveCount:2},standard:{label:"Standard",description:"Balanced sensitivity",relativeChangeThreshold:10,consecutiveCount:1},early_warning:{label:"Early Warning",description:"Catches smaller changes sooner",relativeChangeThreshold:5,consecutiveCount:1}};function UO(e){const t=nx[e];return{sensitivityPreset:e,threshold:t.relativeChangeThreshold,consecutiveCount:t.consecutiveCount,operator:"pct_change_gt"}}function vHe({selected:e,onSelect:t,customValues:n,onCustomize:r}){const[s,o]=w.useState(!1),i=["low_noise","standard","early_warning"];return l.jsxs("div",{className:"space-y-4",children:[l.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:i.map(a=>{const c=nx[a];return l.jsxs("div",{className:`rounded border p-3 ${e===a?"border-primary bg-primary/5":""}`,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Xe,{variant:e===a?"default":"outline",className:"cursor-pointer",onClick:()=>{t(a),o(!1)},children:c.label}),a==="standard"&&l.jsx(Xe,{variant:"secondary",className:"text-[10px]",children:"Recommended"})]}),l.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:c.description}),l.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:[c.relativeChangeThreshold,"% move • ",c.consecutiveCount," check",c.consecutiveCount===1?"":"s"]}),l.jsx("button",{type:"button",className:"mt-2 text-xs font-medium text-primary",onClick:()=>{t(a),o(!0)},children:"Customize"})]},a)})}),s&&e&&l.jsxs("div",{className:"space-y-3 rounded border p-4",children:[l.jsxs("h4",{className:"text-sm font-medium",children:["Customize ",nx[e].label]}),l.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[l.jsxs("div",{children:[l.jsx("label",{className:"text-xs text-muted-foreground",children:"Threshold (%)"}),l.jsx(lt,{type:"number",value:(n==null?void 0:n.threshold)??nx[e].relativeChangeThreshold,onChange:a=>r==null?void 0:r({threshold:parseInt(a.target.value,10)||0}),className:"mt-1"})]}),l.jsxs("div",{children:[l.jsx("label",{className:"text-xs text-muted-foreground",children:"Consecutive checks"}),l.jsx(lt,{type:"number",min:1,value:(n==null?void 0:n.consecutiveCount)??nx[e].consecutiveCount,onChange:a=>r==null?void 0:r({consecutiveCount:parseInt(a.target.value,10)||1}),className:"mt-1"})]})]})]})]})}function wHe({wizard:e}){const{draftJobConfig:t}=e.state;return l.jsxs("div",{className:"flex flex-col gap-5",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-semibold",children:"Signal Sensitivity"}),l.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Choose how quickly Semaphor should surface meaningful changes in this signal."})]}),l.jsx("div",{className:"rounded border p-4",children:l.jsx(vHe,{selected:t.sensitivityPreset,onSelect:n=>e.setSensitivity(n),customValues:{threshold:t.threshold,consecutiveCount:t.consecutiveCount},onCustomize:n=>e.updateJobConfig(n)})}),l.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[l.jsx(re,{variant:"outline",size:"sm",onClick:e.prevStep,children:"Back"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Step 2 of 3"}),l.jsx(re,{size:"sm",onClick:e.nextStep,children:"Continue"})]})]})}var dE="Switch",[CHe]=us(dE),[SHe,NHe]=CHe(dE),Mre=F.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:s,defaultChecked:o,required:i,disabled:a,value:c="on",onCheckedChange:u,form:d,...f}=e,[h,m]=F.useState(null),p=Et(t,v=>m(v)),g=F.useRef(!1),b=h?d||!!h.closest("form"):!0,[x,y]=Ms({prop:s,defaultProp:o??!1,onChange:u,caller:dE});return l.jsxs(SHe,{scope:n,checked:x,disabled:a,children:[l.jsx(at.button,{type:"button",role:"switch","aria-checked":x,"aria-required":i,"data-state":Fre(x),"data-disabled":a?"":void 0,disabled:a,value:c,...f,ref:p,onClick:Ye(e.onClick,v=>{y(C=>!C),b&&(g.current=v.isPropagationStopped(),g.current||v.stopPropagation())})}),b&&l.jsx(Rre,{control:h,bubbles:!g.current,name:r,value:c,checked:x,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});Mre.displayName=dE;var Dre="SwitchThumb",Are=F.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,s=NHe(Dre,n);return l.jsx(at.span,{"data-state":Fre(s.checked),"data-disabled":s.disabled?"":void 0,...r,ref:t})});Are.displayName=Dre;var jHe="SwitchBubbleInput",Rre=F.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...s},o)=>{const i=F.useRef(null),a=Et(i,o),c=T0(n),u=y0(t);return F.useEffect(()=>{const d=i.current;if(!d)return;const f=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(f,"checked").set;if(c!==n&&m){const p=new Event("click",{bubbles:r});m.call(d,n),d.dispatchEvent(p)}},[c,n,r]),l.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...s,tabIndex:-1,ref:a,style:{...s.style,...u,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Rre.displayName=jHe;function Fre(e){return e?"checked":"unchecked"}var HO=Mre,Pre=Are;const EHe=Ki("peer inline-flex shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/20 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",{variants:{size:{default:"h-6 w-11",sm:"h-[22px] w-[36px]",xs:"h-4 w-7"}},defaultVariants:{size:"default"}}),kHe=Ki("pointer-events-none block rounded-full bg-background shadow-sm ring-0 transition-transform data-[state=unchecked]:translate-x-0",{variants:{size:{default:"h-5 w-5 data-[state=checked]:translate-x-5",sm:"size-4 data-[state=checked]:translate-x-4",xs:"h-3 w-3 data-[state=checked]:translate-x-3"}},defaultVariants:{size:"default"}}),gh=F.forwardRef(({className:e,size:t,...n},r)=>l.jsx(HO,{className:Q(EHe({size:t,className:e})),...n,ref:r,children:l.jsx(Pre,{className:Q(kHe({size:t}))})}));gh.displayName=HO.displayName;const THe=[{value:"concise",label:"Concise",description:"Key facts only"},{value:"balanced",label:"Balanced",description:"Summary + context"},{value:"detailed",label:"Detailed",description:"Full analysis"}];function _He({value:e,onChange:t}){return l.jsxs("div",{children:[l.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Format profile"}),l.jsx("div",{className:"mt-1 flex gap-2",children:THe.map(n=>l.jsx(Xe,{variant:e===n.value?"default":"outline",className:"cursor-pointer px-3 py-1.5",onClick:()=>t(n.value),children:l.jsx("span",{className:"text-xs",children:n.label})},n.value))})]})}const IHe={EMAIL:{label:"Email",icon:"✉️",description:"Email notifications"},SLACK:{label:"Slack",icon:"💬",description:"Slack messages"},TELEGRAM:{label:"Telegram",icon:"📱",description:"Telegram messages"},WEBHOOK:{label:"Webhook",icon:"🔗",description:"HTTP webhook calls"},IN_APP:{label:"In-App",icon:"🔔",description:"Dashboard notifications"}},MHe=["EMAIL","SLACK","TELEGRAM","WEBHOOK","IN_APP"];function DHe({enabledChannels:e,channelConfigs:t,onChannelToggle:n,onConfigChange:r}){const[s,o]=w.useState(null);return l.jsx("div",{className:"space-y-3",children:MHe.map(i=>{var f;const a=IHe[i],c=e.includes(i),u=t[i]??{formatProfile:"balanced"},d=s===i;return l.jsxs("div",{className:"rounded-lg border p-3",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(gh,{checked:c,onCheckedChange:h=>n(i,!!h)}),l.jsx("span",{className:"text-base",children:a.icon}),l.jsxs("div",{children:[l.jsx("div",{className:"text-sm font-medium text-foreground",children:a.label}),l.jsx("div",{className:"text-xs text-muted-foreground",children:a.description})]})]}),c&&l.jsx(re,{variant:"ghost",size:"sm",className:"text-xs",onClick:()=>o(d?null:i),children:d?"Collapse":"Customize"})]}),c&&d&&l.jsxs("div",{className:"mt-3 space-y-3 border-t pt-3",children:[l.jsx(_He,{value:u.formatProfile,onChange:h=>r(i,{...u,formatProfile:h})}),l.jsxs("div",{children:[l.jsx("label",{className:"text-xs text-muted-foreground",children:"Subject override (optional)"}),l.jsx(lt,{value:u.subjectOverride??"",onChange:h=>r(i,{...u,subjectOverride:h.target.value||void 0}),placeholder:"Auto-generated",className:"mt-1 text-sm"})]}),l.jsxs("div",{children:[l.jsx("label",{className:"text-xs text-muted-foreground",children:"Summary override (optional)"}),l.jsx(yi,{value:u.summaryOverride??"",onChange:h=>r(i,{...u,summaryOverride:h.target.value||void 0}),placeholder:"Auto-generated summary",className:"mt-1 text-sm",rows:2})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(gh,{checked:u.actionBlockVisible!==!1,onCheckedChange:h=>r(i,{...u,actionBlockVisible:!!h})}),l.jsx("label",{className:"text-xs",children:"Show action block"})]}),i==="WEBHOOK"&&l.jsxs("div",{children:[l.jsx("label",{className:"text-xs text-muted-foreground",children:"Webhook URL"}),l.jsx(lt,{value:((f=u.webhookConfig)==null?void 0:f.url)??"",onChange:h=>{var m,p;return r(i,{...u,webhookConfig:{url:h.target.value,method:((m=u.webhookConfig)==null?void 0:m.method)??"POST",headers:((p=u.webhookConfig)==null?void 0:p.headers)??{}}})},placeholder:"https://...",className:"mt-1 text-sm"})]})]})]},i)})})}const AHe={EMAIL:"Email",SLACK:"Slack",TELEGRAM:"Telegram",WEBHOOK:"Webhook",IN_APP:"In-App"};function RHe({ruleId:e,metricName:t,channels:n,onClose:r}){const s=n.map(o=>AHe[o]??o).join(", ");return l.jsxs("div",{className:"flex flex-col items-center justify-center space-y-4 p-8",children:[l.jsx("div",{className:"flex h-16 w-16 items-center justify-center rounded-full bg-green-100 text-3xl",children:"✓"}),l.jsx("h2",{className:"text-xl font-bold",children:"Semaphor Is Watching This Signal"}),l.jsxs("p",{className:"max-w-md text-sm leading-6 text-muted-foreground",children:[l.jsx("span",{className:"font-medium text-foreground",children:t})," is now being watched. Semaphor will surface meaningful changes via ",s,"."]}),l.jsx("div",{className:"w-full max-w-sm space-y-2 rounded-lg bg-muted p-4 text-sm",children:l.jsxs("div",{children:[l.jsx("span",{className:"font-medium",children:"Where it surfaces:"})," ",s]})}),l.jsx(re,{onClick:r,variant:"outline",children:"Close"})]})}function Ore(e,t){switch(e){case"pct_change_gt":return`${t}% above the previous check`;case"pct_change_lt":return`${Math.abs(t)}% below the previous check`;case"gt":return`Value above ${t}`;case"gte":return`Value at or above ${t}`;case"lt":return`Value below ${t}`;case"lte":return`Value at or below ${t}`;case"eq":return`Value equal to ${t}`;case"neq":return`Value different from ${t}`;default:return`${e} ${t}`}}function FHe(e){switch(e){case"*/5 * * * *":return"Every 5 minutes";case"*/6 * * * *":return"Every 6 minutes";case"*/10 * * * *":return"Every 10 minutes";case"*/12 * * * *":return"Every 12 minutes";case"*/15 * * * *":return"Every 15 minutes";case"*/20 * * * *":return"Every 20 minutes";case"*/30 * * * *":return"Every 30 minutes";case"0 * * * *":return"Hourly";case"0 */2 * * *":return"Every 2 hours";case"0 */3 * * *":return"Every 3 hours";case"0 */4 * * *":return"Every 4 hours";case"0 */6 * * *":return"Every 6 hours";case"0 */8 * * *":return"Every 8 hours";case"0 */12 * * *":return"Every 12 hours";case"0 9 * * *":return"Daily";case"0 9 * * 1":return"Weekly";case"0 9 1 * *":return"Monthly";case"0 9 1 1 *":return"Yearly";default:return e}}function PHe(e){const t=[],n=new Set,r=(s,o)=>{n.has(s)||(n.add(s),t.push(o))};return e.orgUserId&&r(`user:${e.orgUserId}`,{type:"user",userId:e.orgUserId}),e.endUserId&&r(`tenant_user:${e.endUserId}`,{type:"tenant_user",tenantUserId:e.endUserId}),e.orgUserEmail&&r(`email:${e.orgUserEmail.toLowerCase()}`,{type:"email",address:e.orgUserEmail}),e.endUserEmail&&r(`email:${e.endUserEmail.toLowerCase()}`,{type:"email",address:e.endUserEmail}),t}function Lre(e,t){const n=e.recipients&&e.recipients.length>0?e.recipients:PHe(t);return{channels:e.channels,recipients:n,...e.channelConfigs?{channelConfigs:e.channelConfigs}:{}}}function OHe(e,t){if(t.length===0)return;const n=e.driverCandidates.filter(r=>t.includes(r.id));if(n.length!==0)return n.map((r,s)=>({kind:"related_metric",outputAs:`driver_${s+1}`,config:{referenceId:r.referenceId,label:r.label,sourceKind:r.sourceKind,provenance:r.provenance,metricType:r.metricType}}))}function HM(e,t,n=[]){const r=OHe(e,n),s=UO(t.sensitivityPreset??"standard");return{kind:"ALERT",source:e.source,...s,...t,...r?{contextSources:r}:{},notifyPolicy:"on_state_change",severity:t.severity??"MEDIUM",operator:t.operator??s.operator,threshold:t.threshold??s.threshold}}function $re(e){return{metricLabel:e.metricLabel,currentValue:e.currentValue,dashboardName:e.dashboardName,connectionName:e.connectionName,driverCandidates:e.driverCandidates}}function LHe(e){try{const t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{value:t}}catch{return null}}function $He(e,t){if(!t)return null;const n=Array.isArray(t.warnings)?t.warnings:void 0;if(e==="EMAIL")return{html:t.rendered,...n?{warnings:n}:{}};if(e==="TELEGRAM")return{text:t.rendered,...n?{warnings:n}:{}};if(t.contentType.includes("json")){const r=LHe(t.rendered);if(r)return n?{...r,warnings:n}:r}return{text:t.rendered,...n?{warnings:n}:{}}}const zHe=[5,6,10,12,15,20,30,60],VHe=[1,2,3,4,6,8,12,24],WM=60,WO=24*WM,BHe=7*WO,UHe=31*WO;function HHe(e){if(!Number.isFinite(e)||e<=5)return"*/5 * * * *";if(e<WM){const t=zHe.find(n=>n>=e)??60;return t===60?"0 * * * *":`*/${t} * * * *`}if(e<=WO){const t=Math.ceil(e/WM),n=VHe.find(r=>r>=t)??24;return n===24?"0 9 * * *":`0 */${n} * * *`}return e<=BHe?"0 9 * * 1":e<=UHe?"0 9 1 * *":"0 9 1 1 *"}function qM(e){return e==="SLACK"?"Slack":"Telegram"}function WHe(e){if(!e)return null;const t=qM(e.channel);return e.error?`${t}: ${e.error}`:e.installed?e.status&&e.status!=="ACTIVE"?`${t} is not active for this workspace yet.`:e.userLinked?null:`Link your ${t} account before starting this watch.`:`${t} is not installed for this workspace yet.`}function qHe({wizard:e,onClose:t}){var I,W,X,Z,H,K,z;const{authToken:n,tokenProps:r}=rt(),{state:s}=e,{createAlert:o,isCreating:i}=DF({enabled:!1}),[a,c]=w.useState(!1),[u,d]=w.useState(null),[f,h]=w.useState(!1),[m,p]=w.useState(null),[g,b]=w.useState({}),[x,y]=w.useState(null),[v,C]=w.useState(null),[S,N]=w.useState(null),j=w.useMemo(()=>Lre(s.draftDeliveryConfig,r),[s.draftDeliveryConfig,r]),T=j.recipients.length>0?null:"No recipient identity was found in this token. Semaphor will fall back to the current signed-in workspace identity when you start watching.",_=s.draftDeliveryConfig.channels.includes("WEBHOOK")&&!((Z=(X=(W=(I=j.channelConfigs)==null?void 0:I.WEBHOOK)==null?void 0:W.webhookConfig)==null?void 0:X.url)!=null&&Z.trim())?"Configure a webhook URL before sending or starting a webhook-based signal watch.":null,M=((K=(H=s.prefillData)==null?void 0:H.calendarContext)==null?void 0:K.tz)??Intl.DateTimeFormat().resolvedOptions().timeZone,P=w.useMemo(()=>s.draftDeliveryConfig.channels.filter(q=>q==="SLACK"||q==="TELEGRAM"),[s.draftDeliveryConfig.channels]),D=w.useMemo(()=>(u==null?void 0:u.minCadenceMinutes)??15,[u]),A=w.useMemo(()=>HHe(D),[D]),L=w.useMemo(()=>FHe(A),[A]),$=P.length>0&&P.some(q=>g[q]===void 0),B=w.useMemo(()=>{const q=P.map(Y=>WHe(g[Y])).filter(Y=>!!Y);return q.length>0?q.join(" "):null},[P,g]);w.useEffect(()=>{const q=r==null?void 0:r.apiServiceUrl,Y=n==null?void 0:n.accessToken;if(!q||!Y){d(null),h(!1),p(null);return}let G=!1;return h(!0),p(null),(async()=>{var J;try{const ne=await fetch(`${q}/v1/alerts/quota`,{headers:{Authorization:`Bearer ${Y}`}}),be=await ne.json().catch(()=>({}));if(!ne.ok)throw new Error(be.error??"Unable to load this workspace cadence policy right now.");G||d({minCadenceMinutes:((J=be.quota)==null?void 0:J.minCadenceMinutes)??15})}catch(ne){G||(d(null),p(ne instanceof Error?ne.message:"Unable to load this workspace cadence policy right now."))}finally{G||h(!1)}})(),()=>{G=!0}},[n==null?void 0:n.accessToken,r==null?void 0:r.apiServiceUrl]),w.useEffect(()=>{const q=r==null?void 0:r.apiServiceUrl,Y=n==null?void 0:n.accessToken;if(!q||!Y||P.length===0){b({});return}let G=!1;return(async()=>{const J=await Promise.all(P.map(async ne=>{try{const be=await fetch(`${q}/v1/integrations/${ne.toLowerCase()}/status`,{headers:{Authorization:`Bearer ${Y}`}}),te=await be.json().catch(()=>({}));return be.ok?[ne,{channel:ne,installed:!!te.installed,status:te.status,userLinked:!!te.userLinked}]:[ne,{channel:ne,installed:!1,userLinked:!1,error:te.error??`Unable to verify ${qM(ne)} availability`}]}catch(be){return[ne,{channel:ne,installed:!1,userLinked:!1,error:be instanceof Error?be.message:`Unable to verify ${qM(ne)} availability`}]}}));G||b(Object.fromEntries(J))})(),()=>{G=!0}},[n==null?void 0:n.accessToken,P,r==null?void 0:r.apiServiceUrl]);const V=w.useCallback((q,Y)=>{const G=s.draftDeliveryConfig.channels,J=Y?[...G,q]:G.filter(ne=>ne!==q);e.updateDeliveryConfig({channels:J})},[s.draftDeliveryConfig.channels,e]),R=w.useCallback((q,Y)=>{e.updateDeliveryConfig({channelConfigs:{...s.draftDeliveryConfig.channelConfigs,[q]:Y}})},[s.draftDeliveryConfig.channelConfigs,e]),U=w.useCallback(async()=>{const q=r==null?void 0:r.apiServiceUrl,Y=n==null?void 0:n.accessToken;if(!(!q||!Y||!s.prefillData)){c(!0),C(null),N(null);try{if(_)throw new Error(_);const G=HM(s.prefillData,s.draftJobConfig,s.selectedDrivers),J=j,ne=await fetch(`${q}/v1/alerts/wizard/sample-send`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Y}`},body:JSON.stringify({jobConfig:G,deliveryConfig:J,channels:J.channels,metricContext:$re(s.prefillData)})}),be=await ne.json().catch(()=>({})),te=Array.isArray(be.results)?be.results:[],ce=te.filter(ue=>ue.status==="FAILED"),se=te.filter(ue=>ue.status==="SENT");if(!ne.ok)throw ce.length>0?new Error(ce.map(ue=>`${ue.channel??"Channel"}: ${ue.error??"Failed"}`).join("; ")):new Error(be.error||"Preview send failed");if(ce.length>0){const ue=se.length>0?`Preview sent for ${se.length} channel(s).`:null;C(ue),N(ce.map(Re=>`${Re.channel??"Channel"}: ${Re.error??"Failed"}`).join("; "));return}C("Preview sent successfully")}catch(G){N(G instanceof Error?G.message:"Preview send failed")}finally{c(!1)}}},[n,j,s,r,_]),O=w.useCallback(async()=>{if(s.prefillData){N(null);try{if($)throw new Error("Checking Slack and Telegram delivery readiness. Try again in a moment.");if(B)throw new Error(B);if(_)throw new Error(_);const q=HM(s.prefillData,s.draftJobConfig,s.selectedDrivers),Y=j,J=(await o({kind:"ALERT",name:s.prefillData.suggestedName,scheduleExpr:A,timezone:M,jobConfig:q,deliveryConfig:Y})).alert.id;y({ruleId:J})}catch(q){N(q instanceof Error?q.message:"Unable to start watching")}}},[o,B,$,j,A,M,s,_]);return x?l.jsx(RHe,{ruleId:x.ruleId,metricName:((z=s.prefillData)==null?void 0:z.metricLabel)??"Metric",channels:s.draftDeliveryConfig.channels,onClose:t}):l.jsxs("div",{className:"flex flex-col gap-5",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-semibold",children:"Where should this surface?"}),l.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Choose where Semaphor should surface this signal for your team."})]}),l.jsx("div",{className:"rounded border p-4",children:l.jsx(DHe,{enabledChannels:s.draftDeliveryConfig.channels,channelConfigs:s.draftDeliveryConfig.channelConfigs??{},onChannelToggle:V,onConfigChange:R})}),T&&l.jsx("div",{className:"rounded border border-amber-200 bg-amber-50 p-4",children:l.jsx("p",{className:"text-xs text-amber-800",children:T})}),_&&l.jsx("div",{className:"rounded border border-amber-200 bg-amber-50 p-4",children:l.jsx("p",{className:"text-xs text-amber-800",children:_})}),f&&l.jsx("div",{className:"rounded border border-muted bg-muted/30 p-4",children:l.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading workspace cadence policy..."})}),m&&l.jsx("div",{className:"rounded border border-amber-200 bg-amber-50 p-4",children:l.jsxs("p",{className:"text-xs text-amber-800",children:[m," Semaphor will fall back to the default cadence if this check stays unavailable."]})}),$&&l.jsx("div",{className:"rounded border border-muted bg-muted/30 p-4",children:l.jsx("p",{className:"text-xs text-muted-foreground",children:"Checking Slack and Telegram delivery readiness..."})}),B&&l.jsx("div",{className:"rounded border border-amber-200 bg-amber-50 p-4",children:l.jsx("p",{className:"text-xs text-amber-800",children:B})}),S&&l.jsx("div",{className:"rounded border border-destructive/50 bg-destructive/10 p-4",children:l.jsx("p",{className:"text-xs text-destructive",children:S})}),v&&l.jsx("div",{className:"rounded border border-emerald-200 bg-emerald-50 p-4",children:l.jsx("p",{className:"text-xs text-emerald-700",children:v})}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Semaphor will evaluate this signal on the nearest supported workspace cadence:"," ",L,"."]}),l.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[l.jsx(re,{variant:"outline",size:"sm",onClick:e.prevStep,children:"Back"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Step 3 of 3"}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(re,{variant:"outline",size:"sm",onClick:U,disabled:a||s.draftDeliveryConfig.channels.length===0||!!_,children:a?"Sending...":"Send Preview"}),l.jsx(re,{size:"sm",onClick:O,disabled:i||s.draftDeliveryConfig.channels.length===0||!!_||$||!!B,children:i?"Starting...":"Start Watching"})]})]})]})}function YHe({wizard:e,onClose:t}){const{step:n}=e.state;return l.jsxs("div",{className:"flex h-full flex-col",children:[l.jsx("div",{className:"mb-4 flex items-center gap-3",children:[1,2,3].map(r=>l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:`flex h-7 w-7 items-center justify-center rounded-full text-xs font-medium ${r===n?"bg-primary text-primary-foreground":r<n?"bg-primary/20 text-primary":"bg-muted text-muted-foreground"}`,children:r<n?"✓":r}),l.jsx("span",{className:`text-xs ${r===n?"font-medium text-foreground":"text-muted-foreground"}`,children:r===1?"Signal & Intent":r===2?"Signal Sensitivity":"Where It Surfaces"}),r<3&&l.jsx("div",{className:"mx-1 h-px w-6 bg-border"})]},r))}),l.jsxs("div",{className:"flex-1 overflow-y-auto",children:[n===1&&l.jsx(yHe,{wizard:e}),n===2&&l.jsx(wHe,{wizard:e}),n===3&&l.jsx(qHe,{wizard:e,onClose:t})]})]})}function GHe({content:e}){return e?typeof e.html=="string"?l.jsx("div",{className:"prose prose-sm max-w-none rounded border bg-white p-4",dangerouslySetInnerHTML:{__html:e.html}}):l.jsx("p",{className:"text-xs text-muted-foreground",children:"No email preview available."}):l.jsx(rs,{className:"h-64 w-full"})}function KHe({content:e}){if(!e)return l.jsx(rs,{className:"h-64 w-full"});const t=Array.isArray(e.blocks)?e.blocks:[],n=typeof e.text=="string"?e.text:null;return l.jsxs("div",{className:"space-y-2 rounded bg-slate-50 p-4",children:[t.length>0?t.map((r,s)=>{var o,i;return l.jsxs("div",{className:"text-sm",children:[r.type==="header"&&l.jsx("h4",{className:"font-bold",children:String(((o=r.text)==null?void 0:o.text)??"")}),r.type==="section"&&l.jsx("p",{children:String(((i=r.text)==null?void 0:i.text)??"")}),r.type==="divider"&&l.jsx("hr",{className:"my-2"})]},s)}):n&&l.jsx("p",{className:"whitespace-pre-wrap text-sm",children:n}),t.length===0&&!n&&l.jsx("p",{className:"text-xs text-muted-foreground",children:"No Slack preview available."})]})}function ZHe({content:e}){if(!e)return l.jsx(rs,{className:"h-64 w-full"});const t=typeof e.text=="string"?e.text:null;return t?l.jsx("div",{className:"rounded-lg bg-blue-50 p-4",children:l.jsx("p",{className:"whitespace-pre-wrap text-sm",children:t})}):l.jsx("p",{className:"text-xs text-muted-foreground",children:"No Telegram preview available."})}function XHe({content:e}){return e?l.jsx("pre",{className:"overflow-auto rounded bg-gray-900 p-4 text-xs text-gray-100",children:JSON.stringify(e,null,2)}):l.jsx(rs,{className:"h-64 w-full"})}function QHe({content:e}){if(!e)return l.jsx(rs,{className:"h-64 w-full"});const t=typeof e.title=="string"?e.title:"Alert",n=typeof e.body=="string"?e.body:"",r=typeof e.actionUrl=="string"?e.actionUrl:null;return l.jsxs("div",{className:"rounded-lg border p-4",children:[l.jsx("div",{className:"font-semibold text-sm",children:t}),n&&l.jsx("div",{className:"mt-1 text-sm text-muted-foreground",children:n}),r&&l.jsx(re,{variant:"link",className:"mt-2 h-auto p-0 text-xs",children:"View Details →"})]})}function JHe({wizard:e}){const{authToken:t,tokenProps:n}=rt(),{state:r}=e,{draftDeliveryConfig:s,draftJobConfig:o,prefillData:i}=r,[a,c]=w.useState({}),[u,d]=w.useState(""),f=w.useRef(null),h=w.useRef(0),m=s.channels;return w.useEffect(()=>{m.length>0&&!m.includes(u)&&d(m[0])},[m,u]),w.useEffect(()=>{if(!u||!i)return;const p=n==null?void 0:n.apiServiceUrl,g=t==null?void 0:t.accessToken;if(!p||!g)return;f.current&&clearTimeout(f.current);const b=Lre(s,n),x=HM(i,o,r.selectedDrivers),y=h.current+1;return h.current=y,f.current=setTimeout(async()=>{try{const v=await fetch(`${p}/v1/alerts/preview-deliverable`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${g}`},body:JSON.stringify({channels:[u],jobConfig:x,deliveryConfig:b,metricContext:$re(i)})});if(v.ok){const C=await v.json();if(h.current!==y)return;c(S=>{var N;return{...S,[u]:$He(u,(N=C.previews)==null?void 0:N[u])}})}else h.current===y&&c(C=>({...C,[u]:null}))}catch{h.current===y&&c(v=>({...v,[u]:null}))}},300),()=>{f.current&&clearTimeout(f.current)}},[u,t==null?void 0:t.accessToken,s,o,i,r.selectedDrivers,n]),m.length===0?l.jsx("div",{className:"flex h-full flex-col items-center justify-center text-center",children:l.jsx("p",{className:"text-sm text-muted-foreground",children:"Enable a channel to see preview."})}):l.jsxs("div",{className:"flex h-full flex-col",children:[l.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Live Preview"}),l.jsxs(As,{value:u,onValueChange:d,className:"flex-1",children:[l.jsx(ys,{className:"w-full",children:m.map(p=>l.jsx(on,{value:p,className:"text-xs",children:p},p))}),m.map(p=>l.jsxs(sr,{value:p,className:"mt-3 h-[calc(100%-3rem)]",children:[p==="EMAIL"&&l.jsx(GHe,{content:a[p]??null}),p==="SLACK"&&l.jsx(KHe,{content:a[p]??null}),p==="TELEGRAM"&&l.jsx(ZHe,{content:a[p]??null}),p==="WEBHOOK"&&l.jsx(XHe,{content:a[p]??null}),p==="IN_APP"&&l.jsx(QHe,{content:a[p]??null})]},p))]})]})}const eWe="standard";function YM(){return UO(eWe)}function tWe(e,t){switch(t.type){case"START_PREFILL":return{...e,step:1,prefillData:null,prefillLoading:!0,prefillError:null,draftJobConfig:YM(),draftDeliveryConfig:{channels:["EMAIL"]},selectedDrivers:[]};case"RESET_PREFILL":return{...e,step:1,prefillData:null,prefillLoading:!1,prefillError:null,draftJobConfig:YM(),draftDeliveryConfig:{channels:["EMAIL"]},selectedDrivers:[]};case"SET_PREFILL":return{...e,prefillData:t.payload,prefillLoading:!1,prefillError:null,draftJobConfig:{...e.draftJobConfig,source:t.payload.source}};case"SET_PREFILL_ERROR":return{...e,prefillLoading:!1,prefillError:t.error};case"NEXT_STEP":return{...e,step:Math.min(3,e.step+1)};case"PREV_STEP":return{...e,step:Math.max(1,e.step-1)};case"SET_SENSITIVITY":return{...e,draftJobConfig:{...e.draftJobConfig,...UO(t.payload)}};case"TOGGLE_DRIVER":{const n=e.selectedDrivers.includes(t.driverId)?e.selectedDrivers.filter(r=>r!==t.driverId):[...e.selectedDrivers,t.driverId];return{...e,selectedDrivers:n}}case"UPDATE_JOB_CONFIG":return{...e,draftJobConfig:{...e.draftJobConfig,...t.payload}};case"UPDATE_DELIVERY_CONFIG":return{...e,draftDeliveryConfig:{...e.draftDeliveryConfig,...t.payload}};default:return e}}function nWe(e,t){const n=t!=null&&t.format&&(!e.source.format||JSON.stringify(e.source.format)!==JSON.stringify(t.format))?{...e.source,format:t.format}:e.source,r=e.currentValue!==null||typeof(t==null?void 0:t.currentValue)!="number"||!Number.isFinite(t.currentValue)?e.currentValue:t.currentValue;return n===e.source&&r===e.currentValue?e:{...e,source:n,currentValue:r}}const gT=new Map;function zre({cardSnapshot:e}){const{authToken:t,tokenProps:n}=rt(),r=e==null?void 0:e.dashboardId,s=e==null?void 0:e.visualId,o=e==null?void 0:e.cardId,i=e==null?void 0:e.executionSnapshot,a=w.useMemo(()=>!r||!s||!o?null:JSON.stringify({dashboardId:r,visualId:s,cardId:o,executionSnapshot:i}),[o,r,i,s]),c=w.useMemo(()=>a?JSON.parse(a):null,[a]),[u,d]=w.useReducer(tWe,{step:1,prefillData:null,prefillLoading:!0,prefillError:null,draftJobConfig:YM(),draftDeliveryConfig:{channels:["EMAIL"]},selectedDrivers:[]}),f=w.useRef(e),h=w.useRef(null);f.current=e,w.useEffect(()=>{if(!c){h.current=null,d({type:"RESET_PREFILL"});return}const v=n==null?void 0:n.apiServiceUrl,C=t==null?void 0:t.accessToken;if(!v||!C){h.current=null,d({type:"START_PREFILL"});return}const S=`${v}:${a}`;let N=!1;h.current!==S&&(h.current=S,d({type:"START_PREFILL"}));let j=gT.get(S);return j||(j=fetch(`${v}/v1/alerts/wizard/prefill`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C}`},body:JSON.stringify({sourceType:"dashboard_metric",...c})}).then(async k=>{if(!k.ok){const T=await k.json().catch(()=>({}));throw new Error(T.error||"Failed to load wizard data")}return await k.json()}),gT.set(S,j),j.finally(()=>{gT.delete(S)})),j.then(k=>{N||d({type:"SET_PREFILL",payload:nWe(k,f.current)})}).catch(k=>{N||d({type:"SET_PREFILL_ERROR",error:k instanceof Error?k.message:"Failed to load wizard data"})}),()=>{N=!0}},[t==null?void 0:t.accessToken,a,c,n==null?void 0:n.apiServiceUrl]);const m=w.useCallback(()=>d({type:"NEXT_STEP"}),[]),p=w.useCallback(()=>d({type:"PREV_STEP"}),[]),g=w.useCallback(v=>d({type:"TOGGLE_DRIVER",driverId:v}),[]),b=w.useCallback(v=>d({type:"UPDATE_JOB_CONFIG",payload:v}),[]),x=w.useCallback(v=>d({type:"UPDATE_DELIVERY_CONFIG",payload:v}),[]),y=w.useCallback(v=>d({type:"SET_SENSITIVITY",payload:v}),[]);return{state:u,dispatch:d,nextStep:m,prevStep:p,toggleDriver:g,updateJobConfig:b,updateDeliveryConfig:x,setSensitivity:y}}function qO({open:e,onOpenChange:t,cardSnapshot:n}){const r=zre({cardSnapshot:e?n:null}),s=()=>t(!1);return l.jsx(zr,{open:e,onOpenChange:t,children:l.jsxs(Tr,{className:"max-w-7xl h-[90vh] flex flex-col gap-0 p-0",children:[l.jsx(_r,{className:"border-b px-6 py-4",children:l.jsx(Ir,{className:"text-base",children:"Watch this metric?"})}),l.jsxs("div",{className:"flex flex-1 gap-0 overflow-hidden",children:[l.jsx("div",{className:"w-3/5 overflow-y-auto border-r p-6",children:l.jsx(YHe,{wizard:r,onClose:s})}),l.jsx("div",{className:"w-2/5 overflow-y-auto bg-muted/30 p-6",children:l.jsx(JHe,{wizard:r})})]})]})})}function GM(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(Array.isArray(e)){for(const t of e){const n=GM(t);if(n!==null)return n}return null}if(e&&typeof e=="object")for(const t of Object.values(e)){const n=GM(t);if(n!==null)return n}return null}function X8(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return typeof t.connectionId!="string"||typeof t.connectionType!="string"||!Array.isArray(t.selectedEntities)?null:t}function rWe(e){if(e!=null&&e.dataSource)return e.dataSource;if(!(e!=null&&e.queryConfig)||typeof e.queryConfig!="object"||Array.isArray(e.queryConfig))return null;const t=e.queryConfig;return X8(t.cardDataSource)??X8(t.dataSource)}function sWe({card:e,dashboardId:t,visualId:n,accessToken:r,activeFilters:s,controlValues:o,controlDefinitions:i,cardControlDefinitions:a,controlBindings:c,calendarContext:u}){if(!e||!t||!n||!e.connectionId)return;const d=rWe(e);if(d)return{type:"dashboard_metric",dashboardId:t,visualId:n,cardId:e.id,title:e.title||"Metric card",format:u7e({card:e,accessToken:r}),executionSnapshot:{queryConfig:{cardType:e.type,cardMode:"explorer",cardConfig:e.config||{},cardDataSource:d,connectionId:e.connectionId},filterContext:{active_filters:s},...o!==void 0?{controlContext:{values:o}}:{},...i&&i.length>0?{controlDefinitions:i}:{},...a&&a.length>0?{cardControlDefinitions:a}:{},...c&&c.length>0?{controlBindings:c}:{},connectionId:e.connectionId,calendarContext:u}}}function Vre(e,t){return(e==null?void 0:e.type)!=="dashboard_metric"?null:{dashboardId:e.dashboardId,visualId:e.visualId,cardId:e.cardId,title:e.title,...t!==void 0?{currentValue:GM(t)}:{},format:e.format,executionSnapshot:e.executionSnapshot}}const oWe=[{key:"all",label:"All"},{key:"ACTIVE",label:"Watching"},{key:"firing",label:"Surfaced"},{key:"PAUSED",label:"Paused"}];function iWe(e){if(!e)return"--";const t=new Date(e);return Number.isNaN(t.getTime())?"--":t.toLocaleString()}function aWe(e){var t;return((t=e.alertState)==null?void 0:t.currentState)==="FIRING"?"destructive":e.status==="ACTIVE"?"default":e.status==="PAUSED"?"secondary":"outline"}function lWe(e){var t;return((t=e.alertState)==null?void 0:t.currentState)==="FIRING"?"Signal surfaced":e.status==="ACTIVE"?"Watching":e.status==="PAUSED"?"Paused":"Inactive"}function cWe(e,t){return!(t!=null&&t.dashboardId)&&!(t!=null&&t.cardId)?!0:!(e.jobConfig.source.type!=="dashboard_metric"||t.dashboardId&&e.jobConfig.source.dashboardId!==t.dashboardId||t.cardId&&e.jobConfig.source.cardId!==t.cardId)}function Bre({scope:e,prefilledSource:t,allowCreateSignalWatch:n=!0,onOpenAlertDetail:r,onCreateSignalWatch:s}){const{tokenProps:o}=rt(),{alerts:i,isLoading:a,error:c,refetch:u,updateAlert:d,deleteAlert:f,triggerAlert:h,isUpdating:m,isDeleting:p,isTriggering:g}=DF(),[b,x]=w.useState("all"),[y,v]=w.useState(""),[C,S]=w.useState(!1),[N,j]=w.useState(null),k=w.useMemo(()=>i.filter(D=>cWe(D,e)),[i,e]),T=w.useMemo(()=>{const D=y.trim().toLowerCase();return k.filter(A=>{var L,$;return b==="ACTIVE"&&(A.status!=="ACTIVE"||((L=A.alertState)==null?void 0:L.currentState)==="FIRING")||b==="PAUSED"&&A.status!=="PAUSED"||b==="firing"&&(($=A.alertState)==null?void 0:$.currentState)!=="FIRING"?!1:D?A.name.toLowerCase().includes(D)||(A.description||"").toLowerCase().includes(D):!0})},[k,y,b]),E=w.useMemo(()=>({all:k.length,ACTIVE:k.filter(D=>{var A;return D.status==="ACTIVE"&&((A=D.alertState)==null?void 0:A.currentState)!=="FIRING"}).length,PAUSED:k.filter(D=>D.status==="PAUSED").length,firing:k.filter(D=>{var A;return((A=D.alertState)==null?void 0:A.currentState)==="FIRING"}).length}),[k]),_=w.useMemo(()=>{if((t==null?void 0:t.type)==="dashboard_metric")return t},[t]),M=w.useMemo(()=>Vre(_),[_]),P=n&&!!M;return l.jsxs("div",{className:"space-y-4 p-4",children:[l.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-xl font-semibold",children:"Signals"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:e!=null&&e.cardId?"Manage signal watches for this card and investigate what changes.":"See what changed, why it matters, and where to investigate."}),n?P?null:l.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Start a new watch from a dashboard signal card so Semaphor can use that signal context."}):l.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Start new signal watches from a dashboard signal card."})]}),l.jsxs("div",{className:"inline-flex items-center gap-2",children:[l.jsxs(re,{size:"sm",variant:"outline",onClick:()=>u(),children:[l.jsx(WU,{className:"mr-1 h-4 w-4"}),"Refresh"]}),n?l.jsxs(re,{onClick:()=>S(!0),variant:"default",size:"sm",disabled:!P,title:P?"Watch this signal":"Open this from a dashboard signal card to start watching it",children:[l.jsx(Y_,{className:"mr-1 h-4 w-4"}),"Watch a Signal"]}):s?l.jsxs(re,{onClick:s,variant:"default",size:"sm",children:[l.jsx(Y_,{className:"mr-1 h-4 w-4"}),"Choose a Signal"]}):null]})]}),l.jsx("div",{className:"flex flex-wrap items-center gap-2",children:oWe.map(D=>l.jsxs(re,{size:"sm",variant:b===D.key?"default":"outline",onClick:()=>x(D.key),children:[D.label,l.jsx("span",{className:"ml-1 text-xs opacity-80",children:E[D.key]})]},D.key))}),l.jsx(lt,{value:y,onChange:D=>v(D.target.value),placeholder:"Search signals and watches","aria-label":"Search signals and watches",className:"max-w-sm"}),a&&l.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading signals..."}),c&&l.jsx("p",{className:"text-sm text-destructive",children:"Failed to load signals."}),!a&&T.length===0&&l.jsx("div",{className:"rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground",children:"No signals configured yet. Start watching an important business change."}),T.length>0&&l.jsx("div",{className:"overflow-hidden rounded-lg border",children:l.jsxs("table",{className:"w-full text-sm",children:[l.jsx("thead",{className:"bg-muted/40",children:l.jsxs("tr",{children:[l.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Signal"}),l.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Status"}),l.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Where It Surfaces"}),l.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Watching For"}),l.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Last Check"}),l.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Actions"})]})}),l.jsx("tbody",{children:T.map(D=>{var A,L;return l.jsxs("tr",{className:"border-t",children:[l.jsxs("td",{className:"px-3 py-2 align-top",children:[l.jsx("p",{className:"font-medium",children:D.name}),D.description?l.jsx("p",{className:"text-xs text-muted-foreground",children:D.description}):null]}),l.jsx("td",{className:"px-3 py-2 align-top",children:l.jsx(Xe,{variant:aWe(D),children:lWe(D)})}),l.jsx("td",{className:"px-3 py-2 align-top",children:l.jsx("div",{className:"flex flex-wrap gap-1",children:(((A=D.deliveryConfig)==null?void 0:A.channels)??[]).map($=>l.jsx(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:$},$))})}),l.jsx("td",{className:"px-3 py-2 align-top text-xs text-muted-foreground",children:Ore(D.jobConfig.operator,D.jobConfig.threshold)}),l.jsx("td",{className:"px-3 py-2 align-top text-xs text-muted-foreground",children:iWe(((L=D.alertState)==null?void 0:L.lastEvaluatedAt)||D.lastRunAt)}),l.jsx("td",{className:"px-3 py-2 align-top",children:l.jsxs("div",{className:"inline-flex flex-wrap items-center gap-1",children:[l.jsxs(re,{size:"sm",variant:"outline",onClick:()=>r==null?void 0:r(D),disabled:!r,children:[l.jsx(Ws,{className:"mr-1 h-3.5 w-3.5"}),"Investigate"]}),l.jsxs(re,{size:"sm",variant:"outline",onClick:async()=>{try{await h(D.id),qe.success("Signal watch run started")}catch($){qe.error($ instanceof Error?$.message:"Failed to start signal watch run")}},disabled:g,title:"Run this signal watch now",children:[l.jsx(KA,{className:"mr-1 h-3.5 w-3.5"}),"Run Now"]}),D.status==="ACTIVE"?l.jsxs(re,{size:"sm",variant:"outline",onClick:async()=>{try{await d({id:D.id,payload:{status:"PAUSED"}}),qe.success("Signal watch paused")}catch($){qe.error($ instanceof Error?$.message:"Failed to pause signal watch")}},disabled:m,children:[l.jsx(kpe,{className:"mr-1 h-3.5 w-3.5"}),"Pause"]}):l.jsxs(re,{size:"sm",variant:"outline",onClick:async()=>{try{await d({id:D.id,payload:{status:"ACTIVE"}}),qe.success("Signal watch resumed")}catch($){qe.error($ instanceof Error?$.message:"Failed to resume signal watch")}},disabled:m,children:[l.jsx(YA,{className:"mr-1 h-3.5 w-3.5"}),"Resume"]}),l.jsxs(re,{size:"sm",variant:"outline",onClick:()=>j(D),disabled:p,children:[l.jsx(La,{className:"mr-1 h-3.5 w-3.5"}),"Remove Watch"]})]})})]},D.id)})})]})}),l.jsx(qO,{open:C,onOpenChange:S,cardSnapshot:M}),l.jsx(qc,{open:!!N,onOpenChange:D=>{D||j(null)},children:l.jsxs(Pl,{children:[l.jsxs(Ol,{children:[l.jsx($l,{children:"Remove This Signal Watch?"}),l.jsx(zl,{children:N?`This will permanently remove "${N.name}" and cannot be undone.`:"This action cannot be undone."})]}),l.jsxs(Ll,{children:[l.jsx(Bl,{disabled:p,children:"Cancel"}),l.jsx(Vl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:p||!N,onClick:async D=>{if(D.preventDefault(),!!N)try{await f(N.id),qe.success("Signal watch removed"),j(null)}catch(A){qe.error(A instanceof Error?A.message:"Failed to remove signal watch")}},children:"Remove Watch"})]})]})})]})}function Ure({frame:e,isHovered:t,isExpandedViewOpen:n=!1,onExpandClick:r}){var Ke,Ze,st;const{authToken:s,tokenProps:o}=rt(),[i,a]=w.useState(!1),{openPopover:c}=jP(),[u,d]=w.useState(!1),[f,h]=w.useState(!1),[m,p]=w.useState(!1),[g,b]=w.useState(!1),[x,y]=w.useState(!1),[v,C]=w.useState(""),[S,N]=w.useState(!1),[j,k]=w.useState(!1),T=r?n:j,E=r||(()=>k(!0)),_=w.useRef(null),M=w.useRef(null),P=ee(ae=>ae.isDashboardEditing),D=ee(ae=>ae.isDownloadingPdf),A=ee(ae=>ae.selectedSheetId),L=ee(ae=>{var Pe;return(Pe=ae.dashboard)==null?void 0:Pe.id}),$=ee(ae=>{var Pe;return(Pe=ae.dashboard)==null?void 0:Pe.title}),{removeFrame:B,addFrame:V,setSelectedFrameId:R}=ee(ae=>ae.actions),U=e.cards.find(ae=>ae.id===e.activeCardId),{handleEditVisual:O,card:I,data:W}=fPe(e),X=MF((I==null?void 0:I.id)||""),{cardFilterValues:Z}=NP((I==null?void 0:I.id)||""),H=bs(ae=>ae.selectedDashboard),K=bs(ae=>ae.initialDashboard),z=H?(Ze=H==null?void 0:H.permissions)==null?void 0:Ze.canEdit:(Ke=K==null?void 0:K.permissions)==null?void 0:Ke.canEdit,q=ee(ae=>ae.inlineFilterValuesMap[(I==null?void 0:I.id)||""]),Y=w.useMemo(()=>[...Z||[],...q||[]],[Z,q]),G=!!(I&&L&&I.type==="kpi"&&I.connectionId&&(o!=null&&o.apiServiceUrl)&&(s!=null&&s.accessToken)),J=X.length,ne=J>0,be=e.visualId||(I==null?void 0:I.id),te=(st=o==null?void 0:o.params)!=null&&st.calendarContext&&typeof o.params.calendarContext=="object"?o.params.calendarContext:void 0,ce=te&&typeof te.tz=="string"?te.tz:"UTC",se=te&&te.weekStart!==void 0?Number(te.weekStart):1,{controlValues:ue,controlDefinitions:Re,cardControlDefinitions:je,controlBindings:ke}=HN(I),me=w.useMemo(()=>{if(G)return sWe({card:I,dashboardId:L,visualId:be,accessToken:s==null?void 0:s.accessToken,activeFilters:Y,controlValues:ue,controlDefinitions:Re,cardControlDefinitions:je,controlBindings:ke,calendarContext:{tz:ce,weekStart:se}})},[s==null?void 0:s.accessToken,G,I,L,be,Y,ue,Re,je,ke,ce,se]),Me=w.useMemo(()=>Vre(me,(W==null?void 0:W.records)??W),[W,me]),Se=w.useMemo(()=>{if(!(!me||me.type!=="dashboard_metric"))return{dashboardId:me.dashboardId,cardId:me.cardId}},[me]);w.useEffect(()=>()=>{M.current&&clearTimeout(M.current)},[]);const ie=()=>{M.current&&clearTimeout(M.current),a(!0)},pe=()=>{M.current=setTimeout(()=>{a(!1)},300)},Ne=()=>{a(!1),M.current&&clearTimeout(M.current)},de=async()=>{if(!v)return;d(!1),C(""),N(!1);const ae=qe.loading("Generating protected PDF report... may take up to 60 seconds");try{await SPe(o.apiServiceUrl,s,e.activeCardId||"",e.id,(I==null?void 0:I.title)||"visual",I==null?void 0:I.type,v,void 0,void 0,void 0,Y),qe.dismiss(ae),qe.success("Protected visual PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(Pe){qe.dismiss(ae),qe.error("Failed to download protected visual PDF. Please try again."),console.error("Protected visual PDF download error:",Pe)}},fe=()=>{if(A)try{const ae=JSON.parse(JSON.stringify(e)),Pe=yre(ae),Ee=Pe.cards.findIndex(_e=>_e.id===Pe.activeCardId);Ee!==-1&&(Pe.cards[Ee].title=`${Pe.cards[Ee].title} (Copy)`),V(A,Pe,{insertAfterFrameId:e.id,copyLayoutFromFrameId:e.id}),R(Pe.id),qe.success("Card duplicated successfully")}catch(ae){console.error("Failed to duplicate frame:",ae),qe.error("Failed to duplicate card")}},Oe=()=>{const{theme:ae,defaultControlValues:Pe,controlDefinitions:Ee,cardControlDefinitions:_e,controlBindings:We,selectedSheetId:Te,dashboardId:Ue}=WJ(s,e.activeCardId,e.id,(I==null?void 0:I.title)||(U==null?void 0:U.title)||""),et=new URLSearchParams;et.set("token",(s==null?void 0:s.accessToken)||""),et.set("theme",ae),et.set("filterValues",JSON.stringify(Y||[])),et.set("controlValues",JSON.stringify(Pe||{})),BJ(et,{controlDefinitions:Ee,cardControlDefinitions:_e,controlBindings:We}),et.set("cardTitle",(I==null?void 0:I.title)||(U==null?void 0:U.title)||""),et.set("selectedSheetId",Te||""),et.set("dashboardId",Ue||"");const bt=e.activeCardId,dt=cHe({apiServiceUrl:o==null?void 0:o.apiServiceUrl,dashboardId:Ue,cardId:bt,params:et});if(!dt){qe.error("Unable to open this visual in a new window.");return}window.open(dt,"_blank","noopener,noreferrer")},ye=(I==null?void 0:I.type)==="kpi",Ce=(I==null?void 0:I.type)==="text",$e={editVisual:{visible:P&&z},duplicateFrame:{visible:P&&z},expand:{visible:!ye&&!Ce},export:{visible:!ye&&!Ce},alertAction:{visible:!!G},deleteCard:{visible:P&&z},moreOptions:{visible:!ye&&!Ce,submenu:{interactions:{visible:P&&z&&!!(U!=null&&U.config)&&!ye&&!Ce},schedule:{visible:!ye&&!Ce&&!P}}}},ze=$e.editVisual.visible||$e.duplicateFrame.visible||$e.expand.visible||$e.export.visible||$e.alertAction.visible||$e.deleteCard.visible||$e.moreOptions.visible,Ge=t&&!T&&ze;return l.jsxs(l.Fragment,{children:[Ge&&l.jsx("div",{ref:_,className:"absolute right-2 top-2 z-50 duration-200 animate-in fade-in-0 zoom-in-95",onMouseLeave:Ne,children:l.jsx(xi,{className:"min-w-[32px] border-border bg-popover p-0.5 shadow-lg",children:l.jsxs("div",{className:"flex flex-row gap-0.5",children:[$e.alertAction.visible&&l.jsxs(re,{variant:"ghost",size:"sm",className:"relative h-6 w-6 p-0 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:ae=>{ae.stopPropagation(),ne?y(!0):b(!0),a(!1)},disabled:!1,title:ne?`Manage watches (${J})`:"Watch this signal","aria-label":ne?`Manage ${J} signal watch${J===1?"":"es"}`:"Watch this signal",children:[ne?l.jsx(Fm,{className:"h-3.5 w-3.5"}):l.jsx(Y_,{className:"h-3.5 w-3.5"}),ne?l.jsx("span",{className:"absolute -right-1 -top-1 min-w-[0.85rem] rounded-full bg-primary px-[3px] text-[9px] leading-3 text-primary-foreground",children:J>9?"9+":J}):null]}),$e.moreOptions.visible&&l.jsxs("div",{className:"relative",children:[l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-accent hover:text-accent-foreground",onMouseEnter:ie,onMouseLeave:pe,onClick:ae=>ae.stopPropagation(),title:"More Options",children:l.jsx(_h,{className:"h-3.5 w-3.5"})}),i&&l.jsx("div",{className:"z-60 absolute right-full top-0 mr-0.5 duration-150 animate-in fade-in-0 zoom-in-95",onMouseEnter:ie,onMouseLeave:pe,children:l.jsx(xi,{className:"min-w-[140px] border-border bg-popover p-0.5 shadow-lg",children:l.jsxs("div",{className:"flex flex-col gap-0.5",children:[$e.moreOptions.submenu.interactions.visible&&l.jsxs(re,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:ae=>{ae.stopPropagation(),R(e.id);const Pe=e.activeCardId;Pe&&c(e.id,Pe,ae.currentTarget),a(!1)},children:[l.jsx(eg,{className:"mr-1.5 h-3.5 w-3.5"}),l.jsx("span",{className:"text-xs",children:"Interactions"})]}),$e.export.visible&&l.jsxs(re,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:ae=>{ae.stopPropagation(),h(!0),a(!1)},children:[l.jsx(Th,{className:"mr-1.5 h-3.5 w-3.5"}),l.jsx("span",{className:"text-xs",children:"Download"})]}),l.jsxs(re,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:ae=>{ae.stopPropagation(),Oe()},children:[l.jsx(pp,{className:"mr-1.5 h-3.5 w-3.5"}),l.jsx("span",{className:"text-xs",children:"Open in New Window"})]}),$e.moreOptions.submenu.schedule.visible&&l.jsxs(re,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:ae=>{ae.stopPropagation(),p(!0),a(!1)},children:[l.jsx(Yu,{className:"mr-1.5 h-3.5 w-3.5"}),l.jsx("span",{className:"text-xs",children:"Schedule Export"})]})]})})})]}),$e.deleteCard.visible&&l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-destructive hover:text-destructive-foreground",onClick:ae=>{ae.stopPropagation(),B(A,e.id)},disabled:!1,title:"Delete Card",children:l.jsx(La,{className:"h-3.5 w-3.5"})}),$e.duplicateFrame.visible&&l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:ae=>{ae.stopPropagation(),fe()},disabled:!1,title:"Duplicate Card",children:l.jsx(PU,{className:"h-3.5 w-3.5"})}),$e.expand.visible&&l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:ae=>{ae.stopPropagation(),E(),a(!1)},disabled:!1,title:"Expand View",children:l.jsx(xN,{className:"h-3.5 w-3.5"})}),$e.editVisual.visible&&l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-primary hover:text-primary-foreground",onClick:ae=>{ae.stopPropagation(),O()},disabled:!1,title:"Edit Visual",children:l.jsx(yN,{className:"h-3.5 w-3.5"})})]})})}),l.jsx(zr,{open:u,onOpenChange:d,children:l.jsxs(Tr,{className:"sm:max-w-[425px]",children:[l.jsxs(_r,{children:[l.jsx(Ir,{children:"Download Protected Visual PDF"}),l.jsx(ss,{children:"Enter a password to protect your visual PDF. The PDF will be encrypted and require this password to open."})]}),l.jsx("div",{className:"grid gap-4 py-4",children:l.jsxs("div",{className:"grid gap-2",children:[l.jsx(ge,{htmlFor:"password",children:"Password"}),l.jsxs("div",{className:"relative",children:[l.jsx(lt,{id:"password",type:S?"text":"password",value:v,onChange:ae=>C(ae.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:ae=>{ae.key==="Enter"&&v&&de()}}),l.jsx(re,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>N(!S),children:S?l.jsx(mN,{className:"h-4 w-4 text-muted-foreground"}):l.jsx(Gu,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),l.jsxs(Ds,{children:[l.jsx(re,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),l.jsx(re,{onClick:de,disabled:!v||D,children:"Download"})]})]})}),!r&&j&&l.jsx(CUe,{isOpen:j,onClose:()=>k(!1),frame:e,card:I,data:W}),l.jsx(FP,{isOpen:f,onClose:()=>h(!1),frame:e,card:I,data:W}),l.jsx(Ire,{open:m,onOpenChange:p,dashboardId:L||"",dashboardName:$,preSelectedVisual:I?{visualId:I.id,cardType:I.type,title:I.title||"Visual",type:"visual",format:RP(I.type),supportedFormats:AP(I.type),settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0,inlineFilterValues:q}}:void 0}),l.jsx(qO,{open:g,onOpenChange:b,cardSnapshot:Me}),l.jsx(zr,{open:x,onOpenChange:y,children:l.jsxs(Tr,{className:"max-h-[92vh] overflow-auto sm:max-w-5xl",children:[l.jsxs(_r,{children:[l.jsx(Ir,{children:"Manage Signal Watches"}),l.jsx(ss,{children:"Review surfaced signals, pause watches, send previews, and remove watches for this dashboard."})]}),l.jsx(Bre,{scope:Se,prefilledSource:me})]})})]})}Ure.displayName="CardControlsToolbar";const Hre=w.memo(Ure);function YO({card:e}){const t=ee(v=>v.isVisualEditing),{setCardInfo:n}=lr(),[r,s]=w.useState(!1),[o,i]=w.useState(!1),[a,c]=w.useState(e.info||""),u=w.useRef(null),d=e.info||"",f=d.trim(),h=a.trim(),m=w.useMemo(()=>h!==f,[f,h]);w.useEffect(()=>{o||c(d)},[d,o]),w.useEffect(()=>{if(!o)return;const v=u.current;if(!v)return;v.focus();const C=v.value.length;v.setSelectionRange(C,C)},[o]);const p=()=>{t&&(c(d),i(!0))},g=()=>{c(d),i(!1)},b=()=>{if(t){if(!m){i(!1);return}n(h),i(!1)}},x=v=>{v||g(),s(v)},y="Describe what this card shows";return l.jsxs(Gr,{open:r,onOpenChange:x,children:[l.jsx(Kr,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":f?"View card info":"Add card info",className:"inline-flex items-center justify-center text-muted-foreground/40 transition-colors hover:text-muted-foreground",onMouseDown:v=>v.stopPropagation(),onClick:v=>v.stopPropagation(),children:l.jsx(hr,{className:"size-4"})})}),l.jsx(Zr,{align:"start",className:"w-[340px] p-3",onMouseDown:v=>v.stopPropagation(),onClick:v=>v.stopPropagation(),children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"About this visual"}),o?l.jsxs(l.Fragment,{children:[l.jsx(yi,{ref:u,value:a,onChange:v=>c(v.target.value),onKeyDown:v=>{v.key==="Escape"&&(v.preventDefault(),g()),(v.metaKey||v.ctrlKey)&&v.key==="Enter"&&(v.preventDefault(),b())},className:"min-h-[120px] resize-y text-sm",placeholder:y}),l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("span",{className:"text-xs text-muted-foreground",children:"Press Ctrl/Cmd+Enter to save"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(re,{size:"sm",variant:"outline",onClick:g,children:"Cancel"}),l.jsx(re,{size:"sm",onClick:b,disabled:!m,children:"Save"})]})]})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"max-h-52 overflow-y-auto whitespace-pre-wrap text-sm text-muted-foreground",children:f?d:l.jsx("span",{className:"italic text-muted-foreground/80",children:y})}),t&&l.jsx("div",{className:"flex justify-end",children:l.jsx(re,{size:"sm",variant:f?"outline":"default",onClick:p,children:f?"Edit":"Add info"})})]})]})})]})}function uWe({card:e,renderFilterInfo:t}){var y,v,C,S,N,j,k,T,E;ee(_=>_.themeStyle);const{data:n,isLoading:r}=kl(e),s=(n==null?void 0:n.records)||[],{getCurrency:o,getLocale:i,getPrimaryFormat:a}=rE(e),c=(v=(y=e.preferences)==null?void 0:y.formatNumber)==null?void 0:v.colorRanges,u=Oa(a()),d=(S=(C=e.preferences)==null?void 0:C.formatNumber)==null?void 0:S.enabled,f=d===!1||d==="false",{keys:h}=Qn(s||[]),m=(N=s==null?void 0:s[0])==null?void 0:N[h==null?void 0:h[0]],p=(j=s==null?void 0:s[0])==null?void 0:j[h==null?void 0:h[1]],g=(s==null?void 0:s.length)>0,b=p&&p-m!==0?(m-p)/p:null,x=_=>{var M,P,D,A,L,$;return f?String(_):u!=null&&u.type&&u.type!=="auto"?kn(_,u.type,{...u,locale:u.locale||i()||"",currency:u.currency||o()||""}):Lp({number:_,decimalPlaces:((P=(M=e.preferences)==null?void 0:M.formatNumber)==null?void 0:P.decimalPlaces)||0,useSuffix:!!((A=(D=e.preferences)==null?void 0:D.formatNumber)!=null&&A.suffix),customSuffix:(($=(L=e.preferences)==null?void 0:L.formatNumber)==null?void 0:$.suffix)||"",locale:i()||"",currency:o()||""})};return l.jsx("div",{className:"flex min-w-fit grow flex-col overflow-auto",children:l.jsxs("div",{className:"grow",children:[g?l.jsx("div",{className:"",children:l.jsxs("div",{className:Q("flex items-end gap-1.5",{"animate-pulse":r}),children:[l.jsx("p",{style:{color:qj(m,c)},className:"text-3xl font-semibold",children:x(m)}),b&&l.jsxs("div",{className:"flex items-end gap-1",children:[l.jsx(bre,{isLowerIsBetter:(T=(k=e.preferences)==null?void 0:k.kpiVisualOptions)==null?void 0:T.lowerIsBetter,className:"",children:b}),p&&l.jsx("div",{className:"ml-0.5 mr-1 min-w-fit text-sm font-normal text-muted-foreground",children:`from ${x(p)}`})]})]})}):l.jsx("div",{className:"flex h-9 items-center justify-center"}),l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsxs(ja,{className:"flex items-center gap-2 text-base font-medium text-muted-foreground",children:[e.title,((E=e.info)==null?void 0:E.trim())&&l.jsx(YO,{card:e})]}),t==null?void 0:t()]})]})})}function dWe({cardId:e}){const t=h7(e||""),n=Vt(c=>c.removeClickFiltersByValue),r=t.map((c,u)=>{const d=c.filterGroups.flatMap(f=>f.filters.map(h=>({field:h.field.label||h.field.name,value:h.value})));return{id:`click-filter-${c.sourceCardId}-${u}`,sourceCardId:c.sourceCardId,name:`Click Filter from ${c.sourceCardId}`,values:d,applyToCardIds:c.applyToCardIds,excludeCardIds:c.excludeCardIds,originalEvent:c}}),s=r.reduce((c,u)=>(u.values.forEach(d=>{var h,m;const f=c.find(p=>p.fieldName===d.field);f?f.filters.some(g=>g.values.some(b=>b.field===d.field&&b.value===d.value))||f.filters.push(u):c.push({fieldName:d.field,fieldLabel:d.field,filters:[u],targetingInfo:(h=u.applyToCardIds)!=null&&h.length?`Applied to: ${u.applyToCardIds.join(", ")}`:(m=u.excludeCardIds)!=null&&m.length?`Excluded from: ${u.excludeCardIds.join(", ")}`:"Applied to all cards"})}),c),[]);function o(c,u){const d=r.filter(f=>f.values.some(h=>h.field===c&&h.value===u));if(d.length>0){const h=d.sort((m,p)=>{const g=t.findIndex(x=>Pi(x,m.originalEvent));return t.findIndex(x=>Pi(x,p.originalEvent))-g})[0];n(h.sourceCardId,c,u)}}function i(c){const u=r.flatMap(f=>f.values.filter(h=>h.field===c)).map(f=>f.value);[...new Set(u)].forEach(f=>{o(c,f)})}function a(c){const u=c.filters.flatMap(h=>h.values.filter(m=>m.field===c.fieldName)).map(h=>h.value),d=[...new Set(u)],f=d.filter(h=>{const g=c.filters.filter(y=>y.values.some(v=>v.field===c.fieldName&&v.value===h)).sort((y,v)=>{const C=t.findIndex(N=>Pi(N,y.originalEvent));return t.findIndex(N=>Pi(N,v.originalEvent))-C})[0];return t.findIndex(y=>Pi(y,g.originalEvent))===t.length-1});return l.jsxs("div",{className:"space-y-3 rounded-lg border border-border/50 bg-muted/30 p-3",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"h-2 w-2 flex-shrink-0 rounded-full bg-blue-500"}),l.jsx(ge,{className:"text-sm font-medium text-foreground",children:c.fieldLabel})]}),l.jsxs(re,{variant:"ghost",size:"sm",onClick:()=>i(c.fieldName),className:"h-7 px-2.5 text-xs text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive",children:[l.jsx(La,{className:"mr-1.5 h-3.5 w-3.5"}),"Clear"]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"flex flex-wrap gap-1.5",children:d.map((h,m)=>{const p=f.includes(h);return l.jsxs(Xe,{variant:"secondary",className:`group relative ${p?"cursor-pointer border border-blue-500/20 bg-blue-500/10 text-blue-600 transition-colors hover:bg-blue-500/15":"cursor-not-allowed border border-border/30 bg-muted/50 text-muted-foreground"}`,onClick:()=>{p&&o(c.fieldName,h)},children:[h,l.jsx(Mt,{className:`ml-1.5 h-3 w-3 ${p?"opacity-60 transition-opacity group-hover:opacity-100":"cursor-not-allowed opacity-40"}`})]},m)})}),d.length>1&&l.jsx("div",{className:"text-xs text-muted-foreground",children:'Clear filters in sequence (most recent first) or use "Clear" to remove all'})]})]})}return s.length===0?null:l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Cpe,{className:"h-3.5 w-3.5 text-muted-foreground"}),l.jsx("span",{className:"text-xs font-medium text-foreground",children:"Click Filters"})]}),l.jsx("div",{className:"space-y-3",children:s==null?void 0:s.map(c=>l.jsx("div",{children:a(c)},c.fieldName))})]})}function KM({cardId:e,cardFilters:t,cardFilterCount:n=0,onFiltersClick:r,inlineFilters:s,inlineFilterValues:o,sheetId:i,removeInlineFilterValue:a}){var de,fe,Oe;const[c,u]=w.useState(!1),d=ee(ye=>ye.isDashboardEditing),f=ee(ye=>ye.isVisualEditing),h=ee(ye=>ye.dashboard.defaultFilterValues),m=ee(ye=>ye.themeStyle),p=ee(ye=>ye.filterValues),g=ee(ye=>ye.dashboard.filters),b=ee(ye=>ye.filteringCards),x=ee(ye=>ye.selectedSheetId),y=ee(ye=>ye.onSaveFunction),{removeFilterValues:v,removeFilteringCard:C,setFilterValues:S,setFilteringCards:N,setDefaultFilterValues:j,getDashboard:k}=en(),{tokenProps:T}=rt(),_=((fe=(de=T==null?void 0:T.params)==null?void 0:de.calendarContext)==null?void 0:fe.tz)||((Oe=T==null?void 0:T.params)==null?void 0:Oe.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone,{updateFilters:M,clearFilters:P}=lr(),{updateCardFilters:D,clearCardFilters:A}=en(),L=ee(ye=>ye.actions.removeCardInlineFilterValue),$=Vt(ye=>ye.clearAllClickFilters),B=e?zR(g,p,x,e).cardFilterValues:(()=>{const ye=Yl(g,x);return p==null?void 0:p.filter(Ce=>(ye==null?void 0:ye.some($e=>$e.id===Ce.filterId))||Ce.filterId.endsWith(x))})(),V=(B==null?void 0:B.map(ye=>{const Ce=g==null?void 0:g.find($e=>$e.id===ye.filterId);return{filterId:ye.filterId,fieldName:(Ce==null?void 0:Ce.title)||ye.name,fieldLabel:(Ce==null?void 0:Ce.title)||ye.name,values:ye.values,dataType:Ce==null?void 0:Ce.dataType,operation:Ce==null?void 0:Ce.operation,isDateFilter:Ca((Ce==null?void 0:Ce.dataType)||"")}}))||[],R=h7(e||""),U=(o==null?void 0:o.length)||0;if(!f&&V.length===0&&R.length===0&&n===0&&U===0)return null;const O=V.length+R.length+n+U,I={dashboard:V.length,card:n,inline:U,click:R.length},W=[I.dashboard>0?"dashboard":null,I.card>0?"card":null,I.inline>0?"inline":null,I.click>0?"click":null].filter(ye=>ye!==null),X=W.length===0?"none":W.length===1?W[0]:"mixed",Z={dashboard:"Dashboard",card:"Card",inline:"Inline",click:"Click",mixed:"Mixed"},H={none:"border-border/70 bg-muted/30 text-muted-foreground hover:bg-muted/50",dashboard:"border-purple-200/70 bg-purple-50/60 text-purple-700 hover:bg-purple-100/70 dark:border-purple-800/50 dark:bg-purple-950/40 dark:text-purple-300 dark:hover:bg-purple-900/50",card:"border-blue-200/70 bg-blue-50/60 text-blue-700 hover:bg-blue-100/70 dark:border-blue-800/50 dark:bg-blue-950/40 dark:text-blue-300 dark:hover:bg-blue-900/50",inline:"border-green-200/70 bg-green-50/60 text-green-700 hover:bg-green-100/70 dark:border-green-800/50 dark:bg-green-950/40 dark:text-green-300 dark:hover:bg-green-900/50",click:"border-amber-200/70 bg-amber-50/60 text-amber-700 hover:bg-amber-100/70 dark:border-amber-800/50 dark:bg-amber-950/40 dark:text-amber-300 dark:hover:bg-amber-900/50",mixed:"border-indigo-200/70 bg-indigo-50/60 text-indigo-700 hover:bg-indigo-100/70 dark:border-indigo-800/50 dark:bg-indigo-950/40 dark:text-indigo-300 dark:hover:bg-indigo-900/50"},K=X==="none"?0:X==="mixed"?O:I[X],z=f,q=z?H[X]:"border-border/70 bg-muted/30 text-muted-foreground hover:bg-muted/50",Y=z&&X!=="none"?Z[X]:null,G=z?K:O;function J(ye){return ye instanceof Date?ot.formatInTimeZone(ye,_,"MM/dd/yyyy"):ye}function ne(ye){const Ce=b==null?void 0:b.find($e=>ye.filterId.startsWith($e.id));Ce&&C(Ce),v(ye.filterId)}function be(ye){V.filter($e=>$e.fieldName===ye).forEach($e=>{ne($e)})}function te(ye){if(e){if(a){a(ye);return}L(e,ye)}}function ce(){!e||!(o!=null&&o.length)||o.forEach(ye=>{a?a(ye.filterId):L(e,ye.filterId)})}function se(){N([]),S([]),$(),e&&f&&P(e),ce()}function ue(ye){function Ce(){return ye.values.map((ze,Ge)=>l.jsx(Xe,{variant:"outline",className:"cursor-pointer select-none border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm transition-all hover:shadow-md hover:from-purple-100/60 hover:to-purple-100/50 dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",onClick:()=>ne(ye),children:l.jsxs("span",{className:"flex items-center gap-1.5",children:[l.jsx("span",{className:"font-medium",children:J(ze)}),l.jsx(Mt,{className:"h-3 w-3"})]})},(ze==null?void 0:ze.toString())+Ge))}function $e(){const ze=ye.values[0],Ge=ye.values[1];if(!ze||!Ge)return null;const Ke=new Date(ze),Ze=new Date(Ge),st=ot.formatInTimeZone(Ke,_,"MM/dd/yyyy"),ae=ot.formatInTimeZone(Ze,_,"MM/dd/yyyy");return l.jsx(Xe,{variant:"outline",className:"cursor-pointer select-none border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm transition-all hover:shadow-md hover:from-purple-100/60 hover:to-purple-100/50 dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",onClick:()=>ne(ye),children:l.jsxs("span",{className:"flex items-center gap-1.5",children:[l.jsx("span",{className:"font-medium",children:`${st} - ${ae}`}),l.jsx(Mt,{className:"h-3 w-3"})]})})}return l.jsxs("div",{className:"group space-y-1.5 rounded-lg border border-border/50 bg-muted/30 p-2 transition-colors hover:bg-muted/50",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:ye.fieldLabel}),!ye.isDateFilter&&ye.operation==="not in"&&l.jsx("span",{className:"text-xs text-muted-foreground/70",children:rC(ye.operation)})]}),l.jsx(re,{variant:"ghost",size:"sm",onClick:()=>be(ye.fieldName),className:"h-4 w-4 p-0 text-muted-foreground/70 opacity-0 transition-all hover:bg-muted/60 hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100","aria-label":"Clear filter",children:l.jsx(Mt,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex flex-wrap gap-1.5",children:ye.isDateFilter?$e():Ce()})]})}function Re(ye){return{"=":"equals","!=":"not equals",">":"greater than",">=":"greater than or equals","<":"less than","<=":"less than or equals",contains:"contains",startsWith:"starts with",endsWith:"ends with",in:"in","not in":"not in",between:"between",isNull:"is null",isNotNull:"is not null","not between":"not between"}[ye]||ye}function je(ye){const Ce=$e=>$e instanceof Date?ot.formatInTimeZone($e,_,"MM/dd/yyyy"):String($e);if(Array.isArray(ye.value)){if(ye.operator==="between"){const $e=Ce(ye.value[0]),ze=Ce(ye.value[1]);return`${$e} and ${ze}`}return ye.value.map(Ce).join(", ")}return ye.value instanceof Date?ot.formatInTimeZone(ye.value,_,"MM/dd/yyyy"):String(ye.value||"")}function ke(ye){if(!t||!e)return;const Ce=ze=>({...ze,conditions:ze.conditions.filter(Ge=>Ge.id!==ye),groups:ze.groups.map(Ce)}),$e=Ce(t);f?M(e,$e):D(e,$e)}function me(){e&&(f?P(e):A(e),ce())}function Me(ye){const Ce=[...ye.conditions];return ye.groups.forEach($e=>{Ce.push(...Me($e))}),Ce}function Se(){if(!t)return null;const ye=Me(t);return ye.length===0?null:l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Card Filters"}),f&&l.jsxs(re,{variant:"ghost",size:"sm",onClick:me,className:"h-6 px-2 text-xs text-muted-foreground/70 transition-colors hover:bg-muted/60 hover:text-foreground",children:[l.jsx(Mt,{className:"mr-1 h-3 w-3"}),"Clear All"]})]}),l.jsx("div",{className:"space-y-1.5",children:ye.map(Ce=>l.jsxs("div",{className:"group space-y-1.5 rounded-lg border border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 p-2 transition-colors hover:from-blue-100/60 hover:to-blue-100/50 dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:Ce.field.label||Ce.field.name}),l.jsx("span",{className:"text-xs text-muted-foreground/70",children:Re(Ce.operator)})]}),f&&l.jsx(re,{variant:"ghost",size:"sm",onClick:()=>ke(Ce.id),className:"h-4 w-4 p-0 text-muted-foreground/70 opacity-0 transition-all hover:bg-muted/60 hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100","aria-label":"Clear filter",children:l.jsx(Mt,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.jsx(Xe,{variant:"outline",className:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100",children:l.jsx("span",{className:"font-medium",children:je(Ce)})})})]},Ce.id))})]})}function ie(){return!o||o.length===0?null:l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Inline Filters"}),l.jsx("div",{className:"space-y-1.5",children:o.map(ye=>{const Ce=s==null?void 0:s.find(ze=>ze.id===ye.filterId);if(!Ce)return null;const $e=Ca(Ce.dataType);return l.jsxs("div",{className:"group space-y-1.5 rounded-lg border border-green-200/70 bg-gradient-to-r from-green-50/50 to-green-100/30 p-2 transition-colors hover:from-green-100/60 hover:to-green-100/50 dark:border-green-800/50 dark:from-green-950/40 dark:to-green-900/30",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:Ce.title}),!$e&&ye.operation==="not in"&&l.jsx("span",{className:"text-xs text-muted-foreground/70",children:rC(ye.operation)})]}),l.jsx(re,{variant:"ghost",size:"sm",onClick:()=>{te(ye.filterId)},className:"h-4 w-4 p-0 text-muted-foreground/70 opacity-0 transition-all hover:bg-muted/60 hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100","aria-label":"Clear filter",children:l.jsx(Mt,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex flex-wrap gap-1.5",children:$e?(()=>{const ze=ye.values;if(!ze[0]||!ze[1])return null;const Ge=new Date(ze[0]),Ke=new Date(ze[1]),Ze=ot.formatInTimeZone(Ge,_,"MM/dd/yyyy"),st=ot.formatInTimeZone(Ke,_,"MM/dd/yyyy");return l.jsx(Xe,{variant:"outline",className:"border-green-200/70 bg-gradient-to-r from-green-50/50 to-green-100/30 text-green-900 shadow-sm dark:border-green-800/50 dark:from-green-950/40 dark:to-green-900/30 dark:text-green-100",children:l.jsx("span",{className:"font-medium",children:`${Ze} - ${st}`})})})():ye.values.map((ze,Ge)=>l.jsx(Xe,{variant:"outline",className:"border-green-200/70 bg-gradient-to-r from-green-50/50 to-green-100/30 text-green-900 shadow-sm dark:border-green-800/50 dark:from-green-950/40 dark:to-green-900/30 dark:text-green-100",children:l.jsx("span",{className:"font-medium",children:J(ze)})},String(ze)+Ge))})]},ye.filterId)})})]})}function pe(ye){const Ce=k();Ce&&(y==null||y(Ce,ye))}function Ne(){return l.jsxs(l.Fragment,{children:[l.jsx(Vs,{className:"my-4"}),l.jsxs("div",{className:"space-y-3",children:[l.jsx("p",{className:"text-xs text-muted-foreground",children:"Start with these filters? Set them as default."}),l.jsxs("div",{className:"flex flex-row-reverse gap-2",children:[l.jsxs(re,{onClick:()=>{j(p||[]),pe("Default filters saved successfully")},style:{borderRadius:m==null?void 0:m.controlInputRadius},className:"h-8 text-xs font-medium",variant:"outline",children:[h&&(h==null?void 0:h.length)>0&&l.jsx(qr,{className:"mr-1.5 h-3.5 w-3.5 text-green-500"}),"Set Default"]}),l.jsx(re,{onClick:()=>{j(void 0),pe("Default filters cleared")},style:{borderRadius:m==null?void 0:m.controlInputRadius},className:"h-8 text-xs font-medium",variant:"secondary",children:"Reset"})]})]})]})}return l.jsxs(Yc,{open:c,onOpenChange:u,openDelay:50,children:[l.jsx(Gc,{asChild:!0,children:l.jsxs(Xe,{variant:"outline",className:Q("h-6 cursor-pointer select-none gap-1.5 transition-all",q),onClick:ye=>{ye.stopPropagation(),u(!1),r==null||r()},children:[l.jsx(Ic,{className:"h-3 w-3"}),Y&&l.jsx("span",{className:"text-[10px] font-medium",children:Y}),G>0&&l.jsx("span",{className:"text-xs font-medium",children:G})]})}),l.jsx(Ia,{onMouseDown:ye=>ye.stopPropagation(),style:{borderRadius:m==null?void 0:m.cardBorderRadius},className:"w-[380px] border border-border/50 p-0 text-xs shadow-lg",align:"start",children:O===0?l.jsxs("div",{className:"p-6 text-center",children:[l.jsx(Ic,{className:"mx-auto mb-3 h-8 w-8 text-muted-foreground/50"}),l.jsx("p",{className:"text-sm font-medium text-foreground",children:"No filters applied"}),l.jsx("p",{className:"mb-4 mt-1 text-xs text-muted-foreground",children:"Add filters to narrow down your data"}),l.jsxs(re,{variant:"outline",size:"sm",onClick:ye=>{ye.stopPropagation(),u(!1),r==null||r()},className:"mx-auto",children:[l.jsx(Ic,{className:"mr-2 h-3.5 w-3.5"}),"Add Filters"]})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"border-b border-border/50 bg-muted/30 px-3 py-2",children:l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-sm font-medium text-foreground",children:"Active Filters"}),l.jsx(Xe,{variant:"secondary",className:"h-5 px-1.5 text-[10px] font-medium",children:O})]}),l.jsxs(re,{variant:"ghost",size:"sm",onClick:se,className:"h-6 px-2 text-xs text-muted-foreground/70 transition-colors hover:bg-muted/60 hover:text-foreground",children:[l.jsx(Mt,{className:"mr-1 h-3 w-3"}),"Clear All"]})]})}),l.jsxs("div",{className:"space-y-2.5 p-3",children:[l.jsxs("div",{className:"max-h-[280px] space-y-2.5 overflow-y-auto",children:[V.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Dashboard Filters"}),l.jsx("div",{className:"space-y-1.5",children:V==null?void 0:V.map(ye=>l.jsx("div",{children:ue(ye)},ye.filterId))})]}),l.jsx(dWe,{cardId:e}),Se(),ie()]}),d&&!f&&Ne()]})]})})]})}function Wre({columns:e=5,rows:t=10}){const n=ee(r=>r.themeStyle);return l.jsxs(za,{style:{borderRadius:n==null?void 0:n.cardBorderRadius},className:"relative h-full w-full rounded-none border border-border/60 bg-background/95",children:[l.jsxs("table",{className:"w-full text-sm [border-spacing:0]",children:[l.jsx(Mg,{className:"sticky top-0 z-10 border-b border-border/60 bg-muted",children:l.jsx(Pr,{children:Array.from({length:e}).map((r,s)=>l.jsx(Go,{className:"h-10 border-r border-border/20 text-foreground/80 last:border-r-0",children:l.jsx(rs,{className:"h-4 w-full"})},s))})}),l.jsx(fh,{children:Array.from({length:t}).map((r,s)=>l.jsx(Pr,{className:Q("border-border/35 transition-colors duration-150",s%2===1&&"bg-muted/[0.14]"),children:Array.from({length:e}).map((o,i)=>l.jsx(Un,{className:"overflow-hidden border-r border-border/20 py-2.5 text-foreground/90 last:border-r-0",children:l.jsx(rs,{className:"h-4 w-full"})},i))},s))})]}),l.jsx(Da,{orientation:"horizontal"})]})}const wS=e=>{if(!e)return 0;let t=e.conditions.length;return e.groups.forEach(n=>{t+=wS(n)}),t};function ZM(e,t){const{function:n,rowLevel:r,columnLevel:s}=e,o={...t};if(r!==void 0){const i=o.rowAggregates||[],a=r==="all"?"ALL":r,c=i.findIndex(u=>u.groupLevel===a&&u.function===n);c>=0?o.rowAggregates=i.filter((u,d)=>d!==c):o.rowAggregates=[...i,{function:n,groupLevel:a}]}if(s!==void 0){const i=o.columnAggregates||[],a=s==="all"?"ALL":s,c=i.findIndex(u=>u.pivotLevel===a&&u.function===n);c>=0?o.columnAggregates=i.filter((u,d)=>d!==c):o.columnAggregates=[...i,{function:n,pivotLevel:a}]}return o}function qre(e,t){const n={...t};return e.type==="row"&&n.rowAggregates?n.rowAggregates=n.rowAggregates.map(r=>r.function===e.function&&r.groupLevel===e.level?{...r,label:e.label}:r):e.type==="column"&&n.columnAggregates&&(n.columnAggregates=n.columnAggregates.map(r=>r.function===e.function&&r.pivotLevel===e.level?{...r,label:e.label}:r)),n}function Q8({frame:e}){var f,h;const[t,n]=w.useState(!1),r=e==null?void 0:e.cards[0],{data:s,isPending:o,isError:i}=kl(r),a=e==null?void 0:e.cards[1],{data:c,isLoading:u,isFetching:d}=kl(a);return(a==null?void 0:a.type)!=="text"?l.jsx(ph,{card:r,data:(s==null?void 0:s.records)||[],isPending:o,isError:i,comparisonMetadata:(f=s==null?void 0:s.metadata)==null?void 0:f.comparisonMetadata}):l.jsxs(Fo,{className:Q("group relative overflow-y-auto",t?"m-4":"mx-0"),children:[t?l.jsx("div",{className:"overflow-y-auto break-words p-1",children:l.jsx($p,{card:a,data:(c==null?void 0:c.records)||[],isLoading:!1})}):l.jsx(ph,{card:r,data:(s==null?void 0:s.records)||[],isPending:o,isError:i,comparisonMetadata:(h=s==null?void 0:s.metadata)==null?void 0:h.comparisonMetadata}),l.jsx("div",{className:Q("fixed z-10",{"invisible bottom-4 right-4 group-hover:visible":t,"right-6 top-6":!t}),children:l.jsx(uv,{disabled:u||d,className:Q("h-7 p-1"),pressed:t,onPressedChange:n,"aria-label":"Toggle bold",children:t?l.jsx(xpe,{className:"size-4 text-muted-foreground/70"}):l.jsx(ype,{className:"size-4 text-muted-foreground/70"})})})]})}function CS(e){return{clickFilter:Ic,drillToDetail:XA,drillThrough:pp,drillToURL:pN,drillDown:Spe,drillUp:Npe,dynamicDrill:Ws,inlineDrill:bN}[e]||Ic}function Uh(e){return{clickFilter:"Filter Dashboard",drillToDetail:"Show Details",drillThrough:"Navigate to Dashboard",drillToURL:"Open External Link",drillDown:"Drill Down",drillUp:"Drill Up",dynamicDrill:"Explore Field",inlineDrill:"Drill"}[e]||"Interaction"}function fWe(e,t,n,r,s){const o=CS(e.mode),i=e.label||Uh(e.mode),a=hWe(e,t,n,r,s);return{label:i,icon:o,targetInfo:a,interaction:e}}function hWe(e,t,n=0,r,s){var o,i,a,c,u,d;switch(e.mode){case"clickFilter":{if((o=e.applyToCardIds)!=null&&o.length){const f=e.applyToCardIds.length;return`Apply to ${f} ${f===1?"card":"cards"}`}return(i=e.excludeCardIds)!=null&&i.length?"Apply to all cards":"Apply to other cards"}case"drillToDetail":{if(e.targetInsightId)return"Drill into Insight";const f=((a=e.detailFields)==null?void 0:a.length)||0;return f>0?`Show ${f} detail ${f===1?"field":"fields"}`:"Show detail table"}case"drillThrough":return e.targetDashboardId,"Navigate to dashboard";case"drillToURL":{if(e.urlTemplate)try{return`Open ${new URL(e.urlTemplate).hostname}`}catch{return"Open external link"}return"Open external link"}case"drillDown":{if(e.hierarchyId&&t){const f=t.find(h=>h.id===e.hierarchyId);if(f&&f.steps.length>0){let h;if((f.type==="date"||f.baseField)&&r&&f.baseField){const m=GD(f,r,s),p=YD(f,m);h=p==null?void 0:p.field}else h=(c=f.steps[n])==null?void 0:c.field;return h?h.label:n>=f.steps.length?"End of path":f.label||"Drill by hierarchy"}}return"Drill to next level"}case"drillUp":{if(n>0&&e.hierarchyId&&t){const f=t.find(h=>h.id===e.hierarchyId);if(f&&f.steps.length>0){const h=(u=f.steps[n-2])==null?void 0:u.field;return h?`Back to ${h.label}`:`Back to All: ${f.label||"Data"}`}}return"Go back one level"}case"dynamicDrill":{if(e.drillField)return`Drill into ${e.drillField.label} data`;if((d=e.availableFields)!=null&&d.length){const f=e.availableFields.length;return`Choose from ${f} ${f===1?"dimension":"dimensions"}`}return"Explore dimension"}case"inlineDrill":{const f=e.inlineLimit||100,h=e.displayMode||"table";return`Show ${f} records as ${h}`}default:return""}}function mWe(e,t,n,r,s){return e.map(o=>fWe(o,t,n,r,s))}const J8=[];function pWe({open:e,onOpenChange:t,position:n,interactions:r,selectedConditions:s,onSelectInteraction:o,drillHierarchies:i,cardId:a,card:c}){const{currentDepth:u,breadcrumbs:d}=Vt(Kp(C=>{var S,N,j;return{currentDepth:a?((N=(S=C.interactionStates[a])==null?void 0:S.breadcrumbs)==null?void 0:N.length)??0:0,breadcrumbs:a?((j=C.interactionStates[a])==null?void 0:j.breadcrumbs)??J8:J8}})),f=F.useMemo(()=>mWe(r,i,u,c,d),[r,i,u,c,d]),h=F.useMemo(()=>{if(s.length===0)return"";const C=s[0];if(C.label){const S=C.label.split(/[=><]/);if(S.length>1)return S[1].trim()}return String(C.value)},[s]);if(F.useEffect(()=>{if(!e)return;const C=S=>{S.key==="Escape"&&t(!1)};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[e,t]),!e||!n)return null;const m=280,p=80+f.length*60,g=window.innerWidth,b=window.innerHeight;let x=n.x,y=n.y+8;x+m>g&&(x=Math.max(8,g-m-8)),y+p>b&&(y=Math.max(8,n.y-p-8));const v=l.jsxs("div",{className:"semaphor-scope",style:{position:"fixed",inset:0,pointerEvents:"none",background:"transparent"},children:[l.jsx("div",{className:"fixed inset-0",style:{zIndex:50,pointerEvents:"auto",background:"transparent"},onClick:()=>t(!1),"aria-hidden":"true"}),l.jsxs("div",{className:Q("fixed rounded-lg border bg-popover shadow-lg","animate-in fade-in-0 zoom-in-95"),style:{left:`${x}px`,top:`${y}px`,zIndex:51,width:`${m}px`,maxHeight:"400px",pointerEvents:"auto"},role:"menu","aria-label":"Select interaction",children:[h&&l.jsxs("div",{className:"border-b px-4 py-3",children:[l.jsx("p",{className:"text-xs text-muted-foreground",children:"Selected"}),l.jsx("p",{className:"text-sm font-medium",children:h})]}),l.jsx("div",{className:"max-h-80 overflow-y-auto py-1",children:f.map((C,S)=>{var k;const N=C.icon,j=C.interaction.mode==="dynamicDrill"&&(S===0||((k=f[S-1])==null?void 0:k.interaction.mode)!=="dynamicDrill");return l.jsxs(F.Fragment,{children:[j&&l.jsx("div",{className:"border-t px-4 py-2",children:l.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"⚡ Explore Other Fields"})}),l.jsxs("button",{className:Q("flex w-full items-start gap-3 px-4 py-3","hover:bg-accent hover:text-accent-foreground","cursor-pointer transition-colors","border-b text-left last:border-b-0"),onClick:()=>{o(C.interaction),t(!1)},role:"menuitem",children:[l.jsx("div",{className:"mt-0.5 flex-shrink-0",children:l.jsx(N,{className:"h-4 w-4 text-muted-foreground"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("p",{className:"mb-1 text-sm font-medium leading-none",children:C.label}),C.targetInfo&&l.jsx("p",{className:"text-xs text-muted-foreground",children:C.targetInfo})]})]})]},S)})})]})]});return mr.createPortal(v,document.body)}function gWe(e){const t=w.useRef([]),n=w.useRef(null),r=w.useRef(null),o=gc(e.interactionConfig).some(h=>h.mode==="clickFilter"&&h.trigger!==void 0),i=ku(h=>h.registerClearBlurCallback),a=ku(h=>h.unregisterCard);w.useEffect(()=>{const h=()=>{r.current&&f(r.current)};return i(e.id,h),()=>{a(e.id)}},[e.id,i,a]);function c({chart:h,selectedSegments:m,storedOriginalColorsRef:p}){if(!h||!h.canvas||!h.canvas.ownerDocument){console.warn("Chart or canvas is null when trying to toggle blur segments");return}const g=h.data.datasets;p.current||(p.current=g.map((x,y)=>h.getDatasetMeta(y).data.map(C=>C.options.backgroundColor)));const b=p.current;g.forEach((x,y)=>{const v=b[y];if(m.length===0){x.backgroundColor=[...v];return}x.backgroundColor=v.map((C,S)=>m.some(j=>j.datasetIndex===y&&j.dataIndex===S)?C:u(C,.2))});try{h.update()}catch(x){console.warn("Failed to update chart during blur toggle:",x)}}function u(h,m=.2){if(h.startsWith("rgba"))return h.replace(/[\d.]+\)$/g,`${m})`);if(h.startsWith("#")){const p=parseInt(h.slice(1,3),16),g=parseInt(h.slice(3,5),16),b=parseInt(h.slice(5,7),16);return`rgba(${p}, ${g}, ${b}, ${m})`}return h}function d(h,m){var v;if(!o||!m)return;r.current=m;const p=m.getElementsAtEventForMode(h,"nearest",{intersect:!0},!0);if(!p.length)return;const{datasetIndex:g,index:b}=p[0],x={datasetIndex:g,dataIndex:b};if(((v=h.native)==null?void 0:v.shiftKey)||h.shiftKey){const C=t.current.findIndex(S=>S.datasetIndex===g&&S.dataIndex===b);C>=0?t.current.splice(C,1):t.current.push(x)}else{const C=t.current.length===1&&t.current[0].datasetIndex===g&&t.current[0].dataIndex===b;t.current=C?[]:[x]}c({chart:m,selectedSegments:t.current,storedOriginalColorsRef:n})}function f(h){h&&(t.current=[],n.current&&c({chart:h,selectedSegments:[],storedOriginalColorsRef:n}))}return{handleChartClick:d,clearBlur:f}}function Kw(e,t,n){var s;if(!e||!(t!=null&&t.id)||!n)return;const r=(s=n.byFieldId)==null?void 0:s[t.id];if(r){if(r.outputKey&&Object.prototype.hasOwnProperty.call(e,r.outputKey))return e[r.outputKey];if(r.rawKey&&Object.prototype.hasOwnProperty.call(e,r.rawKey))return e[r.rawKey]}}function bWe({resolvedCardConfig:e,card:t,records:n,chart:r,clickEvent:s,columnKeyMap:o}){var d,f,h,m,p,g,b,x,y,v;const i=r==null?void 0:r.getElementsAtEventForMode(s,"nearest",{intersect:!0},!0);if(!i.length)return;const a=i[0].datasetIndex,c=i[0].index,u=(f=(d=i[0].element)==null?void 0:d.$context)==null?void 0:f.raw;console.log("datasetIndex",a),console.log("clickIndex",c),console.log("value",u);try{if(!(n!=null&&n.length))return;const{keys:C}=Qn(n),{groupByColumns:S=[],pivotByColumns:N=[],metricColumns:j=[]}=e||t.config,k=T=>S.find(E=>E.label===T)||N.find(E=>E.label===T)||j.find(E=>E.label===T);if(t.type==="map"){const T=C[0],E=((m=(h=u==null?void 0:u.feature)==null?void 0:h.properties)==null?void 0:m.name)||((g=(p=u==null?void 0:u.feature)==null?void 0:p.properties)==null?void 0:g.NAME),_=S[0]||k(T);return!_||E==null?void 0:{conditions:[{field:_,operator:"=",value:E}]}}if(["pie","funnel","doughnut"].includes(t.type)){const T=C[0],E=C==null?void 0:C[1+a],_=S[0]||k(T),M=j[a]||j[0]||k(E),P=Kw(n==null?void 0:n[c],_,o)??((b=n==null?void 0:n[c])==null?void 0:b[T]),D=Kw(n==null?void 0:n[c],M,o)??u;if(!_||P==null){console.log("no dim field or value",T,P);return}return{conditions:[{field:_,operator:"=",value:P}],metrics:M?[{field:M,value:D}]:void 0}}if(["stackedBar","bar","line"].includes(t.type)){const T=C[0],E=S[0]||k(T),_=Kw(n==null?void 0:n[c],E,o)??((x=n==null?void 0:n[c])==null?void 0:x[T]);if(!E||_==null){console.log("no dim field or value for stacked bar",T,_);return}const M=j[a]||j[0];if(!M){console.log("no metric field found");return}const P=N[0],A=Object.keys(n[0]).filter(R=>R!==T)[a],B=Kw(n==null?void 0:n[c],M,o)??(A?(y=n==null?void 0:n[c])==null?void 0:y[A]:(v=n==null?void 0:n[c])==null?void 0:v[M.label])??u,V=[{field:E,operator:"=",value:_}];return P&&A&&V.push({field:P,operator:"=",value:A}),{conditions:V,metrics:[{field:M,value:B}]}}}catch(C){console.error("getClickContextFromChart error",C)}}function xWe(e){return e&&typeof e=="object"&&"field"in e&&"operator"in e}function yWe(e){return e&&typeof e=="object"&&"filterId"in e&&"operation"in e&&"values"in e}function Yre({filters:e,filterDefinitions:t,contextMode:n,className:r,showLabel:s=!0,labelText:o="Applied Filters:",icon:i}){if(!e||e.length===0)return n==="none"?l.jsx("div",{className:"px-6 pb-4",children:l.jsx("span",{className:"text-xs text-muted-foreground",children:"No filters applied"})}):null;const c=e.map(u=>{var d,f;if(xWe(u))return{fieldName:((d=u.field)==null?void 0:d.label)||((f=u.field)==null?void 0:f.name)||"Unknown",operator:u.operator,value:wWe(u)};if(yWe(u)){const h=t==null?void 0:t.find(m=>m.id===u.filterId);return{fieldName:(h==null?void 0:h.title)||u.name,operator:u.operation,value:vWe(u)}}else return{fieldName:"Unknown",operator:"=",value:String(u)}}).reduce((u,d)=>(u[d.fieldName]||(u[d.fieldName]=[]),u[d.fieldName].push(d),u),{});return l.jsxs("div",{className:r||"border-b px-6 pb-4",children:[l.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s&&i&&l.jsxs("div",{className:"flex items-center gap-2 text-foreground/80",children:[i,l.jsx("span",{className:"whitespace-nowrap text-sm font-medium",children:o})]}),s&&!i&&l.jsx("span",{className:"whitespace-nowrap text-sm text-muted-foreground",children:o}),l.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(c).map(([u,d])=>l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsxs("span",{className:"text-sm font-medium",children:[u,":"]}),d.map((f,h)=>l.jsx(Xe,{variant:"outline",className:"cursor-pointer select-none border-primary/20 bg-gradient-to-r from-primary/5 to-primary/10 text-primary shadow-sm transition-all hover:from-primary/10 hover:to-primary/15 hover:shadow-md dark:border-primary/30 dark:from-primary/10 dark:to-primary/20 dark:text-primary dark:hover:from-primary/15 dark:hover:to-primary/25",children:f.value},`${u}-${h}`))]},u))})]}),n&&l.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:[n==="interactionFilters"&&l.jsx("span",{children:"Showing data filtered by interaction only"}),n==="full"&&l.jsx("span",{children:"Showing data with all dashboard filters + interaction filters"}),n==="none"&&l.jsx("span",{children:"Showing all data (no filters applied)"})]})]})}function vWe(e){const{values:t,operation:n}=e;return!t||t.length===0?"":n==="="||n==="!="||n===">"||n==="<"||n===">="||n==="<="?String(t[0]):n==="in"||n==="not in"?t.map(r=>String(r)).join(", "):(n==="between"||n==="not between")&&t.length===2?`${t[0]} - ${t[1]}`:String(t[0])}function wWe(e){const{operator:t,value:n}=e;if(e.label){const r=e.label.split(/[=><]/);if(r.length>1)return r[1].trim()}switch(t){case"=":return String(n);case"!=":return`≠ ${n}`;case">":return`> ${n}`;case"<":return`< ${n}`;case">=":return`≥ ${n}`;case"<=":return`≤ ${n}`;case"in":return Array.isArray(n)?n.join(", "):String(n);case"not in":return`not ${Array.isArray(n)?n.join(", "):n}`;case"contains":return`contains ${n}`;case"startsWith":return`starts with ${n}`;case"endsWith":return`ends with ${n}`;case"between":return Array.isArray(n)?`between ${n[0]} and ${n[1]}`:String(n);case"not between":return Array.isArray(n)?`not between ${n[0]} and ${n[1]}`:String(n);case"isNull":return"is null";case"isNotNull":return"is not null";default:return String(n)}}function CWe({cardId:e,className:t}){const n=Vt(d=>d.interactionStates[e]),r=Vt(d=>d.popInteractionStep),s=Vt(d=>d.resetInteractionState),o=(n==null?void 0:n.breadcrumbs)??[];if(n==null||n.hierarchyId,o.length===0)return null;const i=d=>{const f=o.length-d-1;for(let h=0;h<f;h++)r(e)},a=()=>{s(e)},c=d=>(d.sourceFilterGroups[0],d.toField?d.toField.label||d.toField.name:"Drill Step"),u=d=>{const f=d.sourceFilterGroups.flatMap(h=>h.filters);return l.jsxs("div",{className:"max-w-xs space-y-2 text-sm",children:[f.length>0&&l.jsx(Yre,{filters:f,className:"pb-2",labelText:"Drill Down Filters:",icon:l.jsx(Ipe,{className:"h-4 w-4 text-foreground/80"})}),d.granularity&&l.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[l.jsx(js,{className:"h-4 w-4 text-foreground/80"}),l.jsxs("span",{className:"text-sm font-medium text-foreground/80",children:["Granularity: ",d.granularity]})]}),d.metric&&l.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[l.jsx(dpe,{className:"h-4 w-4 text-foreground/80"}),l.jsxs("span",{className:"text-sm font-medium text-foreground/80",children:["Value:"," ",d.metric.formattedValue||d.metric.value]})]})]})};return l.jsx(gr,{children:l.jsxs("div",{className:Q("flex items-center gap-1 text-sm",t),children:[l.jsx(wn,{children:l.jsx(Cn,{asChild:!0,children:l.jsx("button",{className:"flex items-center p-0 text-muted-foreground hover:text-foreground",onClick:a,"aria-label":"Reset drill path",children:l.jsx(Kx,{className:"h-3.5 w-3.5"})})})}),l.jsx(ms,{className:"ml-0.5 h-3 w-3 text-muted-foreground"}),l.jsx("div",{className:"flex items-center",children:o.map((d,f)=>l.jsxs("div",{className:"flex items-center",children:[f>0&&l.jsx(ms,{className:"mx-1 h-3 w-3 text-muted-foreground"}),l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(re,{variant:"link",size:"sm",className:"h-6 px-1 text-muted-foreground no-underline hover:text-foreground hover:no-underline",onClick:()=>i(f),"aria-label":`Go back to: ${c(d)}`,children:c(d)})}),l.jsx(Tn,{className:"ml-4",side:"bottom",children:u(d)})]})]},f))})]})})}function Gre(e){var t;if(e&&e.type!=="organization"&&e.type==="tenant")return((t=e.role)==null?void 0:t.toUpperCase())==="VIEWER"?{showFilters:!1}:void 0}function SWe(e){var t;return e?e.type==="organization"?!0:e.type==="tenant"?((t=e.role)==null?void 0:t.toUpperCase())!=="VIEWER":!1:!1}function NWe(e){var t;return e?e.type==="organization"?!0:e.type==="tenant"?((t=e.role)==null?void 0:t.toUpperCase())!=="VIEWER":!1:!1}function jWe(e){return!!e}function EWe(e){var t;return e?e.type==="organization"?!0:e.type==="tenant"?((t=e.role)==null?void 0:t.toUpperCase())!=="VIEWER":!1:!1}function kWe(e){var t;return e?e.type==="organization"?!0:e.type==="tenant"?((t=e.role)==null?void 0:t.toUpperCase())!=="VIEWER":!1:!1}function TWe(e){var t;return e?e.type==="organization"?!0:e.type==="tenant"?((t=e.role)==null?void 0:t.toUpperCase())==="POWER_USER":!1:!1}function _We(e){switch(e){case"print":return{showHeader:!0,showTitle:!0,showDescription:!0,showTabs:!1,showFilters:!1,showBreadcrumbs:!1,showRefreshIndicator:!1,showFilterInfo:!1,showTableToolbar:!1,showColumnSettings:!1};case"table-print":return{showHeader:!1,showTitle:!0,showDescription:!1,showTabs:!1,showFooter:!1,showFilters:!1,showBreadcrumbs:!1,showRefreshIndicator:!1,showFilterInfo:!1,showPagination:!1,showTableToolbar:!1,showColumnSettings:!1};case"full":default:return{showHeader:!0,showTitle:!0,showDescription:!0,showTabs:!0,showFooter:!0,showFilters:!0,showBreadcrumbs:!0,showRefreshIndicator:!0,showFilterInfo:!0}}}function GO({children:e,displayPreferences:t={mode:"full"},currentUser:n}){const r=w.useMemo(()=>{const s=t.mode||"full",o=_We(s),i=Gre(n||null),a={mode:s,overrides:{...o,...i,...t.overrides}};return{displayPreferences:a,shouldShowElement:u=>{var d;return((d=a.overrides)==null?void 0:d[u])??!0}}},[t,n]);return l.jsx($Y.Provider,{value:r,children:e})}function Kre({card:e,sheetId:t,inlineFilterValues:n,setInlineFilterValue:r,removeInlineFilterValue:s}){const o=e.inlineFilters,i=ee(c=>c.inlineFilterValuesMap[e.id]),a=n??i;return!o||o.length===0?null:l.jsx("div",{className:"flex flex-wrap items-start gap-2",children:o.map(c=>l.jsx(Zne,{inlineFilter:c,sheetId:t,cardId:e.id,inlineFilterValues:a,setInlineFilterValue:r,removeInlineFilterValue:s},c.id))})}const IWe={value:Tc.CONTROL_CARD_DEFAULT_VALUE,label:"Current card setup"};function fv(e){return e?u8e({sql:e.sql,controlBindings:e.controlBindings}):[]}function MWe(e){if(!e)return!1;const t=new Set(fv(e));return(e.controls||[]).some(n=>!n.hidden&&t.has(n.id))}function DWe(e){return e.controls||[]}function Ay(e){return e.placement?e.placement:e.scope==="dashboard"?"toolbar":"card_header"}function AWe(e){switch(e.source.kind){case"manual":return e.source.options;case"field_allowlist":return e.source.fieldIds.map(t=>({value:t,label:t}));case"metric_allowlist":return e.source.metricIds.map(t=>({value:t,label:t}));case"dataset_values":return[];default:return[]}}function RWe(e){return e.type==="enum"||e.type==="field_selector"||e.type==="metric_selector"||e.type==="aggregation_selector"||e.type==="grain_selector"}function Zw(e,t){return t==null?"":e.type==="date"&&t instanceof Date?t.toISOString().slice(0,10):String(t)}function XM({control:e,value:t,disabled:n=!1,onChange:r,className:s,showLabel:o=!0,density:i="default"}){var k;const a=o?"":"w-full min-w-0",c=i==="compact",u=c?"h-8":"h-9",d=c?"h-8":"h-9",f=c?"gap-0.5":"gap-1",h=ee(T=>T.themeStyle),m=(h==null?void 0:h.controlInputRadius)??(h==null?void 0:h.cardBorderRadius)??6,p=w.useMemo(()=>AWe(e),[e]),g=w.useMemo(()=>!(t===Tc.CONTROL_CARD_DEFAULT_VALUE||e.defaultValue===Tc.CONTROL_CARD_DEFAULT_VALUE)||p.some(E=>E.value===Tc.CONTROL_CARD_DEFAULT_VALUE)?p:[IWe,...p],[p,e.defaultValue,t]),b=n||e.locked===!0,x=!e.requiredAtExecution&&!b,y=t!=null&&(!Array.isArray(t)||t.length>0),[v,C]=w.useState(()=>Zw(e,t));w.useEffect(()=>{C(Zw(e,t))},[e,t]);const S=e.helpText||e.label;if(RWe(e))return l.jsxs("div",{className:Q(o?`flex min-w-[160px] flex-col ${f}`:`flex flex-col ${f}`,a,s),title:S,children:[o?l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx(ge,{className:"text-xs font-medium text-muted-foreground",children:e.label}),x&&y?l.jsx(re,{type:"button",variant:"ghost",className:"h-auto px-0 py-0 text-xs text-muted-foreground",onClick:()=>r(void 0),children:"Clear"}):null]}):null,l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs(pt,{value:typeof t=="string"?t:void 0,onValueChange:T=>r(T),disabled:b||g.length===0,children:[l.jsx(ft,{className:Q(u,"shadow-sm"),style:{borderRadius:m},children:l.jsx(gt,{placeholder:g.length===0?"No options":"Select"})}),l.jsx(ht,{children:g.map(T=>l.jsx(Ie,{value:T.value,children:T.label},T.value))})]}),!o&&x&&y?l.jsx(re,{type:"button",variant:"ghost",className:Q(d,"shrink-0 px-2 text-xs text-muted-foreground"),onClick:()=>r(void 0),children:"Clear"}):null]})]});if(e.type==="multi_enum"){const T=Array.isArray(t)?t.filter(_=>typeof _=="string"):[],E=T.length===0?"Select":T.length===1?((k=g.find(_=>_.value===T[0]))==null?void 0:k.label)||T[0]:`${T.length} selected`;return l.jsxs("div",{className:Q(o?`flex min-w-[180px] flex-col ${f}`:`flex flex-col ${f}`,a,s),title:S,children:[o?l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx(ge,{className:"text-xs font-medium text-muted-foreground",children:e.label}),x&&y?l.jsx(re,{type:"button",variant:"ghost",className:"h-auto px-0 py-0 text-xs text-muted-foreground",onClick:()=>r(void 0),children:"Clear"}):null]}):null,l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs(Gr,{children:[l.jsx(Kr,{asChild:!0,children:l.jsx(re,{type:"button",variant:"outline",className:Q(u,"w-full justify-between shadow-sm"),style:{borderRadius:m},disabled:b||g.length===0,children:l.jsx("span",{className:"truncate",children:E})})}),l.jsx(Zr,{align:"start",className:"w-64",children:l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("p",{className:"text-sm font-medium",children:e.label}),e.helpText&&l.jsx("p",{className:"text-xs text-muted-foreground",children:e.helpText})]}),l.jsx("div",{className:"space-y-2",children:g.map(_=>{const M=T.includes(_.value);return l.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[l.jsx(Jt,{checked:M,disabled:b||M&&T.length===1&&e.requiredAtExecution,onCheckedChange:P=>{if(P){r([...T,_.value]);return}T.length===1&&e.requiredAtExecution||r((()=>{const D=T.filter(A=>A!==_.value);return D.length===0&&!e.requiredAtExecution?void 0:D})())}}),l.jsx("span",{children:_.label})]},_.value)})})]})})]}),!o&&x&&y?l.jsx(re,{type:"button",variant:"ghost",className:Q(d,"shrink-0 px-2 text-xs text-muted-foreground"),onClick:()=>r(void 0),children:"Clear"}):null]})]})}if(e.type==="boolean")return t===void 0&&e.requiredAtExecution?l.jsxs("div",{className:Q("flex min-w-[180px] items-center justify-between gap-3 rounded-md border bg-background px-3",c?"py-1.5":"py-2",s),style:{borderRadius:m},title:S,children:[o?l.jsxs("div",{className:"min-w-0",children:[l.jsx(ge,{className:"text-xs font-medium text-muted-foreground",children:e.label}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Choose true or false"})]}):l.jsx("div",{className:"min-w-0 text-[11px] text-muted-foreground",children:"Choose true or false"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(re,{type:"button",size:"sm",variant:"outline",style:{borderRadius:m},disabled:b,onClick:()=>r(!0),children:"True"}),l.jsx(re,{type:"button",size:"sm",variant:"outline",style:{borderRadius:m},disabled:b,onClick:()=>r(!1),children:"False"})]})]}):l.jsxs("div",{className:Q(o?"flex min-w-[180px] items-center justify-between gap-3 rounded-md border bg-background px-3":"flex items-center justify-between gap-3 rounded-md border bg-background px-3",c?"py-1.5":"py-2",a,s),style:{borderRadius:m},title:S,children:[o?l.jsxs("div",{className:"min-w-0",children:[l.jsx(ge,{className:"text-xs font-medium text-muted-foreground",children:e.label}),e.helpText&&l.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:e.helpText})]}):null,l.jsxs("div",{className:"flex items-center gap-2",children:[x&&y?l.jsx(re,{type:"button",variant:"ghost",className:"h-auto px-0 py-0 text-xs text-muted-foreground",onClick:()=>r(void 0),children:"Clear"}):null,l.jsx(gh,{checked:!!t,disabled:b,onCheckedChange:T=>r(T)})]})]});const N=e.type==="number"?"number":e.type==="date"?"date":"text",j=()=>{const T=v.trim();if(T.length===0){if(!e.requiredAtExecution){r(void 0),C("");return}C(Zw(e,t));return}if(e.type==="number"){const E=Number(T);if(!Number.isNaN(E)){r(E);return}C(Zw(e,t));return}r(T)};return l.jsxs("div",{className:Q(o?`flex min-w-[160px] flex-col ${f}`:`flex flex-col ${f}`,a,s),title:S,children:[o&&l.jsx(ge,{className:"text-xs font-medium text-muted-foreground",children:e.label}),l.jsx(lt,{type:N,value:v,disabled:b,className:Q(u,"shadow-sm"),style:{borderRadius:m},onChange:T=>C(T.target.value),onBlur:j,onKeyDown:T=>{T.key==="Enter"&&j()}})]})}function Zre({title:e="Controls",controls:t,values:n,onChange:r,immediatePlacement:s,advancedLabel:o="More controls",density:i="default"}){const a=e||"Card controls",c=t.filter(f=>!f.hidden),u=c.filter(f=>Ay(f)===s),d=c.filter(f=>Ay(f)==="advanced");return u.length===0&&d.length===0?null:l.jsxs("div",{className:Q("flex min-w-0 flex-wrap items-start",i==="compact"?"gap-2":"gap-3"),children:[e?l.jsx("div",{className:Q("flex items-center",i==="compact"?"h-8":"h-9"),children:l.jsx(ge,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:e})}):null,u.map(f=>l.jsx(XM,{control:f,value:n==null?void 0:n[f.id],onChange:h=>r(f,h),density:i},f.id)),d.length>0&&l.jsxs(Gr,{children:[l.jsx(Kr,{asChild:!0,children:l.jsxs(re,{type:"button",variant:"outline",className:Q(i==="compact"?"h-8 gap-1.5":"h-9 gap-2"),children:[l.jsx(gl,{className:"h-4 w-4"}),o]})}),l.jsx(Zr,{align:"start",className:"w-80",children:l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("p",{className:"text-sm font-medium",children:a}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls that are available behind one more click."})]}),l.jsx("div",{className:"grid gap-3",children:d.map(f=>l.jsx(XM,{control:f,value:n==null?void 0:n[f.id],onChange:h=>r(f,h),density:i},f.id))})]})})]})]})}function FWe({card:e}){const t=ee(o=>o.cardControlValuesMap[e.id]),{setCardControlValue:n}=en(),r=new Set(fv(e)),s=(e.controls||[]).filter(o=>r.has(o.id));return s.length===0?null:l.jsx(Zre,{title:"",controls:s,values:t,onChange:(o,i)=>n(e.id,o.id,i),immediatePlacement:"card_header",advancedLabel:"More options",density:"compact"})}function QM({card:e,mode:t="dashboard"}){const{authToken:n}=rt(),{data:r,isLoading:s,isRefreshing:o,enabled:i,refresh:a,applyAction:c}=FO(e),[u,d]=w.useState(t==="editor");if(w.useEffect(()=>{d(t==="editor")},[t]),!i)return null;if(s&&!r)return l.jsxs("div",{className:"rounded-md border bg-muted/20 p-3",children:[l.jsx("div",{className:"mb-2 h-3 w-20 animate-pulse rounded bg-muted"}),l.jsx("div",{className:"h-3 w-4/5 animate-pulse rounded bg-muted"})]});if(!r)return null;const f=xS({card:e,accessToken:n==null?void 0:n.accessToken}),h=r.metadata.warnings.length,m=h>0,p=r.metadata.partial||m,g={narrative:r.narrative,generatedAt:r.generatedAt,keyChanges:r.keyChanges,drivers:r.drivers,anomalies:r.anomalies,suggestedActions:r.suggestedActions,metadata:r.metadata};return t==="editor"?l.jsxs("div",{className:"rounded-md border border-border bg-card",children:[l.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[l.jsx("div",{className:"min-w-0 flex-1",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Summary"}),r.metadata.partial&&l.jsx("span",{className:"rounded bg-amber-100 px-1.5 py-0.5 text-[10px] font-medium text-amber-800",children:"Partial"}),m&&l.jsxs("span",{className:"rounded bg-amber-100 px-1.5 py-0.5 text-[10px] font-medium text-amber-800",children:[h," warning",h>1?"s":""]})]})}),l.jsx(re,{size:"icon",variant:"ghost",className:"size-6 shrink-0",onClick:()=>a(),disabled:o,"aria-label":"Refresh summary",children:l.jsx(cC,{className:Q("h-3.5 w-3.5",o&&"animate-spin")})})]}),l.jsx("div",{className:"border-t border-border px-3 py-3",children:l.jsx(Iy,{data:g,applyAction:c,audience:"author",numberFormatter:f})})]}):l.jsxs("div",{className:"rounded-md border border-border bg-card",children:[l.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[l.jsx(re,{size:"icon",variant:"ghost",className:"size-6 shrink-0",onClick:()=>d(b=>!b),"aria-label":u?"Collapse summary":"Expand summary",children:l.jsx(pr,{className:Q("h-4 w-4 transition-transform",!u&&"-rotate-90")})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Summary"}),p&&l.jsx(OO,{className:"text-amber-500"})]}),l.jsx("p",{className:"truncate text-xs text-muted-foreground",children:r.narrative})]}),l.jsx(re,{size:"icon",variant:"ghost",className:"size-6 shrink-0",onClick:()=>a(),disabled:o,"aria-label":"Refresh summary",children:l.jsx(cC,{className:Q("h-3.5 w-3.5",o&&"animate-spin")})})]}),u&&l.jsx("div",{className:"border-t border-border px-3 py-3",children:l.jsx("div",{className:"max-h-56 overflow-y-auto pr-1",children:l.jsx(Iy,{data:g,applyAction:c,audience:"dashboard",numberFormatter:f})})})]})}function Xre({cardId:e}){const t=MF(e);if(t.length===0)return null;const n=t.filter(r=>{var s;return((s=r.alertState)==null?void 0:s.currentState)==="FIRING"}).length;return l.jsxs(wn,{children:[l.jsx(Cn,{asChild:!0,children:l.jsxs(re,{type:"button",variant:"ghost",size:"icon",className:"relative h-6 w-6 text-muted-foreground","aria-label":`${t.length} signal watch${t.length===1?"":"es"}${n>0?`, ${n} currently surfaced`:""}`,children:[l.jsx(Fm,{className:"h-4 w-4"}),n>0?l.jsx("span",{className:"absolute -right-1 -top-1 h-2.5 w-2.5 rounded-full bg-destructive"}):null]})}),l.jsx(Tn,{side:"top",align:"center",children:l.jsxs("p",{className:"text-xs",children:[t.length," signal watch",t.length===1?"":"es"," attached",n>0?`, ${n} surfaced`:""]})})]})}function PWe({canEditDashboard:e,isDashboardEditing:t,isMissingConnection:n,onConfigure:r}){return l.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-4 text-center",children:[l.jsx("div",{className:"rounded-full border border-border bg-muted/40 p-3",children:l.jsx(Ope,{className:"size-6 text-muted-foreground","aria-hidden":!0})}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("h3",{className:"text-sm font-semibold",children:"Set up this visual"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:n?"Choose a data source to begin.":"Add fields or SQL to show data."})]}),e?l.jsx(re,{type:"button",size:"sm",className:"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",onClick:r,children:t?"Configure visual":"Edit visual"}):l.jsx("p",{className:"text-xs text-muted-foreground",children:"You don't have permission to configure this visual."})]})}function OWe(e,t,n){const r=fl(e)==="dynamic",s=r?Wx(e):e,{data:o}=$0(s),i=w.useMemo(()=>(t==null?void 0:t.records)||[],[t==null?void 0:t.records]),a=w.useMemo(()=>{var d;return s.type!=="pivotTable"||!((d=t==null?void 0:t.records)!=null&&d.length)?null:{records:t.records,columnSubtotalMeta:t.columnSubtotalMeta,subtotalColumns:t.subtotalColumns||[],pivotSchema:t.pivotSchema||[],groupByColumns:t.groupByColumns}},[s.type,t==null?void 0:t.records,t==null?void 0:t.columnSubtotalMeta,t==null?void 0:t.subtotalColumns,t==null?void 0:t.pivotSchema,t==null?void 0:t.groupByColumns]),c=Ig(s,a),u=w.useMemo(()=>{var d;if(!(!((d=t==null?void 0:t.records)!=null&&d.length)||["kpi","text","table","detailTable","pivotTable","aggregateTable","custom"].includes(s.type)))return xg({card:s,data:t.records,cardType:s.type,queryConfig:s.queryConfig,customCfg:s.customCfg,preferences:s.preferences,topoJson:o})},[s,o,t==null?void 0:t.records,n]);return{isDynamicVisualizationMode:r,fallbackCard:s,tableRecords:i,pivotTableConfig:c,fallbackCfg:u}}const LWe=[];function e9({card:e,frame:t}){var Nr,Jr,ei,go,Ha,nu,yt,xe,he,Le,ut,It,zt,bn,cr,bo;const{customCards:n,placeholders:r,tokenProps:s}=rt(),{shouldShowElement:o}=Kc(),i=ee(Fe=>Fe.themeStyle),a=ee(Fe=>Fe.dashboard),c=ee(Fe=>Fe.selectedSheetId),u=ee(Fe=>Fe.isDashboardEditing);ee(Fe=>Fe.selectedLensId);const d=ee(Fe=>Fe.dashboard.filters),f=ee(Fe=>Fe.filterValues),h=ee(Fe=>Fe.inlineFilterValuesMap),m=Ve(Fe=>Fe.selectedConnectionId),p=Ve(Fe=>Fe.selectedDatabaseName),g=Ve(Fe=>Fe.selectedSchemaName),b=Ve(Fe=>Fe.selectedTableName),x=Ve(Fe=>Fe.selectedDatamodelId),y=TO(t,e),{manifest:v}=$h(((Nr=y==null?void 0:y.customCardPreferences)==null?void 0:Nr.url)||""),C=(Jr=v==null?void 0:v.visuals)==null?void 0:Jr.find(Fe=>{var Nt;return Fe.name===((Nt=y==null?void 0:y.customCardPreferences)==null?void 0:Nt.componentName)}),S=cv(y,C)==="multiple",N=S&&y?y:e,j=fl(N)==="dynamic",k=j?Wx(N):N,T=Vt(Fe=>Fe.interactionStates[N.id]),E=((ei=T==null?void 0:T.breadcrumbs)==null?void 0:ei.length)>0,_=ee(Fe=>Fe.inlineFilterValuesMap[N.id]),M=d==null?void 0:d.find(Fe=>Fe.id===t.filterId&&!Fe.hide),{clearSelectedVisual:P}=Jp(),D=bs(Fe=>Fe.selectedDashboard),A=bs(Fe=>Fe.initialDashboard),L=D?(Ha=D==null?void 0:D.permissions)==null?void 0:Ha.canEdit:(go=A==null?void 0:A.permissions)==null?void 0:go.canEdit,{setSelectedFrameId:$,updateFilter:B,updateFrame:V,setIsDashboardEditing:R,setIsVisualEditing:U}=en(),{handleChartClick:O}=gWe(N),{setCard:I,setFrame:W,setQueryResultColumns:X,setActiveTabCardId:Z,setIsDevMode:H,initializeModeDrafts:K,updateDataSource:z}=lr(),q=Ve(Fe=>Fe.actions.setSelectedConnectionId),Y=Ve(Fe=>Fe.actions.setSelectedDatamodelId),G=Ve(Fe=>Fe.actions.setSelectedDatabaseName),J=Ve(Fe=>Fe.actions.setSelectedSchemaName),ne=Ve(Fe=>Fe.actions.setSelectedTableName),be=Ve(Fe=>Fe.actions.setFilterValues),te=Ve(Fe=>Fe.actions.setInlineFilterValuesMap),ce=Ve(Fe=>Fe.actions.setApplyFilters),se=o("showHeader")&&(((nu=N.customCardPreferences)==null?void 0:nu.showCardHeader)??!0),ue=w.useMemo(()=>S&&N?{...N,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:N,[N,S]),Re=!(N.connectionId||(yt=N.dataSource)!=null&&yt.connectionId),je=!!(n!=null&&n.find(Fe=>Fe.cardId===e.id&&!!Fe.content)),ke=hhe(N,{skipSetupCheck:S&&!!y||je});function me(){L&&($(t.id),P(),SP({frame:t,card:e,setFrame:W,setCard:I,setIsDevMode:H,initializeModeDrafts:K,setActiveTabCardId:Z,updateDataSource:z,setQueryResultColumns:X,setSelectedConnectionId:q,setSelectedDatabaseName:G,setSelectedSchemaName:J,setSelectedTableName:ne,setSelectedDatamodelId:Y,setFilterValues:be,setInlineFilterValuesMap:te,setApplyFilters:ce,setIsDashboardEditing:R,setIsVisualEditing:U,dashboard:a,selectedSheetId:c,selectedFrameId:t.id,filterValues:f,inlineFilterValuesMap:h,currentSelections:{connectionId:m,databaseName:p,schemaName:g,tableName:b,datamodelId:x}}))}const{isError:Me,isLoading:Se,isFetching:ie,isPending:pe,data:Ne,handleDatapointClick:de,pagination:fe,comparisonMetadata:Oe}=z0(ue),{tableRecords:ye,pivotTableConfig:Ce,fallbackCfg:$e}=OWe(k,Ne,i),[ze,Ge]=w.useState({open:!1,position:null,interactions:[],context:null}),{breadcrumbs:Ke,hierarchyId:Ze}=Vt(Kp(Fe=>{var Nt,En;return{breadcrumbs:((Nt=Fe.interactionStates[N.id])==null?void 0:Nt.breadcrumbs)??LWe,hierarchyId:(En=Fe.interactionStates[N.id])==null?void 0:En.hierarchyId}})),st=(Fe,Nt,En)=>{var nr;const tn=Ke.length>0?[{mode:"drillUp",trigger:(nr=Fe[0])==null?void 0:nr.trigger,label:"Drill Up",hierarchyId:Ze}]:[],vt=[];for(const Ur of Fe)if(Ur.mode==="dynamicDrill"&&Ur.availableFields){const Rs=Ur.availableFields.filter(Zl=>!Ke.some(HE=>{var Iv;return((Iv=HE.toField)==null?void 0:Iv.id)===Zl.id}));for(const Zl of Rs)vt.push({mode:"dynamicDrill",trigger:Ur.trigger,drillField:Zl,label:Zl.label,availableFields:Ur.availableFields})}const Kn=Fe.filter(Ur=>Ur.mode!=="dynamicDrill"),tr=[...tn,...Kn,...vt];Ge({open:!0,position:En||{x:0,y:0},interactions:tr,context:Nt})},ae=N,{handlePointerInteraction:Pe,applySelectedInteraction:Ee}=d7(ae,t.id,c||"",st),_e=XD(ae),We=(Fe,Nt)=>{const En={...e,paginationConfig:{page:Fe+1,pageSize:Nt}},tn={...t,cards:t.cards.map(vt=>vt.id===e.id?En:vt)};c&&V(c,tn)},Te=Fe=>{var vt,Kn,tr;const Nt=Eee(Fe,(vt=e.config)==null?void 0:vt.metricColumns,(Kn=e.config)==null?void 0:Kn.groupByColumns,(tr=e.config)==null?void 0:tr.detailColumns),En={...e,config:{...e.config||{},sortByColumns:Nt}},tn={...t,cards:t.cards.map(nr=>nr.id===e.id?En:nr)};c&&V(c,tn)};function Ue(Fe,Nt){Fe.stopPropagation();const En=bWe({resolvedCardConfig:_e,card:ae,records:(Ne==null?void 0:Ne.records)||[],chart:Nt,clickEvent:Fe.nativeEvent,columnKeyMap:Ne==null?void 0:Ne.columnKeyMap});if(!En)return;const tn=gc(ae.interactionConfig),vt=eN(tn,En),Kn=vt.length===1&&vt[0].mode==="clickFilter",tr=vt.some(Rs=>Rs.mode==="dynamicDrill"),nr=vt.length>1||tr;Fe.button===0&&Kn&&!nr&&O(Fe.nativeEvent,Nt);const Ur={shift:Fe.shiftKey,ctrl:Fe.ctrlKey,meta:Fe.metaKey};Fe.button===0?Pe({context:En,gesture:"leftClick",modifierKeys:Ur,position:{x:Fe.clientX,y:Fe.clientY}}):Fe.button===2&&Pe({context:En,gesture:"rightClick",modifierKeys:Ur,position:{x:Fe.clientX,y:Fe.clientY}})}function et(){var Fe,Nt,En;if(S&&y)return pn;if(n&&n.length>0){const tn=n.find(vt=>vt.cardId===e.id);if(tn&&tn.replaceDefault){const vt=tn.content;if(vt)return l.jsx(vt,{card:e})}}if(!j&&e.type==="kpi"){if(((Fe=t==null?void 0:t.cards)==null?void 0:Fe.length)===1)return l.jsx(ph,{card:e,data:Me?[]:(Ne==null?void 0:Ne.records)||[],isPending:pe,isError:Me,comparisonMetadata:Oe});if(((Nt=t==null?void 0:t.cards)==null?void 0:Nt.length)>1)return l.jsx(Q8,{frame:t})}return!j&&e.type==="text"&&((En=t==null?void 0:t.cards)==null?void 0:En.length)===1?l.jsx(Fo,{className:"my-4 overflow-y-auto break-words px-4",children:l.jsx($p,{isLoading:Se||ie,card:e,data:(Ne==null?void 0:Ne.records)||[]})}):pn}function bt(){const Fe=k;if(S&&y)return l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(Ra,{FallbackComponent:My,children:l.jsx(mS,{frame:t,card:y})})});if(ke)return l.jsx(PWe,{canEditDashboard:!!L,isDashboardEditing:u,isMissingConnection:Re,onConfigure:me});if(Me)return l.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[l.jsx(GA,{className:"size-8 text-destructive"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Error fetching data. Check your card settings."})]});if((Se||ie)&&(!(Ne!=null&&Ne.records)||Ne.records.length===0))return e.type==="table"||e.type==="detailTable"?l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(Wre,{})}):l.jsx("div",{className:"flex h-full w-full items-center justify-center",children:l.jsx(ad,{size:"md",color:"muted","aria-label":"Loading data"})});if(Ne!=null&&Ne.records&&Ne.records.length===0&&!j)return r!=null&&r.NoRecords?l.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:r.NoRecords}):l.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[l.jsx(JA,{className:"size-8 text-muted-foreground"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});function Nt(){var En,tn,vt;if(Fe.type==="kpi"){if(((En=t==null?void 0:t.cards)==null?void 0:En.length)===1)return l.jsx(ph,{card:Fe,data:Me?[]:(Ne==null?void 0:Ne.records)||[],isPending:pe,isError:Me,comparisonMetadata:Oe});if(((tn=t==null?void 0:t.cards)==null?void 0:tn.length)>1)return l.jsx(Q8,{frame:t})}if(Fe.type==="table"||Fe.type==="detailTable")return l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(hh,{card:Fe,data:ye,comparisonMetadata:Oe,paginationMetadata:fe,onPaginationChange:We,onSortChange:Te,isLoading:Se||ie,frameId:t.id,sheetId:c||"",onMultipleInteractions:st})});if(Fe.type==="pivotTable"&&Ce)return l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(dv,{card:Fe,data:Ce.data,options:Ce.options,onAggregationChange:Kn=>{const tr=ZM(Kn,e.config),nr={...e,config:tr},Ur={...t,cards:t.cards.map(Rs=>Rs.id===e.id?nr:Rs)};c&&V(c,Ur)},onAggregationLabelChange:Kn=>{const tr=qre(Kn,e.config),nr={...e,config:tr},Ur={...t,cards:t.cards.map(Rs=>Rs.id===e.id?nr:Rs)};c&&V(c,Ur)}})});if(Fe.type==="aggregateTable")return l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(Yj,{card:Fe,data:(Ne==null?void 0:Ne.records)||[],groupByColumns:Ne==null?void 0:Ne.groupByColumns,pivotSchema:Ne==null?void 0:Ne.pivotSchema,paginationMetadata:fe,onPaginationChange:We,onAggregationChange:Kn=>{const tr=ZM(Kn,e.config),nr={...e,config:tr},Ur={...t,cards:t.cards.map(Rs=>Rs.id===e.id?nr:Rs)};c&&V(c,Ur)},isLoading:Se||ie})});if(Fe.type==="text")return l.jsx(Fo,{className:"overflow-y-auto break-words pr-2",children:l.jsx($p,{isLoading:Se||ie,card:Fe,data:(Ne==null?void 0:Ne.records)||[]})});if(aN(Fe)&&((vt=Fe.customCardPreferences)!=null&&vt.url))return l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(Ra,{FallbackComponent:My,children:l.jsx(mS,{frame:t,card:Fe})})});if(n&&n.length>0){const Kn=n.find(tr=>tr.cardId===Fe.id);if(Kn&&Kn.content){const tr=Kn.content;return l.jsx(tr,{card:Fe})}}return $e?l.jsx(ev,{cfg:$e,onChartClick:Ue,onDatapointClick:de}):null}return j?l.jsx(aE,{card:N,records:ye,title:N.title,sql:N.sql,python:N.python,layoutMode:"fill",disablePointerEvents:u,fallback:Nt()}):Nt()}function dt(){if(n&&n.length>0){const Fe=n.find(Nt=>Nt.cardId===e.id);if(Fe&&Fe.footer){const Nt=Fe.footer;if(Nt)return l.jsx(Nt,{card:e})}}return null}function St(){var En;if(S&&y)return null;const Fe=t.cards.filter(tn=>{var vt;return!((vt=tn.tabTitle)!=null&&vt.endsWith("__Header"))&&(tn.displayTab===!0||tn.displayTab===void 0)}),Nt=i==null?void 0:i.controlInputRadius;return l.jsx(As,{value:t.activeCardId,className:"flex items-center justify-end gap-3",onValueChange:tn=>{const vt={...t,activeCardId:tn};V(c,vt)},children:l.jsx(ys,{style:{borderRadius:i==null?void 0:i.controlInputRadius},className:"flex-end flex h-9 flex-wrap items-center border border-border bg-background p-0",children:(En=t.cards.filter(tn=>{var vt;return!((vt=tn.tabTitle)!=null&&vt.endsWith("__Header"))&&(tn.displayTab===!0||tn.displayTab===void 0)}))==null?void 0:En.map((tn,vt)=>l.jsx(on,{className:Q("h-full items-center rounded-none data-[state=active]:bg-muted data-[state=active]:shadow-none",{"border-r":vt!==Fe.length-1}),style:{borderTopLeftRadius:vt===0?Nt:0,borderTopRightRadius:vt===Fe.length-1?Nt:0,borderBottomLeftRadius:vt===0?Nt:0,borderBottomRightRadius:vt===Fe.length-1?Nt:0},value:tn.id,children:tn.tabTitle||tn.title},tn.id))})})}function Ot(){var Nt,En,tn,vt,Kn,tr;let Fe=t.cards.find(nr=>nr.type==="kpi"&&nr.tabTitle===`${e.tabTitle}__Header`);return Fe||(Fe=t.cards.find(nr=>nr.type==="kpi"&&nr.tabTitle==="All__Header")),Fe?l.jsx("div",{className:"flex items-end gap-2",children:l.jsx(uWe,{renderFilterInfo:()=>{var nr,Ur,Rs,Zl;return o("showFilterInfo")&&((Ur=(nr=N.preferences)==null?void 0:nr.displayOptions)==null?void 0:Ur.showFilterInfo)!==!1?l.jsx(KM,{cardId:N.id,cardFilters:(Rs=N.config)==null?void 0:Rs.filters,cardFilterCount:wS(((Zl=N.config)==null?void 0:Zl.filters)||null),inlineFilters:N.inlineFilters,inlineFilterValues:_,sheetId:c||""}):null},card:Fe})}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{role:"card-title-container",className:"flex h-7 items-center gap-2",children:[o("showTitle")&&l.jsx(ja,{className:Q("text-base",{}),children:l.jsx(Ui,{value:N.title,onSave:()=>{},isEditable:!1,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),o("showTitle")&&((Nt=N.info)==null?void 0:Nt.trim())&&l.jsx(YO,{card:N}),o("showTitle")&&l.jsx(Xre,{cardId:N.id}),o("showRefreshIndicator")&&N.refreshInterval&&l.jsxs(wn,{children:[l.jsx(Cn,{className:"pr-1",children:l.jsx("div",{className:Q("h-2 w-2 rounded-full bg-green-500 transition-opacity",{"opacity-10":Se||ie})})}),l.jsx(Tn,{side:"right",align:"center",children:l.jsx("p",{className:"text-xs",children:`Realtime (${N==null?void 0:N.refreshInterval})`})})]}),o("showFilterInfo")&&((tn=(En=N.preferences)==null?void 0:En.displayOptions)==null?void 0:tn.showFilterInfo)!==!1&&l.jsx(KM,{cardId:N.id,cardFilters:(vt=N.config)==null?void 0:vt.filters,cardFilterCount:wS(((Kn=N.config)==null?void 0:Kn.filters)||null),inlineFilters:N.inlineFilters,inlineFilterValues:_,sheetId:c||""}),Oe&&N.type!=="table"&&l.jsx(wee,{metadata:Oe,variant:"compact"})]}),l.jsxs("div",{"data-content":"card-description-and-breadcrumb",className:"flex h-6 items-center overflow-y-auto",children:[!E&&o("showDescription")&&((tr=N.description)==null?void 0:tr.trim())&&l.jsx("div",{className:Q("text-sm text-muted-foreground",{}),children:l.jsx(Ui,{value:(N.description||"").trim(),onSave:()=>{},isEditable:!1,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})}),E&&o("showBreadcrumbs")&&l.jsx(CWe,{cardId:N.id})]})]})}if(!e.id)return null;const xt=((he=(xe=N.preferences)==null?void 0:xe.displayOptions)==null?void 0:he.showChrome)??!0,an=((ut=(Le=N.preferences)==null?void 0:Le.displayOptions)==null?void 0:ut.allowScroll)??!0,Tt=((zt=(It=N.preferences)==null?void 0:It.displayOptions)==null?void 0:zt.showInlineFilterBar)??!0,ve=MWe(N),nt=RO(N),ct=xt?"px-6 pb-3":"px-3 pb-3",pn=xt?l.jsxs(l.Fragment,{children:[se?l.jsx(Na,{className:N.inlineFilters&&N.inlineFilters.length>0?"pb-3":"",children:l.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[l.jsx("div",{className:"flex-1 basis-0 scroll-pb-2 overflow-x-auto",role:"header-container",children:Ot()}),l.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[l.jsx("div",{children:M&&o("showFilters")&&l.jsxs("div",{style:{borderRadius:(cr=(bn=i==null?void 0:i.chart)==null?void 0:bn.options)==null?void 0:cr.borderRadius},"data-content":"frame-filter-container",className:"flex shrink-0 items-center",children:[!Ca(M.dataType)&&l.jsx(ge,{className:"my-1 shrink-0 px-3",children:l.jsx(Ui,{value:M.title||M.column,onSave:Fe=>B({...M,title:Fe}),isEditable:u,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),l.jsx(Vg,{filter:M})]})}),t.cards.length>1&&o("showTabs")&&St()]})]})}):l.jsx("div",{className:"h-8"}),(ve||Tt&&N.inlineFilters&&N.inlineFilters.length>0)&&l.jsx("div",{className:"px-6 pb-2",children:l.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[Tt&&N.inlineFilters&&N.inlineFilters.length>0&&l.jsx(Kre,{card:N,sheetId:c||""}),ve&&l.jsx(FWe,{card:N})]})}),l.jsx(Ea,{"data-role":"card-content",className:"relative flex min-h-0 grow flex-col",children:bt()}),nt&&e.type!=="kpi"&&l.jsx("div",{className:ct,children:l.jsx(QM,{card:N,mode:"dashboard"})}),o("showFooter")&&l.jsx(EU,{children:dt()})]}):l.jsxs(l.Fragment,{children:[bt(),nt&&e.type!=="kpi"&&l.jsx("div",{className:ct,children:l.jsx(QM,{card:N,mode:"dashboard"})})]}),Qr=()=>xt&&an?"flex h-full flex-col":xt&&!an?"flex h-full flex-col overflow-hidden":!xt&&!an?"h-full":"h-full overflow-auto";return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"relative h-full",children:[l.jsx("div",{className:Q(Qr(),{"animate-pulse":Se||ie}),children:et()}),(Se||ie)&&(Ne==null?void 0:Ne.records)&&Ne.records.length>0&&l.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-background/50",children:l.jsx(ad,{size:"md",color:"muted","aria-label":"Loading data"})})]}),ze.context&&l.jsx(pWe,{open:ze.open,onOpenChange:Fe=>{Ge(Nt=>({...Nt,open:Fe}))},position:ze.position,interactions:ze.interactions,selectedConditions:ze.context.conditions,drillHierarchies:(bo=N.interactionConfig)==null?void 0:bo.drillHierarchies,cardId:N.id,card:N,onSelectInteraction:Fe=>{ze.context&&Ee(Fe,ze.context),Ge({open:!1,position:null,interactions:[],context:null})}})]})}function Qre({card:e,frame:t}){var a,c;const n=TO(t,e),{manifest:r}=$h(((a=n==null?void 0:n.customCardPreferences)==null?void 0:a.url)||""),s=w.useMemo(()=>{var u;return(u=r==null?void 0:r.visuals)==null?void 0:u.find(d=>{var f;return d.name===((f=n==null?void 0:n.customCardPreferences)==null?void 0:f.componentName)})},[r,(c=n==null?void 0:n.customCardPreferences)==null?void 0:c.componentName]),i=cv(n,s)==="multiple"&&n?n:e;return i.displayPreferences?l.jsx(GO,{displayPreferences:i.displayPreferences,children:l.jsx(e9,{card:e,frame:t})}):l.jsx(e9,{card:e,frame:t})}Qre.displayName="DashboardCard";const Jre=F.memo(Qre);function $We({card:e,frame:t,showTitle:n=!0}){const{isError:r,isLoading:s,isFetching:o,data:i,pagination:a,comparisonMetadata:c}=z0(e),u=ee(x=>x.themeStyle),d=fl(e)==="dynamic"?Wx(e):e,{data:f}=$0(d),h=w.useMemo(()=>{var x;return d.type!=="pivotTable"||!((x=i==null?void 0:i.records)!=null&&x.length)?null:{records:i.records,columnSubtotalMeta:i.columnSubtotalMeta,subtotalColumns:i.subtotalColumns||[],pivotSchema:i.pivotSchema||[],groupByColumns:i.groupByColumns}},[d.type,i==null?void 0:i.records,i==null?void 0:i.columnSubtotalMeta,i==null?void 0:i.subtotalColumns,i==null?void 0:i.pivotSchema,i==null?void 0:i.groupByColumns]),m=Ig(d,h),p=w.useMemo(()=>(i==null?void 0:i.records)||[],[i==null?void 0:i.records]),g=w.useMemo(()=>{var x;if(!(!((x=i==null?void 0:i.records)!=null&&x.length)||["kpi","text","table","detailTable","pivotTable","aggregateTable","custom"].includes(d.type)))return xg({card:d,data:i.records,cardType:d.type,queryConfig:d.queryConfig,customCfg:d.customCfg,preferences:d.preferences,topoJson:f})},[i==null?void 0:i.records,d,f,u]);if(s||o)return l.jsxs("div",{className:"flex h-full grow flex-col items-center justify-center gap-4 p-12",children:[l.jsx(Mn,{className:"h-8 w-8 animate-spin text-muted-foreground"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading visual..."})]});if(r)return l.jsx("div",{className:"flex flex-col items-center justify-center gap-2 p-12",children:l.jsx("p",{className:"text-sm font-medium text-destructive",children:"Failed to load visual"})});function b(){function x(){var y;return d.type==="kpi"?l.jsx(ph,{card:d,data:(i==null?void 0:i.records)||[],isPending:s||o,comparisonMetadata:c}):d.type==="table"||d.type==="detailTable"?l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(hh,{card:d,data:p,comparisonMetadata:c,isLoading:s||o,paginationMetadata:a})}):d.type==="pivotTable"&&m?l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(dv,{card:d,data:(i==null?void 0:i.records)||[],onAggregationChange:()=>{},onAggregationLabelChange:()=>{}})}):d.type==="aggregateTable"?l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(Yj,{card:d,data:(i==null?void 0:i.records)||[],groupByColumns:i==null?void 0:i.groupByColumns,pivotSchema:i==null?void 0:i.pivotSchema,paginationMetadata:a,onAggregationChange:()=>{},isLoading:s||o})}):d.type==="text"?l.jsx(Fo,{className:"overflow-y-auto break-words pr-2",children:l.jsx($p,{isLoading:s||o,card:d,data:(i==null?void 0:i.records)||[]})}):aN(d)&&((y=d.customCardPreferences)!=null&&y.url)?l.jsx(Ra,{FallbackComponent:My,children:l.jsx(mS,{frame:t,card:d})}):g?l.jsx(ev,{cfg:g,onChartClick:()=>{},onDatapointClick:()=>{}}):null}return fl(e)==="dynamic"?l.jsx(aE,{card:e,records:p,title:e.title,sql:e.sql,python:e.python,layoutMode:"fill",fallback:x()}):x()}return l.jsxs("div",{className:"flex h-full w-full flex-col",children:[n&&e.title&&l.jsxs("div",{className:"border-b px-4 py-2",children:[l.jsx("h3",{className:"text-lg font-medium",children:e.title}),e.description&&l.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:e.description})]}),l.jsx("div",{className:"min-h-0 flex-1 p-4",children:b()})]})}function ese({insightId:e,filters:t,contextMode:n}){const{data:r,isLoading:s,isError:o,error:i}=AN(e,{enabled:!!e}),a=Vt(f=>f.setInteractionState),c=Vt(f=>f.resetInteractionState),u=w.useMemo(()=>{var f;return r?NZ((r==null?void 0:r.frameObject)??((f=r==null?void 0:r.visual)==null?void 0:f.frameObject)):null},[r]),d=w.useMemo(()=>lj(u),[u]);return w.useEffect(()=>{if(!d)return;if(n==="none"||!(t!=null&&t.length)){const p={...Oi(),contextMode:n};a(d.id,p);return}const h={sourceCardId:"drill-to-insight",interactionMode:"clickFilter",filterGroups:[{filters:t}],applyToCardIds:[d.id]},m={...Oi(),appliedClickFilters:[h],contextMode:n};return a(d.id,m),()=>{c(d.id)}},[d,t,n,a,c]),s?l.jsxs("div",{className:"flex h-full grow flex-col items-center justify-center gap-4 p-12",children:[l.jsx(Mn,{className:"h-8 w-8 animate-spin text-muted-foreground"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading visual..."})]}):o?l.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 p-12",children:[l.jsx("p",{className:"text-sm font-medium text-destructive",children:"Failed to load insight"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:i instanceof Error?i.message:"Unknown error"})]}):!u||!d?l.jsx("div",{className:"flex items-center justify-center p-12",children:l.jsx("p",{className:"text-sm text-muted-foreground",children:"This insight has no visual data to display"})}):l.jsx("div",{className:"h-full w-full",children:l.jsx($We,{card:d,frame:u,showTitle:!1})})}function zWe({filters:e,contextMode:t}){if(!e||e.length===0)return t==="none"?l.jsxs(Xe,{variant:"outline",className:"gap-1 whitespace-nowrap",children:[l.jsx(Ic,{className:"h-3 w-3"}),"No filters"]}):null;const n=e.reduce((s,o)=>{var a,c;const i=((a=o.field)==null?void 0:a.label)||((c=o.field)==null?void 0:c.name)||"Unknown";return s[i]||(s[i]=[]),s[i].push(o),s},{});e.length;const r=Object.keys(n).length;return l.jsx(gr,{children:l.jsxs(wn,{delayDuration:200,children:[l.jsx(Cn,{asChild:!0,children:l.jsxs(Xe,{variant:"secondary",className:"cursor-help gap-1 whitespace-nowrap border border-blue-500/20 bg-blue-500/10 text-blue-700 dark:text-blue-300",children:[l.jsx(Ic,{className:"h-3 w-3"}),r," ",r===1?"filter":"filters"]})}),l.jsx(Tn,{side:"bottom",align:"start",className:"max-w-md",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium",children:"Applied Filters"}),l.jsx("div",{className:"space-y-1.5",children:Object.entries(n).map(([s,o])=>l.jsxs("div",{className:"text-xs",children:[l.jsxs("span",{className:"font-medium",children:[s,":"]})," ",o.map((i,a)=>l.jsxs("span",{children:[VWe(i),a<o.length-1?", ":""]},a))]},s))}),t&&l.jsx("div",{className:"border-t pt-2 text-xs text-muted-foreground",children:BWe(t)})]})})]})})}function VWe(e){const{operator:t,value:n}=e;if(e.label){const r=e.label.split(/[=><]/);if(r.length>1)return r[1].trim()}switch(t){case"=":return String(n);case"!=":return`≠ ${n}`;case">":return`> ${n}`;case"<":return`< ${n}`;case">=":return`≥ ${n}`;case"<=":return`≤ ${n}`;case"in":return Array.isArray(n)?n.join(", "):String(n);case"not in":return`not ${Array.isArray(n)?n.join(", "):n}`;case"contains":return`contains ${n}`;case"startsWith":return`starts with ${n}`;case"endsWith":return`ends with ${n}`;case"between":return Array.isArray(n)?`${n[0]}-${n[1]}`:String(n);case"not between":return Array.isArray(n)?`not ${n[0]}-${n[1]}`:String(n);case"isNull":return"is null";case"isNotNull":return"is not null";default:return String(n)}}function BWe(e){switch(e){case"filters":case"interactionFilters":return"Showing data filtered by interaction only";case"full":return"Showing data with all dashboard filters + interaction filters";case"none":return"Showing all data (no filters applied)"}}function tse(e,t={}){const{enabled:n=!0}=t,{data:r}=AN(e,{enabled:n&&!!e});return w.useMemo(()=>{if(!r)return{title:"",description:void 0};const o=jZ(r);return o?{title:o.title,description:o.description}:{title:"",description:void 0}},[r])}function UWe({cardId:e,children:t}){const n=Vt(o=>o.replacedCards[e]),r=Vt(o=>o.restoreCard),s=tse((n==null?void 0:n.insightId)||"",{enabled:!!(n!=null&&n.insightId)});return n?l.jsxs("div",{className:"flex h-full w-full flex-col",children:[l.jsxs("div",{className:"border-b bg-muted/30",children:[l.jsx("div",{className:"flex items-baseline gap-2 px-5 pb-2 pt-4",children:s.title&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"truncate text-sm font-semibold",children:s.title}),s.description&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"text-muted-foreground",children:"-"}),l.jsx("span",{className:"truncate text-xs text-muted-foreground",children:s.description})]})]})}),l.jsxs("div",{className:"flex items-center gap-3 px-4 pb-2",children:[l.jsxs(re,{variant:"ghost",size:"sm",onClick:()=>r(e),className:"flex-shrink-0 gap-1",children:[l.jsx(TU,{className:"h-4 w-4"}),"Back"]}),l.jsx(zWe,{filters:n.filters,contextMode:n.contextMode})]})]}),l.jsx("div",{className:"min-h-0 flex-1",children:l.jsx(ese,{insightId:n.insightId,filters:n.filters,contextMode:n.contextMode})})]}):l.jsx(l.Fragment,{children:t})}function nse({frame:e,footer:t,className:n,...r}){var C,S;const s=w.useRef(null),[o,i]=w.useState(!1),a=ee(N=>N.themeStyle),c=ee(N=>N.isVisualEditing),u=ee(N=>N.selectedFrameId),d=ee(N=>N.isDashboardEditing),{setSelectedFrameId:f}=en(),{clearSelectedVisual:h}=Jp(),{setSelectedConnectionId:m,setSelectedDatabaseName:p,setSelectedSchemaName:g,setSelectedTableName:b,setCard:x}=lr();w.useEffect(()=>{if(u===e.id&&d&&!c){const N=s==null?void 0:s.current;N==null||N.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})}},[u,e.id,d,c,s]);const y=e.cards.find(N=>N.id===e.activeCardId);function v(N){N.stopPropagation(),f(e.id),h(),y&&x(y),y!=null&&y.connectionId&&m(y==null?void 0:y.connectionId),y!=null&&y.lastSelectedDatabase&&p(y==null?void 0:y.lastSelectedDatabase),y!=null&&y.lastSelectedSchema&&g(y==null?void 0:y.lastSelectedSchema),y!=null&&y.lastSelectedTable&&b(y==null?void 0:y.lastSelectedTable)}return l.jsx(Ra,{FallbackComponent:iE,children:l.jsxs("div",{tabIndex:-1,ref:s,role:"card-frame","data-frame-id":e.id,"data-active-card-id":y==null?void 0:y.id,onClick:v,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{borderRadius:a==null?void 0:a.cardBorderRadius},className:Q("relative flex h-full flex-col rounded-sm border bg-background shadow-sm",{"border-dashed border-foreground/50":u===e.id&&d},a==null?void 0:a.dashboardCard,n,"semaphor-card-frame"),...r,children:[(d||((S=(C=y==null?void 0:y.preferences)==null?void 0:C.displayOptions)==null?void 0:S.showCardToolbar)!==!1)&&l.jsx(Hre,{frame:e,isHovered:o}),y&&l.jsx(UWe,{cardId:y.id,children:l.jsx(Jre,{card:y,frame:e},y.id)})]})})}nse.displayName="DashboardFrame";const HWe=w.memo(nse);function WWe({filter:e,onUpdate:t}){const[n,r]=w.useState(""),s=ee(y=>y.dashboard.sheets)||[],o=ee(y=>y.selectedSheetId),i=w.useMemo(()=>{const y=[];return s==null||s.forEach(v=>{var C;(C=v.frames)==null||C.forEach(S=>{var N;(N=S.cards)==null||N.forEach(j=>{y.push({...j,sheetId:v.id,sheetTitle:v.title||v.id})})})}),y},[s]),a=()=>e.applyToSheetIds!==void 0?"specific-sheets":e.excludeSheetIds!==void 0?"all-except-specific":"all-sheets",c=()=>e.applyToCardIds!==void 0?"specific-cards":e.excludeCardIds!==void 0?"all-except-specific":"all-cards",u=y=>{const v={};switch(y){case"all-sheets":v.applyToSheetIds=void 0,v.excludeSheetIds=void 0;break;case"specific-sheets":v.applyToSheetIds=[],v.excludeSheetIds=void 0;break;case"all-except-specific":v.applyToSheetIds=void 0,v.excludeSheetIds=[];break}t(v)},d=y=>{const v={};switch(y){case"all-cards":v.applyToCardIds=void 0,v.excludeCardIds=void 0;break;case"specific-cards":v.applyToCardIds=[],v.excludeCardIds=void 0;break;case"all-except-specific":v.applyToCardIds=void 0,v.excludeCardIds=[];break}t(v)},f=(y,v)=>{if(v==="specific-sheets"){const C=e.applyToSheetIds||[],S=C.includes(y)?C.filter(N=>N!==y):[...C,y];t({applyToSheetIds:S})}else if(v==="all-except-specific"){const C=e.excludeSheetIds||[],S=C.includes(y)?C.filter(N=>N!==y):[...C,y];t({excludeSheetIds:S})}},h=(y,v)=>{if(v==="specific-cards"){const C=e.applyToCardIds||[],S=C.includes(y)?C.filter(N=>N!==y):[...C,y];t({applyToCardIds:S})}else if(v==="all-except-specific"){const C=e.excludeCardIds||[],S=C.includes(y)?C.filter(N=>N!==y):[...C,y];t({excludeCardIds:S})}},m=()=>{const y=a();return y==="specific-sheets"?e.applyToSheetIds||[]:y==="all-except-specific"?(s==null?void 0:s.filter(v=>{var C;return!((C=e.excludeSheetIds)!=null&&C.includes(v.id))}).map(v=>v.id))||[]:(s==null?void 0:s.map(v=>v.id))||[]},p=w.useMemo(()=>{const y=m();return i.filter(v=>y.includes(v.sheetId))},[i,e.applyToSheetIds,e.excludeSheetIds]),g=w.useMemo(()=>{if(!n.trim())return p;const y=n.toLowerCase();return p.filter(v=>{var C;return(C=v==null?void 0:v.title)==null?void 0:C.toLowerCase().includes(y)})},[n,p]),b=a(),x=c();return l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Sheet Scope"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Which sheets should display this filter?"})]}),l.jsxs(Do,{value:b,onValueChange:y=>u(y),className:"space-y-3",children:[l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"all-sheets",id:"all-sheets",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"all-sheets",className:"cursor-pointer text-sm font-medium",children:"All sheets"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Display filter on all sheets (",(s==null?void 0:s.length)||0," sheets)"]})]})]}),l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"specific-sheets",id:"specific-sheets",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"specific-sheets",className:"cursor-pointer text-sm font-medium",children:"Only specific sheets"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Display filter on selected sheets only"})]})]}),b==="specific-sheets"&&l.jsx("div",{className:"ml-7 space-y-2",children:l.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:s==null?void 0:s.map(y=>{const v=(e.applyToSheetIds||[]).includes(y.id);return l.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[l.jsx(Jt,{id:`sheet-${y.id}`,checked:v,onCheckedChange:()=>f(y.id,"specific-sheets")}),l.jsxs(ge,{htmlFor:`sheet-${y.id}`,className:"cursor-pointer text-sm font-medium",children:[y.title||y.id,y.id===o&&l.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:"(this sheet)"})]})]},y.id)})})}),l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"all-except-specific",id:"all-sheets-except",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"all-sheets-except",className:"cursor-pointer text-sm font-medium",children:"All sheets except specific ones"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Display filter on all sheets except selected ones"})]})]}),b==="all-except-specific"&&l.jsx("div",{className:"ml-7 space-y-2",children:l.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:s==null?void 0:s.map(y=>{const v=(e.excludeSheetIds||[]).includes(y.id);return l.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[l.jsx(Jt,{id:`sheet-exclude-${y.id}`,checked:v,onCheckedChange:()=>f(y.id,"all-except-specific")}),l.jsxs(ge,{htmlFor:`sheet-exclude-${y.id}`,className:"cursor-pointer text-sm font-medium",children:[y.title||y.id,y.id===o&&l.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:"(this sheet)"})]})]},y.id)})})})]})]}),l.jsxs("div",{className:"space-y-3 border-t pt-4",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Card Scope"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Which cards should receive this filter?"})]}),l.jsxs(Do,{value:x,onValueChange:y=>d(y),className:"space-y-3",children:[l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"all-cards",id:"all-cards",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"all-cards",className:"cursor-pointer text-sm font-medium",children:"All cards"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Apply filter to all cards in applicable sheets (",p.length," cards)"]})]})]}),l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"specific-cards",id:"specific-cards",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"specific-cards",className:"cursor-pointer text-sm font-medium",children:"Only specific cards"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to selected cards only"})]})]}),x==="specific-cards"&&l.jsxs("div",{className:"ml-7 space-y-2",children:[l.jsx(lt,{placeholder:"Search cards...",value:n,onChange:y=>r(y.target.value),className:"mb-2"}),l.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:g.length>0?g.map(y=>{const v=(e.applyToCardIds||[]).includes(y.id);return l.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[l.jsx(Jt,{id:`card-${y.id}`,checked:v,onCheckedChange:()=>h(y.id,"specific-cards")}),l.jsxs("div",{className:"flex-1",children:[l.jsx(ge,{htmlFor:`card-${y.id}`,className:"cursor-pointer text-sm font-medium",children:y.title}),l.jsx("p",{className:"text-xs text-muted-foreground",children:y.sheetTitle})]})]},y.id)}):l.jsxs("p",{className:"py-4 text-center text-sm text-muted-foreground",children:['No cards found matching "',n,'"']})})]}),l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"all-except-specific",id:"all-cards-except",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"all-cards-except",className:"cursor-pointer text-sm font-medium",children:"All cards except specific ones"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to all cards except selected ones"})]})]}),x==="all-except-specific"&&l.jsxs("div",{className:"ml-7 space-y-2",children:[l.jsx(lt,{placeholder:"Search cards...",value:n,onChange:y=>r(y.target.value),className:"mb-2"}),l.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:g.length>0?g.map(y=>{const v=(e.excludeCardIds||[]).includes(y.id);return l.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[l.jsx(Jt,{id:`card-exclude-${y.id}`,checked:v,onCheckedChange:()=>h(y.id,"all-except-specific")}),l.jsxs("div",{className:"flex-1",children:[l.jsx(ge,{htmlFor:`card-exclude-${y.id}`,className:"cursor-pointer text-sm font-medium",children:y.title}),l.jsx("p",{className:"text-xs text-muted-foreground",children:y.sheetTitle})]})]},y.id)}):l.jsxs("p",{className:"py-4 text-center text-sm text-muted-foreground",children:['No cards found matching "',n,'"']})})]})]})]}),l.jsx("div",{className:"rounded-md bg-blue-50 p-3 text-xs text-blue-900 dark:bg-blue-950 dark:text-blue-100",children:"ℹ️ Cards are filtered based on sheet scope selection. Only cards from applicable sheets are shown in card scope."})]})}function hv(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o<r.length;o++)s=r[o],!(t.indexOf(s)>=0)&&(n[s]=e[s]);return n}var qWe=["color"],YWe=w.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=hv(e,qWe);return w.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),w.createElement("path",{d:"M7.5 2C7.77614 2 8 2.22386 8 2.5L8 11.2929L11.1464 8.14645C11.3417 7.95118 11.6583 7.95118 11.8536 8.14645C12.0488 8.34171 12.0488 8.65829 11.8536 8.85355L7.85355 12.8536C7.75979 12.9473 7.63261 13 7.5 13C7.36739 13 7.24021 12.9473 7.14645 12.8536L3.14645 8.85355C2.95118 8.65829 2.95118 8.34171 3.14645 8.14645C3.34171 7.95118 3.65829 7.95118 3.85355 8.14645L7 11.2929L7 2.5C7 2.22386 7.22386 2 7.5 2Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),GWe=["color"],KWe=w.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=hv(e,GWe);return w.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),w.createElement("path",{d:"M7.14645 2.14645C7.34171 1.95118 7.65829 1.95118 7.85355 2.14645L11.8536 6.14645C12.0488 6.34171 12.0488 6.65829 11.8536 6.85355C11.6583 7.04882 11.3417 7.04882 11.1464 6.85355L8 3.70711L8 12.5C8 12.7761 7.77614 13 7.5 13C7.22386 13 7 12.7761 7 12.5L7 3.70711L3.85355 6.85355C3.65829 7.04882 3.34171 7.04882 3.14645 6.85355C2.95118 6.65829 2.95118 6.34171 3.14645 6.14645L7.14645 2.14645Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ZWe=["color"],XWe=w.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=hv(e,ZWe);return w.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),w.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),QWe=["color"],rse=w.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=hv(e,QWe);return w.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),w.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),JWe=["color"],sse=w.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=hv(e,JWe);return w.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),w.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Fc({text:e,className:t,ariaLabel:n,onCopy:r,disabled:s=!1}){const[o,i]=w.useState(!1);return l.jsx(re,{className:Q("h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",t),variant:"ghost",size:"icon","aria-label":n,disabled:s,onClick:async()=>{try{let a=!1;if(r)a=await r();else if(typeof e=="string"){if(typeof navigator>"u"||!navigator.clipboard)return;await navigator.clipboard.writeText(e),a=!0}if(!a)return;i(!0),setTimeout(()=>{i(!1)},1e3)}catch(a){console.error("Failed to copy text",a)}},children:o?l.jsx(rse,{className:"size-3.5"}):l.jsx(mp,{className:"size-3.5"})})}function ose(){const{authToken:e,tokenProps:t}=rt(),{data:n,isLoading:r,isFetching:s,isError:o}=Qt({queryKey:["plugins",e==null?void 0:e.accessToken],queryFn:()=>hme(t.apiServiceUrl,e==null?void 0:e.accessToken)});return{data:n,isLoading:r,isFetching:s,isError:o}}function fE(){const{data:e,isLoading:t,isError:n}=ose(),r=cN({queries:((e==null?void 0:e.plugins)||[]).map(c=>({queryKey:["manifest",c.value],queryFn:()=>xte(c.value),enabled:!!c.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:u=>Math.min(1e3*2**u,3e4)}))}),s=[],o=[];let i=t,a=n;return r.forEach((c,u)=>{var d;if(c.isLoading&&(i=!0),c.isError&&(a=!0),c.data&&((d=e==null?void 0:e.plugins)!=null&&d[u])){const f=e.plugins[u],h=c.data.visuals.map(m=>({name:m.name,pluginName:f.label,componentType:m.componentType,pluginType:f.type,icon:m.icon,chartType:m.chartType,visualType:m.visualType||(m.dataInputs&&m.dataInputs.length>1?"multiple":"single"),minInputs:m.minInputs,maxInputs:m.maxInputs,slots:m.slots,url:f.value}));if(s.push(...h),c.data.filters){const m=c.data.filters.map(p=>({name:p.name,component:p.component,pluginName:f.label,pluginType:f.type,icon:p.icon,filterType:p.filterType,supportedDataTypes:p.supportedDataTypes,url:f.value}));o.push(...m)}}}),{data:s,filters:o,isLoading:i,isError:a}}function eqe(e){const[t,n]=w.useState(null);return t}function tqe({pluginFilter:e}){const t=eqe(e.icon||""),n=e.name.charAt(0).toUpperCase();return l.jsxs("div",{className:"flex items-center gap-2",children:[t?l.jsx(t,{className:"h-4 w-4"}):l.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:n}),l.jsx("span",{children:e.name}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",e.pluginName,")"]})]})}function nqe({filter:e,onSelect:t,onClear:n}){const{filters:r,isLoading:s}=fE(),o=Sn(e.dataType),i=r==null?void 0:r.filter(u=>!u.supportedDataTypes||u.supportedDataTypes.length===0?!0:u.supportedDataTypes.some(d=>o.toLowerCase()===d.toLowerCase())),a=e.customFilterPreferences,c=a?`${a.url}::${a.componentName}`:"";return s?l.jsxs("div",{className:"flex h-9 items-center gap-2 text-sm text-muted-foreground",children:[l.jsx(Mn,{className:"h-4 w-4 animate-spin"}),"Loading custom filters..."]}):!i||i.length===0?l.jsx("div",{className:"text-sm text-muted-foreground",children:"No custom filters available"}):l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs(pt,{value:c,onValueChange:u=>{if(!u)return;const[d,f]=u.split("::"),h=i.find(m=>m.url===d&&m.component===f);h&&t({url:d,componentName:h.component,pluginFilterType:h.filterType,icon:h.icon})},children:[l.jsx(ft,{className:"h-9 flex-1",children:l.jsx(gt,{placeholder:"Use default UI"})}),l.jsx(ht,{children:i.map(u=>l.jsx(Ie,{value:`${u.url}::${u.component}`,children:l.jsx(tqe,{pluginFilter:u})},`${u.url}::${u.component}`))})]}),a&&l.jsx(re,{variant:"ghost",size:"sm",className:"h-9 w-9 p-0",onClick:n,title:"Clear custom filter selection",children:l.jsx(Mt,{className:"h-4 w-4"})})]})}function rqe(e){for(const[n,r]of Object.entries(k7))if(JSON.stringify(r)===JSON.stringify(e))return n;const t={day:"day",week:"week",month:"month",quarter:"quarter",year:"year"};switch(e.mode){case"last":{const n=e.complete?" (complete)":"",r=e.n>1?"s":"";return`Last ${e.n} ${t[e.unit]}${r}${n}`}case"this":{const n=e.toDate?" to date":"";return`This ${t[e.unit]}${n}`}case"previous":return`Previous ${t[e.unit]}`;case"between":return`Between ${e.from} and ${e.to} ${t[e.unit]}s`}}const sqe=["January","February","March","April","May","June","July","August","September","October","November","December"];function oqe(e){return fA(e)?`${sqe[e.month]} ${e.year}`:rqe(e)}function bT(e){return e&&Zp(e)?"relative":"fixed"}function iqe({filter:e,onUpdate:t,showFilterId:n=!0,filterOptionsData:r,timezone:s,variant:o="dashboard"}){var L;const[i,a]=w.useState(e.title===e.column?"":e.title||""),[c,u]=w.useState(e.column),[d,f]=w.useState(((L=e.defaultValues)==null?void 0:L.map($=>String($)))||[]),[h,m]=w.useState(e.defaultDateFilter),[p,g]=w.useState(bT(e.defaultDateFilter)),[b,x]=w.useState(e.targetColumns||[]),y=w.useMemo(()=>Sn(e.dataType)==="date",[e.dataType]),v=s||Intl.DateTimeFormat().resolvedOptions().timeZone,C=o==="inline"?"z-[80]":void 0,S=w.useMemo(()=>{if(!h)return;const $=sN(h,v);if(!$)return;const[B,V]=$;return{from:B,to:V}},[h,v]),N=w.useMemo(()=>{if(h&&fA(h))return{year:h.year,month:h.month}},[h]),j=w.useMemo(()=>{if(!(!h||!Zp(h)))return h},[h]);w.useEffect(()=>{var B;a(e.title===e.column?"":e.title||""),u(e.column),f(((B=e.defaultValues)==null?void 0:B.map(V=>String(V)))||[]);const $=e.defaultDateFilter;m($),g(bT($)),x(e.targetColumns||[])},[e]);function k(){const $=i.trim();t({title:$||e.column})}function T(){const $=c.trim();if($&&$!==e.column){const B=i.trim()!=="";t(B?{column:$}:{column:$,title:$})}}function E($){f($);const B=$.length>0?$.map(V=>{const R=Number(V);return!isNaN(R)&&wa(e.dataType)?R:V}):void 0;t({defaultValues:B})}function _($){m($),$&&g(bT($)),t({defaultDateFilter:$})}function M($){x($),t({targetColumns:$.length>0?$:void 0})}function P(){M([...b,{column:"",label:""}])}function D($){const B=b.filter((V,R)=>R!==$);M(B)}function A($,B,V){const R=b.map((U,O)=>O===$?{...U,[B]:V}:U);M(R)}return l.jsxs("div",{className:"space-y-5",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Label"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("p",{className:"text-xs",children:"Leave empty to use the column name. Provide a custom label to override it."}),n&&l.jsxs("div",{className:"space-y-1 border-t pt-2",children:[l.jsx("p",{className:"text-xs font-medium",children:"Filter ID"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("p",{className:"break-all font-mono text-xs text-muted-foreground",children:e.id}),l.jsx(Fc,{text:e.id})]})]})]})})]})})]}),l.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[l.jsx(Jt,{id:"hideLabel",checked:e.showLabel===!1,onCheckedChange:$=>{t({showLabel:!$})}}),l.jsx(ge,{htmlFor:"hideLabel",className:"cursor-pointer text-sm text-muted-foreground",children:"Hide label"})]})]}),l.jsx(lt,{value:i,onChange:$=>a($.target.value),onBlur:k,placeholder:e.column,className:"h-8 text-sm"})]}),y?l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Default Date Filter"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsx("p",{className:"text-xs",children:"Sets the initial date selection on load and previews it immediately while editing. Relative defaults recalculate on each load and scheduled execution, while fixed month defaults stay unchanged."})})]})})]}),e.dateSelectionMode==="months"?l.jsxs(As,{value:p,onValueChange:$=>g($),className:"space-y-2",children:[l.jsxs(ys,{className:"grid h-9 w-full grid-cols-2 overflow-hidden rounded-md p-1",children:[l.jsx(on,{value:"fixed",className:"h-7 text-xs leading-none",children:"Fixed"}),l.jsx(on,{value:"relative",className:"h-7 text-xs leading-none",children:"Relative"})]}),l.jsx(sr,{value:"fixed",className:"mt-0",children:l.jsx(Yte,{value:N,placeholder:"Select default month...",className:"w-full",onClear:()=>_(void 0),onChange:($,B)=>_({mode:"fixed",unit:"month",year:$,month:B})})}),l.jsx(sr,{value:"relative",className:"mt-0",children:l.jsxs(pt,{value:j?JSON.stringify(j):"__none__",onValueChange:$=>{if($==="__none__"){_(void 0);return}try{const B=JSON.parse($);_(B)}catch(B){console.error("Failed to parse relative date filter",B)}},children:[l.jsx(ft,{className:"h-8",children:l.jsx(gt,{placeholder:"Select default month range..."})}),l.jsxs(ht,{className:C,children:[l.jsx(Ie,{value:"__none__",children:"None"}),l.jsx(Ie,{value:JSON.stringify({mode:"this",unit:"month"}),children:"This month"}),l.jsx(Ie,{value:JSON.stringify({mode:"previous",unit:"month"}),children:"Last month"})]})]})})]}):l.jsx(iO,{value:S,onRelativeSelect:($,B)=>{_(B)},showRelativeTab:!0,hideCalendar:!0,timezone:v,placeholder:"Select default date range...",buttonClassName:"h-8",contentClassName:C,overlayContentClassName:C}),h&&l.jsx("div",{className:"flex items-center gap-2",children:l.jsxs(Xe,{variant:"secondary",className:"gap-1.5 text-xs",children:[oqe(h),l.jsx(Mt,{className:"h-3 w-3 cursor-pointer hover:text-destructive",onClick:()=>_(void 0)})]})})]}):l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Default Values"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsx("p",{className:"text-xs",children:"Sets the initial selection on load and previews it immediately while editing. Works like a filter selection."})})]})})]}),r!=null&&r.records&&r.records.length>0?l.jsxs(pt,{value:"",onValueChange:$=>{$&&!d.includes($)&&E([...d,$])},children:[l.jsx(ft,{className:"h-8",children:l.jsx(gt,{placeholder:"Select values to add..."})}),l.jsxs(ht,{className:C,children:[r.records.filter($=>{var R;const B=(R=e.column.split(".").pop())==null?void 0:R.replace(/"/g,""),V=B?$[B]:$.value;return V!=null&&!d.includes(String(V))}).map($=>{var R;const B=(R=e.column.split(".").pop())==null?void 0:R.replace(/"/g,""),V=B?$[B]:$.value;return l.jsx(Ie,{value:String(V),children:String(V)},String(V))}),r.records.every($=>{var R;const B=(R=e.column.split(".").pop())==null?void 0:R.replace(/"/g,""),V=B?$[B]:$.value;return V==null||d.includes(String(V))})&&l.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"All values selected"})]})]}):l.jsx("div",{className:"flex h-8 items-center rounded-md border bg-muted px-2 text-xs text-muted-foreground",children:"Loading filter options..."}),d.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"text-xs font-medium text-muted-foreground",children:["Selected (",d.length,"):"]}),l.jsx("div",{className:"flex flex-wrap gap-1.5",children:d.map($=>l.jsxs(Xe,{variant:"secondary",className:"gap-1.5 text-xs",children:[String($),l.jsx(Mt,{className:"h-3 w-3 cursor-pointer hover:text-destructive",onClick:()=>{E(d.filter(B=>B!==$))}})]},$))})]})]}),y&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Target Columns"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsx("p",{className:"text-xs",children:"Add multiple date columns to let users choose which field to filter at runtime. Leave empty to use only the primary column above."})})]})})]}),b.length>0&&l.jsx("div",{className:"space-y-2",children:b.map(($,B)=>l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(lt,{placeholder:"Column name",value:$.column,onChange:V=>A(B,"column",V.target.value),className:"h-8 flex-1 font-mono text-xs"}),l.jsx(lt,{placeholder:"Label",value:$.label,onChange:V=>A(B,"label",V.target.value),className:"h-8 flex-1 text-xs"}),l.jsx(re,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>D(B),children:l.jsx(Mt,{className:"h-4 w-4"})})]},B))}),l.jsxs(re,{variant:"outline",size:"sm",className:"h-8",onClick:P,children:[l.jsx($r,{className:"mr-1 h-4 w-4"}),"Add Column"]})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Column Name"}),l.jsx(lt,{value:c,onChange:$=>u($.target.value),onBlur:T,placeholder:"Enter column name",className:"h-8 font-mono text-xs"})]})]})}function aqe({filter:e,onUpdate:t,variant:n="dashboard"}){const{filters:r,isLoading:s}=fE(),o=w.useMemo(()=>Sn(e.dataType)==="date",[e.dataType]),i=n==="inline"?"z-[80]":void 0,a=w.useMemo(()=>{const p=Sn(e.dataType);return(r==null?void 0:r.filter(g=>!g.supportedDataTypes||g.supportedDataTypes.length===0?!0:g.supportedDataTypes.some(b=>p.toLowerCase()===b.toLowerCase())))??[]},[e.dataType,r]),c=s||!!e.customFilterPreferences||a.length>0;function u(p){t({type:p})}function d(p){t({dateSelectionMode:p})}function f(p){t({uiType:p})}function h(p){t({customFilterPreferences:p})}function m(){t({customFilterPreferences:void 0})}return l.jsxs("div",{className:"space-y-5",children:[o?l.jsxs("div",{className:"space-y-1",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Date Picker Type"}),l.jsxs(pt,{value:e.dateSelectionMode||"range",onValueChange:p=>d(p),children:[l.jsx(ft,{className:"h-8",children:l.jsx(gt,{})}),l.jsxs(ht,{className:i,children:[l.jsx(Ie,{value:"range",children:"Date Range Picker"}),l.jsx(Ie,{value:"months",children:"Month Picker"})]})]})]}):l.jsxs("div",{className:"space-y-1",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Selection Type"}),l.jsxs(pt,{value:e.type||"multiple",onValueChange:u,children:[l.jsx(ft,{className:"h-8",children:l.jsx(gt,{})}),l.jsxs(ht,{className:i,children:[l.jsx(Ie,{value:"multiple",children:"Multiple"}),l.jsx(Ie,{value:"single",children:"Single"})]})]})]}),!o&&e.type==="single"&&l.jsxs("div",{className:"space-y-1",children:[l.jsx(ge,{className:"text-sm font-medium",children:"UI Component"}),l.jsxs(pt,{value:e.uiType||"dropdown",onValueChange:f,children:[l.jsx(ft,{className:"h-8",children:l.jsx(gt,{})}),l.jsxs(ht,{className:i,children:[l.jsx(Ie,{value:"dropdown",children:"Dropdown"}),l.jsx(Ie,{value:"radio",children:"Radio"}),l.jsx(Ie,{value:"tabs",children:"Tabs"})]})]})]}),c&&l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Custom Filter Component"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsx("p",{className:"text-xs",children:"Select a custom filter component from an installed plugin to replace the default filter UI with a custom implementation."})})]})})]}),l.jsx(nqe,{filter:e,onSelect:h,onClear:m})]}),n==="dashboard"&&l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Display Mode"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsx("p",{className:"text-xs",children:`Choose how this filter is displayed. "Inherit" uses the dashboard's default setting. Override with "Canvas Card" or "Toolbar" to always display this filter in a specific mode.`})})]})})]}),l.jsxs(pt,{value:e.displayMode||"inherit",onValueChange:p=>t({displayMode:p}),children:[l.jsx(ft,{className:"h-8",children:l.jsx(gt,{})}),l.jsxs(ht,{children:[l.jsx(Ie,{value:"inherit",children:"Inherit (use dashboard default)"}),l.jsx(Ie,{value:"canvas",children:"Canvas Card"}),l.jsx(Ie,{value:"toolbar",children:"Toolbar"})]})]})]}),n==="inline"&&l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Width (px)"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsx("p",{className:"text-xs",children:"Set the width of this inline filter in pixels. Default is 250px."})})]})})]}),l.jsx(lt,{type:"number",min:100,max:500,value:e.width??250,onChange:p=>{const g=parseInt(p.target.value,10);isNaN(g)||t({width:g})},className:"h-8 w-24 text-sm"})]})]})}function lqe({filter:e,onUpdate:t,variant:n="dashboard"}){const[r,s]=w.useState(e.sql),[o,i]=w.useState(e.searchMode||"auto"),a=n==="inline"?"z-[80]":void 0;w.useEffect(()=>{s(e.sql),i(e.searchMode||"auto")},[e]);function c(){t({sql:r})}function u(d){i(d),t({searchMode:d})}return l.jsxs("div",{className:"space-y-5",children:[wa(e.dataType)&&l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Search Mode"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsxs("div",{className:"space-y-2 text-xs",children:[l.jsxs("p",{children:[l.jsx("strong",{children:"Text Search:"}),' Treats numbers as text (e.g., ZIP codes, IDs). Search for "90210".']}),l.jsxs("p",{children:[l.jsx("strong",{children:"Numeric Operators:"})," Supports comparison operators (e.g., >100, <=50, =100) for quantities, prices."]}),l.jsxs("p",{children:[l.jsx("strong",{children:"Auto-detect:"})," Tries numeric first, falls back to text search."]})]})})]})})]}),l.jsxs(pt,{value:o,onValueChange:u,children:[l.jsx(ft,{className:"h-8",children:l.jsx(gt,{})}),l.jsxs(ht,{className:a,children:[l.jsx(Ie,{value:"text",children:"Text Search"}),l.jsx(Ie,{value:"numeric",children:"Numeric Operators"}),l.jsx(Ie,{value:"auto",children:"Auto-detect"})]})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"SQL"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsx("p",{className:"text-xs",children:"This SQL will be used to fetch the filter values"})})]})})]}),l.jsx(yi,{onKeyDown:d=>{d.stopPropagation()},value:r,onChange:d=>s(d.target.value),onBlur:c,className:`h-32 w-full resize-none break-all font-mono text-xs ${pu}`,placeholder:"SELECT column FROM table..."})]})]})}const cqe=[{id:"basic",label:"Basic Settings",title:"Basic Settings",subtitle:"Configure the core filter properties"},{id:"scope",label:"Scope",title:"Scope",subtitle:"Configure which sheets and cards this filter applies to"},{id:"behavior",label:"Behavior",title:"Behavior",subtitle:"Control how this filter appears and behaves"},{id:"data",label:"Data",title:"Data",subtitle:"Control how this filter searches and fetches values"}];function KO({filter:e,variant:t="dashboard",onAccept:n,open:r,onOpenChange:s,trigger:o,isEditing:i=!1}){var P,D,A;function a(L){if(!L)return"Unknown";const $=Sn(L),B=$==="date"?"Datetime":$==="string"?"Text":$==="number"?"Number":$==="boolean"?"Boolean":$==="json"?"JSON":"Geo";return/nullable/i.test(L)?`${B} (nullable)`:B}const[c,u]=w.useState(!1),d=r??c,f=s??u,[h,m]=w.useState("basic"),[p,g]=w.useState({}),{updateFilter:b,addOrUpdateFilterValue:x,removeFilterValues:y}=en(),v=w.useMemo(()=>cqe.filter(L=>t==="dashboard"||L.id!=="scope"),[t]),{tokenProps:C}=rt(),S=((D=(P=C==null?void 0:C.params)==null?void 0:P.calendarContext)==null?void 0:D.tz)||((A=C==null?void 0:C.params)==null?void 0:A.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone,{data:N}=cO(e),j={...e,...p},k=v.find(L=>L.id===h)||v[0];function T(){let L={...p};const $=Object.prototype.hasOwnProperty.call(L,"defaultValues")||Object.prototype.hasOwnProperty.call(L,"defaultDateFilter");if(t==="inline"&&"width"in L){const B=L.width;L={...L,width:Math.min(500,Math.max(100,B))}}if(n)n(L);else{const B={...e,...L};if(b(B),$){const V=hA(B,S);V?x(V):y(e.id)}}g({}),f(!1)}function E(L){g($=>({...$,...L}))}w.useEffect(()=>{d&&(g({}),m("basic"))},[d]);const _=e.column.split(".").pop()||e.column,M=a(e.dataType);return l.jsxs(Gr,{open:d,onOpenChange:f,children:[l.jsx(Kr,{asChild:!0,children:o??l.jsx("button",{type:"button",className:Q("rounded p-0.5 hover:bg-muted focus:visible focus:outline-none focus:ring-1 focus:ring-ring",i?"visible":"invisible group-hover:visible"),"aria-label":"Filter settings",children:l.jsx(gl,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})}),l.jsx(Zr,{onMouseDown:L=>L.stopPropagation(),onDoubleClick:L=>L.stopPropagation(),className:Q("m-2 h-[400px] w-[600px] p-0",t==="inline"?"z-[70]":"z-50"),children:l.jsxs("div",{className:"flex h-full",children:[l.jsxs("div",{className:"flex w-[180px] min-w-0 flex-col border-r bg-muted/30 p-4",children:[l.jsxs("div",{className:"mb-6 min-w-0",children:[l.jsx("h4",{className:"truncate text-sm font-medium",title:e.column,children:_}),l.jsx(Xe,{variant:"secondary",className:"mt-1 inline-flex max-w-full truncate text-[10px] font-medium leading-tight",title:e.dataType,children:M})]}),l.jsx("nav",{className:"flex flex-1 flex-col gap-1",children:v.map(L=>l.jsx("button",{onClick:()=>m(L.id),className:Q("rounded-md px-3 py-2 text-left text-sm transition-colors",h===L.id?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:L.label},L.id))})]}),l.jsxs("div",{className:"flex min-w-0 flex-1 flex-col p-6",children:[l.jsxs("div",{className:"mb-6",children:[l.jsx("h3",{className:"text-lg font-semibold",children:k.title}),l.jsx("p",{className:"text-sm text-muted-foreground",children:k.subtitle})]}),l.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[h==="basic"&&l.jsx(iqe,{filter:j,onUpdate:E,showFilterId:!0,filterOptionsData:N,timezone:S,variant:t}),h==="behavior"&&l.jsx(aqe,{filter:j,onUpdate:E,variant:t}),h==="data"&&l.jsx(lqe,{filter:j,onUpdate:E,variant:t}),h==="scope"&&t==="dashboard"&&l.jsx(WWe,{filter:j,onUpdate:E})]}),l.jsx("div",{className:"mt-4 flex justify-end",children:l.jsx(re,{onClick:T,size:"sm",children:"Accept"})})]})]})})]})}function uqe(e=[]){const t=w.useRef(null),n=w.useRef(null),r=w.useRef(null),[s,o]=w.useState(),i=w.useCallback(()=>{var m,p,g;const a=((m=t.current)==null?void 0:m.clientWidth)??0,c=((p=r.current)==null?void 0:p.offsetWidth)??0,u=((g=n.current)==null?void 0:g.offsetWidth)??0,f=a-c-u-8,h=Math.max(f,0);o(b=>b===h?b:h)},[]);return w.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=new ResizeObserver(()=>i());return c.observe(a),i(),()=>c.disconnect()},[i,...e]),{headerRef:t,leftActionsRef:n,rightActionsRef:r,titleMaxWidth:s,updateAvailableWidth:i}}function ZO({filter:e}){var p;const t=ee(g=>g.isDashboardEditing),{preferences:n}=ag(),r=((p=n==null?void 0:n.cardDisplay)==null?void 0:p.mode)==="print",s=ee(g=>g.filterValues),o=s==null?void 0:s.some(g=>g.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:c}=en(),{headerRef:u,leftActionsRef:d,rightActionsRef:f,titleMaxWidth:h,updateAvailableWidth:m}=uqe([t,o,r]);return w.useEffect(()=>{m()},[e.title,m]),l.jsxs("div",{ref:u,className:"group mb-1 flex h-5 items-center justify-between",children:[l.jsxs("div",{className:"flex grow items-center gap-2 min-w-0",children:[l.jsx("div",{className:"min-w-0 flex-1",style:h!==void 0?{maxWidth:h}:void 0,children:l.jsx(ge,{className:"my-1 block w-full text-sm",children:l.jsx(Ui,{value:e.title||e.column,onSave:g=>c({...e,title:g}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm truncate",inputClassName:"text-sm"})})}),l.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",ref:d,children:[t&&l.jsx(KO,{filter:e,isEditing:t}),t&&l.jsx("button",{onClick:()=>{i(e.id),a(e.id)},className:"text-muted-foreground hover:text-foreground",children:l.jsx(Mt,{className:"size-3.5"})})]})]}),l.jsx("div",{className:"hidden",ref:f})]})}function dqe({sheetId:e}){const{handleAddNewFrame:t}=_Z(),n=ee(s=>s.themeStyle),r=()=>{t({openVisualEditor:!0,sheetId:e})};return l.jsx("div",{className:"flex h-full min-h-[400px] items-start justify-start p-4",children:l.jsxs("button",{onClick:r,style:{borderRadius:n==null?void 0:n.cardBorderRadius},className:"group flex h-96 w-[600px] flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed border-muted-foreground/25 bg-background transition-all hover:border-muted-foreground/50 hover:bg-muted/50",children:[l.jsx("div",{className:"rounded-full bg-primary/10 p-3 transition-colors group-hover:bg-primary/20",children:l.jsx($r,{className:"h-6 w-6 text-primary"})}),l.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Add new Visual"})]})})}function bh(e){const t=(e||"").toLowerCase(),n=Sn(t);return n==="string"?l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-blue-200/70 bg-gradient-to-r from-blue-100/60 to-blue-200/40 text-blue-900 shadow-sm dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100",children:l.jsx(eI,{className:"h-3 w-3"})}):n==="number"?l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-green-200/70 bg-gradient-to-r from-green-100/60 to-green-200/40 text-green-900 shadow-sm dark:border-green-800/50 dark:from-green-950/40 dark:to-green-900/30 dark:text-green-100",children:l.jsx($U,{className:"h-3 w-3"})}):n==="date"?l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-purple-200/70 bg-gradient-to-r from-purple-100/60 to-purple-200/40 text-purple-900 shadow-sm dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100",children:l.jsx(js,{className:"h-3 w-3"})}):n==="boolean"?l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-orange-200/70 bg-gradient-to-r from-orange-100/60 to-orange-200/40 text-orange-900 shadow-sm dark:border-orange-800/50 dark:from-orange-950/40 dark:to-orange-900/30 dark:text-orange-100",children:l.jsx(Fpe,{className:"h-3 w-3"})}):n==="json"?l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-gray-200/70 bg-gradient-to-r from-gray-100/60 to-gray-200/40 text-gray-900 shadow-sm dark:border-gray-800/50 dark:from-gray-950/40 dark:to-gray-900/30 dark:text-gray-100",children:l.jsx(FU,{className:"h-3 w-3"})}):n==="geo"?l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-amber-200/70 bg-gradient-to-r from-amber-100/60 to-amber-200/40 text-amber-900 shadow-sm dark:border-amber-800/50 dark:from-amber-950/40 dark:to-amber-900/30 dark:text-amber-100",children:l.jsx(vpe,{className:"h-3 w-3"})}):n==="calculated"?l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-indigo-200/70 bg-gradient-to-r from-indigo-100/60 to-indigo-200/40 text-indigo-900 shadow-sm dark:border-indigo-800/50 dark:from-indigo-950/40 dark:to-indigo-900/30 dark:text-indigo-100",children:l.jsx(AA,{className:"h-3 w-3"})}):l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-gray-200/70 bg-gradient-to-r from-gray-100/60 to-gray-200/40 text-gray-900 shadow-sm dark:border-gray-800/50 dark:from-gray-950/40 dark:to-gray-900/30 dark:text-gray-100",children:l.jsx(eI,{className:"h-3 w-3"})})}function fqe({value:e,onChange:t,metrics:n,attributes:r}){const s=(o,i)=>(e==null?void 0:e.field.id)===o.id&&(e==null?void 0:e.type)===i;return l.jsx(gr,{children:l.jsxs("div",{className:"space-y-4",children:[n.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Value of Metric"}),l.jsxs(wn,{children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 text-muted-foreground"})}),l.jsxs(Tn,{className:"max-w-xs",children:[l.jsx("p",{className:"text-xs font-medium mb-1",children:"Captures intersection of all dimensions"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:`Example: Clicking a bar segment in "Sales by Country, stacked by State" captures both Country='USA' AND State='California'`})]})]})]}),l.jsx("div",{className:"space-y-1",children:n.map(o=>{const i=s(o,"metric");return l.jsxs(re,{variant:i?"default":"outline",size:"sm",className:Q("w-full justify-start font-normal",i&&"bg-primary text-primary-foreground"),onClick:()=>t({type:"metric",field:o}),children:[i&&l.jsx(qr,{className:"mr-2 h-4 w-4"}),bh(o.dataType),l.jsx("span",{className:"ml-2",children:o.label})]},o.id)})})]}),r.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Value of Attribute"}),l.jsxs(wn,{children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 text-muted-foreground"})}),l.jsxs(Tn,{className:"max-w-xs",children:[l.jsx("p",{className:"text-xs font-medium mb-1",children:"Captures only this dimension"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:`Example: If configured on "State", clicking a bar in "Sales by Country, stacked by State" captures only State='California' (Country is not included)`})]})]})]}),l.jsx("div",{className:"space-y-1",children:r.map(o=>{const i=s(o,"attribute");return l.jsxs(re,{variant:i?"default":"outline",size:"sm",className:Q("w-full justify-start font-normal",i&&"bg-primary text-primary-foreground"),onClick:()=>t({type:"attribute",field:o}),children:[i&&l.jsx(qr,{className:"mr-2 h-4 w-4"}),bh(o.dataType),l.jsx("span",{className:"ml-2",children:o.label})]},o.id)})})]}),n.length===0&&r.length===0&&l.jsx("div",{className:"text-sm text-muted-foreground text-center py-8",children:"No metrics or attributes available in this chart"})]})})}const t9=[{value:"clickFilter",label:"Cross filter",description:"Filter other cards on the dashboard"},{value:"drillDown",label:"Drill down",description:"Navigate through a hierarchy of dimensions"},{value:"dynamicDrill",label:"Explore dimensions",description:"Let users explore any dimension dynamically"},{value:"drillThrough",label:"Drill into dashboard",description:"Navigate to another dashboard"},{value:"drillToDetail",label:"Drill into insight",description:"Navigate to a saved insight"},{value:"drillToURL",label:"Drill into URL",description:"Navigate to a custom URL"}];function hqe({value:e,onChange:t}){const n=t9.find(r=>r.value===e);return l.jsx("div",{className:"space-y-2",children:l.jsxs(pt,{value:e,onValueChange:t,children:[l.jsx(ft,{className:"w-full",children:l.jsx(gt,{placeholder:"Choose action...",children:n&&l.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const r=CS(n.value);return l.jsx(r,{className:"h-4 w-4"})})(),l.jsx("span",{children:n.label})]})})}),l.jsx(ht,{children:t9.map(r=>{const s=CS(r.value);return l.jsx(Ie,{value:r.value,children:l.jsxs("div",{className:"flex items-start gap-2 py-1",children:[l.jsx(s,{className:"mt-0.5 h-4 w-4 shrink-0"}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{className:"font-medium",children:r.label}),l.jsx("span",{className:"text-xs text-muted-foreground",children:r.description})]})]})},r.value)})})]})})}function mqe({interaction:e,onUpdate:t}){const[n,r]=w.useState(""),s=X7(),o=()=>e.applyToCardIds!==void 0?"specific-cards":e.excludeCardIds!==void 0?"all-except-specific":"all-cards",i=d=>{const f={};switch(d){case"all-cards":f.applyToCardIds=void 0,f.excludeCardIds=void 0;break;case"specific-cards":f.applyToCardIds=[],f.excludeCardIds=void 0;break;case"all-except-specific":f.applyToCardIds=void 0,f.excludeCardIds=[];break}t({...e,...f})},a=(d,f)=>{if(f==="specific-cards"){const h=e.applyToCardIds||[],m=h.includes(d)?h.filter(p=>p!==d):[...h,d];t({...e,applyToCardIds:m})}else if(f==="all-except-specific"){const h=e.excludeCardIds||[],m=h.includes(d)?h.filter(p=>p!==d):[...h,d];t({...e,excludeCardIds:m})}},c=w.useMemo(()=>{if(!n.trim())return s;const d=n.toLowerCase();return s==null?void 0:s.filter(f=>{var h;return(h=f==null?void 0:f.title)==null?void 0:h.toLowerCase().includes(d)})},[n,s]),u=o();return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Filter scope"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose which cards should receive the filter"})]}),l.jsxs(Do,{value:u,onValueChange:d=>i(d),className:"space-y-2",children:[l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"all-cards",id:"all-cards",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"all-cards",className:"cursor-pointer text-sm font-medium",children:"All cards"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to all cards in the dashboard"})]})]}),l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"specific-cards",id:"specific-cards",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"specific-cards",className:"cursor-pointer text-sm font-medium",children:"Only specific cards"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to selected cards only"})]})]}),u==="specific-cards"&&l.jsxs("div",{className:"ml-7 space-y-2",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Cards to filter"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Select which cards should receive the filter"})]}),l.jsx(lt,{placeholder:"Search cards...",value:n,onChange:d=>r(d.target.value),className:"mb-2"}),l.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:c&&c.length>0?c.map(d=>{const f=(e.applyToCardIds||[]).includes(d.id);return l.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[l.jsx(Jt,{id:`card-${d.id}`,checked:f,onCheckedChange:()=>a(d.id,"specific-cards")}),l.jsxs("div",{className:"flex-1",children:[l.jsx(ge,{htmlFor:`card-${d.id}`,className:"cursor-pointer text-sm font-medium",children:d.title}),d.description&&l.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:d.description})]})]},d.id)}):l.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:n?`No cards found matching "${n}"`:"No cards available"})})]}),l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"all-except-specific",id:"all-except-specific",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"all-except-specific",className:"cursor-pointer text-sm font-medium",children:"All cards except specific ones"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to all cards, excluding selected ones"})]})]}),u==="all-except-specific"&&l.jsxs("div",{className:"ml-7 space-y-2",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Cards to exclude"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Select which cards should be excluded from filtering"})]}),l.jsx(lt,{placeholder:"Search cards...",value:n,onChange:d=>r(d.target.value),className:"mb-2"}),l.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:c&&c.length>0?c.map(d=>{const f=(e.excludeCardIds||[]).includes(d.id);return l.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[l.jsx(Jt,{id:`card-exclude-${d.id}`,checked:f,onCheckedChange:()=>a(d.id,"all-except-specific")}),l.jsxs("div",{className:"flex-1",children:[l.jsx(ge,{htmlFor:`card-exclude-${d.id}`,className:"cursor-pointer text-sm font-medium",children:d.title}),d.description&&l.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:d.description})]})]},d.id)}):l.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:n?`No cards found matching "${n}"`:"No cards available"})})]})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Menu label"}),l.jsx(lt,{value:e.label||"",onChange:d=>t({...e,label:d.target.value}),placeholder:Uh(e.mode)}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}function pqe(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return w.useMemo(()=>r=>{t.forEach(s=>s(r))},t)}const hE=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Bg(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function XO(e){return"nodeType"in e}function $o(e){var t,n;return e?Bg(e)?e:XO(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function QO(e){const{Document:t}=$o(e);return e instanceof t}function mv(e){return Bg(e)?!1:e instanceof $o(e).HTMLElement}function ise(e){return e instanceof $o(e).SVGElement}function Ug(e){return e?Bg(e)?e.document:XO(e)?QO(e)?e:mv(e)||ise(e)?e.ownerDocument:document:document:document}const Fa=hE?w.useLayoutEffect:w.useEffect;function mE(e){const t=w.useRef(e);return Fa(()=>{t.current=e}),w.useCallback(function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];return t.current==null?void 0:t.current(...r)},[])}function gqe(){const e=w.useRef(null),t=w.useCallback((r,s)=>{e.current=setInterval(r,s)},[]),n=w.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function Ry(e,t){t===void 0&&(t=[e]);const n=w.useRef(e);return Fa(()=>{n.current!==e&&(n.current=e)},t),n}function pv(e,t){const n=w.useRef();return w.useMemo(()=>{const r=e(n.current);return n.current=r,r},[...t])}function SS(e){const t=mE(e),n=w.useRef(null),r=w.useCallback(s=>{s!==n.current&&(t==null||t(s,n.current)),n.current=s},[]);return[n,r]}function NS(e){const t=w.useRef();return w.useEffect(()=>{t.current=e},[e]),t.current}let xT={};function gv(e,t){return w.useMemo(()=>{if(t)return t;const n=xT[e]==null?0:xT[e]+1;return xT[e]=n,e+"-"+n},[e,t])}function ase(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];return r.reduce((o,i)=>{const a=Object.entries(i);for(const[c,u]of a){const d=o[c];d!=null&&(o[c]=d+e*u)}return o},{...t})}}const Gm=ase(1),Fy=ase(-1);function bqe(e){return"clientX"in e&&"clientY"in e}function pE(e){if(!e)return!1;const{KeyboardEvent:t}=$o(e.target);return t&&e instanceof t}function xqe(e){if(!e)return!1;const{TouchEvent:t}=$o(e.target);return t&&e instanceof t}function jS(e){if(xqe(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return bqe(e)?{x:e.clientX,y:e.clientY}:null}const Si=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[Si.Translate.toString(e),Si.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+" "+n+"ms "+r}}}),n9="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function yqe(e){return e.matches(n9)?e:e.querySelector(n9)}const vqe={display:"none"};function wqe(e){let{id:t,value:n}=e;return w.createElement("div",{id:t,style:vqe},n)}function Cqe(e){let{id:t,announcement:n,ariaLiveType:r="assertive"}=e;const s={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return w.createElement("div",{id:t,style:s,role:"status","aria-live":r,"aria-atomic":!0},n)}function Sqe(){const[e,t]=w.useState("");return{announce:w.useCallback(r=>{r!=null&&t(r)},[]),announcement:e}}const lse=w.createContext(null);function Nqe(e){const t=w.useContext(lse);w.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function jqe(){const[e]=w.useState(()=>new Set),t=w.useCallback(r=>(e.add(r),()=>e.delete(r)),[e]);return[w.useCallback(r=>{let{type:s,event:o}=r;e.forEach(i=>{var a;return(a=i[s])==null?void 0:a.call(i,o)})},[e]),t]}const Eqe={draggable:`
1302
+ Your scheduled email is ready. The attachments you requested are included for your review.`,Gw=[1,2,3,4,5],dT="09:00",rHe=["daily","weekly","biweekly","monthly"],Ym={emails:[],tenantUserIds:[],orgUserIds:[],groupIds:[]};function fT(e){if(!e)return;if(e instanceof Date){const s=new Date(e.getTime());return Number.isNaN(s.getTime())?void 0:s}const t=String(e).trim(),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(n){const s=Number(n[1]),o=Number(n[2])-1,i=Number(n[3]),a=new Date(s,o,i);return Number.isNaN(a.getTime())?void 0:a}const r=new Date(t);return Number.isNaN(r.getTime())?void 0:r}function sHe(e){const t=r=>Array.isArray(r)?r.filter(s=>typeof s=="string"&&!!s.trim()):[],n=r=>{if(!r||typeof r!="object"||Array.isArray(r))return null;const s=r;return"emails"in s||"tenantUserIds"in s||"orgUserIds"in s||"groupIds"in s?{emails:t(s.emails),tenantUserIds:t(s.tenantUserIds),orgUserIds:t(s.orgUserIds),groupIds:t(s.groupIds)}:null};if(typeof e=="string"){const r=e.trim();if(!r)return{...Ym};if(r.startsWith("{")||r.startsWith("["))try{const o=n(JSON.parse(r));if(o)return o}catch{}const s=r.split(/[,;]/).map(o=>o.trim()).filter(Boolean);return{...Ym,emails:s}}return n(e)??{...Ym}}function oHe(e){return rHe.includes(e)?e:"daily"}function iHe(e,t){var i,a,c,u,d,f,h,m,p,g,b,x,y,v,C,S,N,j,k,T,E;const n=((a=(i=e.reportParams)==null?void 0:i.attachments)==null?void 0:a.map(_=>({type:_.type,visualId:_.visualId,cardType:_.cardType,title:_.title,format:_.format,settings:_.settings||{}})))??[];if(n.length>0)return n;const r=e.reportName||e.dashboardName||e.subject||`${t} Report`,s=(c=e.reportParams)==null?void 0:c.format,o=typeof s=="string"&&["pdf","csv","png"].includes(s.toLowerCase())?s.toLowerCase():"pdf";return[{type:e.reportType==="VISUAL"?"visual":"dashboard",visualId:e.visualId,title:r,format:o,settings:{pageSize:((d=(u=e.reportParams)==null?void 0:u.pdfOptions)==null?void 0:d.pageSize)||"letter",orientation:((h=(f=e.reportParams)==null?void 0:f.pdfOptions)==null?void 0:h.orientation)||"portrait",includeFilters:((p=(m=e.reportParams)==null?void 0:m.pdfOptions)==null?void 0:p.includeFilters)??!0,includeTimestamp:((b=(g=e.reportParams)==null?void 0:g.pdfOptions)==null?void 0:b.includeTimestamp)??!0,delimiter:((y=(x=e.reportParams)==null?void 0:x.csvOptions)==null?void 0:y.delimiter)??",",includeHeaders:((C=(v=e.reportParams)==null?void 0:v.csvOptions)==null?void 0:C.includeHeaders)??!0,useFormattedValues:((N=(S=e.reportParams)==null?void 0:S.csvOptions)==null?void 0:N.useFormattedValues)??!0,sheetSelection:(j=e.reportParams)==null?void 0:j.sheetSelection,currentSheetId:(k=e.reportParams)==null?void 0:k.currentSheetId,currentSheetName:(T=e.reportParams)==null?void 0:T.currentSheetName,tablePreferences:(E=e.reportParams)==null?void 0:E.tablePreferences}}]}function Ire({open:e,onOpenChange:t,dashboardId:n,dashboardName:r="Dashboard",preSelectedVisual:s}){const[o,i]=w.useState("schedule"),[a,c]=w.useState({...Ym}),[u,d]=w.useState(`${r} Report`),[f,h]=w.useState(uT),[m,p]=w.useState(s?[s]:[]),[g,b]=w.useState(!1),[x,y]=w.useState(!1),[v,C]=w.useState(!1),[S,N]=w.useState(null),{currentUser:j}=Lo(),k=ee(fe=>fe.dashboard),T=w.useMemo(()=>(k==null?void 0:k.sheets)||[],[k==null?void 0:k.sheets]),E=ee(fe=>fe.selectedSheetId),_=T.find(fe=>fe.id===E),[M,P]=w.useState("daily"),[D,A]=w.useState(dT),[L,$]=w.useState(Intl.DateTimeFormat().resolvedOptions().timeZone),[B,V]=w.useState(Gw),[R,U]=w.useState(!0),[O,I]=w.useState(new Date),[W,X]=w.useState(!0),[Z,H]=w.useState(),{schedules:K,isLoading:z,createSchedule:q,updateSchedule:Y,deleteSchedule:G,isSubmitting:J,deletingId:ne,updatingId:be,refetch:te}=nHe({enabled:e}),ce=!!S,se=J||S!==null&&be===S;w.useEffect(()=>{if(e&&!x){if(j){const fe={...Ym};j.type==="tenant"&&j.id?fe.tenantUserIds=[j.id]:j.type==="organization"&&j.id&&(fe.orgUserIds=[j.id]),c(fe)}if(s)p([s]);else if(k&&_){const fe={type:"dashboard",title:T.length>1?`${k.title} (${_.title})`:`${k.title} (All Sheets)`,format:"pdf",settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0,sheetSelection:T.length>1?"current":"all",currentSheetId:T.length>1?_.id:void 0,currentSheetName:T.length>1?_.title:void 0}};p([fe])}else if(k){const fe={type:"dashboard",title:`${k.title} (All Sheets)`,format:"pdf",settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0,sheetSelection:"all"}};p([fe])}y(!0)}},[e,j,k,_,T,x,s]),w.useEffect(()=>{e||(y(!1),C(!1),N(null),i("schedule"))},[e]);const ue=fe=>{p(fe),b(!1)},Re=fe=>{p(m.filter((Oe,ye)=>ye!==fe))},je=(fe,Oe)=>{const ye=[...m];ye[fe]=Oe,p(ye)},ke=()=>{c({...Ym}),d(`${r} Report`),h(uT),p([]),P("daily"),A(dT),$(Intl.DateTimeFormat().resolvedOptions().timeZone),V(Gw),U(!0),I(new Date),X(!0),H(void 0),N(null)},me=fe=>{const Oe=oHe(fe.frequency),ye=Array.isArray(fe.weekdays)?fe.weekdays:void 0,Ce=!!(ye!=null&&ye.length),$e=fT(fe.startDate),ze=!!$e;c(sHe(fe.recipients)),d(fe.subject||`${r} Report`),h(typeof fe.message=="string"&&fe.message.length>0?fe.message:uT),p(iHe(fe,r)),P(Oe),A(fe.time||dT),$(fe.timezone||Intl.DateTimeFormat().resolvedOptions().timeZone),V(ye&&ye.length>0?ye:Gw),U(Ce),I($e||fT(fe.nextRun)||new Date),X(ze),H(fT(fe.endDate)),N(fe.id),C(!!(fe.subject||fe.message)),i("schedule")},Me=()=>{ke(),i("active")},Se=async()=>{const fe={recipients:a,subject:u,message:f,frequency:M,time:D,timezone:L,weekdays:M==="weekly"&&R?B:void 0,startDate:W?ot.format(O,"yyyy-MM-dd"):void 0,endDate:Z?ot.format(Z,"yyyy-MM-dd"):void 0,reportParams:{attachments:m.map(Oe=>({type:Oe.type,visualId:Oe.visualId,cardType:Oe.cardType,title:Oe.title,format:Oe.format,settings:Oe.settings}))}};try{S?(await Y(S,fe),N(null)):(await q(fe),ke()),i("active")}catch(Oe){console.error("Failed to save schedule:",Oe)}},ie=async fe=>{try{await G(fe)}catch(Oe){console.error("Failed to delete schedule:",Oe)}},Ne=(a.emails.length>0||a.tenantUserIds.length>0||a.orgUserIds.length>0||a.groupIds.length>0)&&u&&m.length>0,de=fe=>{fe||y(!1),t(fe)};return l.jsxs(l.Fragment,{children:[l.jsx(zr,{open:e,onOpenChange:de,children:l.jsxs(Tr,{className:"max-h-[90vh] max-w-2xl",children:[l.jsxs(_r,{children:[l.jsx(Ir,{children:"Schedule Export"}),l.jsx(ss,{className:"sr-only",children:"Create and manage scheduled exports for your dashboard"})]}),l.jsxs(As,{value:o,onValueChange:fe=>i(fe),className:"w-full",children:[l.jsxs(ys,{className:"grid w-full grid-cols-2",children:[l.jsxs(on,{value:"schedule",className:"flex items-center gap-2",children:[l.jsx($r,{className:"h-4 w-4"}),"Schedule"]}),l.jsxs(on,{value:"active",className:"flex items-center gap-2",children:[l.jsx(UA,{className:"h-4 w-4"}),"Active Schedules",K&&K.length>0&&l.jsx(Xe,{variant:"secondary",className:"ml-1 h-5 px-1",children:K.length})]})]}),l.jsxs(sr,{value:"schedule",className:"mt-4 max-h-[calc(80vh-200px)] space-y-3 overflow-y-auto pr-1",children:[l.jsxs("div",{className:"space-y-3 rounded-md border bg-muted/20 p-3",children:[l.jsxs("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"date",className:"text-xs text-muted-foreground",children:"First occurrence"}),l.jsxs(Gr,{modal:!0,children:[l.jsx(Kr,{asChild:!0,children:l.jsxs(re,{variant:"outline",className:Q("w-full justify-start text-left font-normal",!O&&"text-muted-foreground"),children:[l.jsx(js,{className:"mr-2 h-4 w-4 shrink-0"}),O?ot.format(O,"PPP"):"Pick a date"]})}),l.jsx(Zr,{className:"z-[51] w-auto p-0",align:"start",children:l.jsx(Nx,{mode:"single",selected:O,onSelect:fe=>{fe&&(I(fe),X(!0))},disabled:fe=>fe<new Date(new Date().setHours(0,0,0,0)),initialFocus:!0})})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"time",className:"text-xs text-muted-foreground",children:"Time"}),l.jsx(UUe,{value:D,onChange:A})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"timezone",className:"text-xs text-muted-foreground",children:"Timezone"}),l.jsx(BUe,{value:L,onChange:$})]})]}),l.jsxs("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"frequency",className:"text-xs text-muted-foreground",children:"Repeats"}),l.jsxs(pt,{value:M,onValueChange:fe=>{const Oe=fe;Oe==="weekly"&&M!=="weekly"&&(U(!0),B.length||V(Gw)),P(Oe)},children:[l.jsx(ft,{children:l.jsx(gt,{})}),l.jsxs(ht,{children:[l.jsx(Ie,{className:"hover:bg-muted",value:"daily",children:"Daily"}),l.jsx(Ie,{className:"hover:bg-muted",value:"weekly",children:"Weekly"}),l.jsx(Ie,{className:"hover:bg-muted",value:"biweekly",children:"Biweekly"}),l.jsx(Ie,{className:"hover:bg-muted",value:"monthly",children:"Monthly"})]})]}),M==="weekly"&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{className:"text-xs text-muted-foreground",children:"On days"}),l.jsx(HUe,{value:B,onChange:fe=>{V(fe),U(!0)}})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"end-date",className:"text-xs text-muted-foreground",children:"End date (optional)"}),l.jsxs(Gr,{modal:!0,children:[l.jsx(Kr,{asChild:!0,children:l.jsxs(re,{variant:"outline",className:Q("w-full justify-start text-left font-normal",!Z&&"text-muted-foreground"),children:[l.jsx(js,{className:"mr-2 h-4 w-4"}),Z?ot.format(Z,"PPP"):"No end date"]})}),l.jsx(Zr,{className:"z-[51] w-auto p-0",align:"start",children:l.jsx(Nx,{mode:"single",selected:Z,onSelect:H,disabled:fe=>fe<=O,initialFocus:!0})})]})]})]})]}),l.jsx("div",{className:"space-y-1.5",children:l.jsx(MUe,{value:a,onChange:c,triggerAccessory:l.jsx(re,{type:"button",variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>b(!0),title:"Select attachments","aria-label":"Select attachments",children:l.jsx(qA,{className:"h-4 w-4"})})})}),l.jsx("div",{className:"space-y-1.5",children:m.length>0?l.jsx(VUe,{attachments:m,onRemove:Re,onUpdate:je}):l.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-xs text-muted-foreground",children:"No attachments selected"})}),l.jsx(Vs,{className:"my-1"}),l.jsxs(oo,{open:v,onOpenChange:C,children:[l.jsx(io,{asChild:!0,children:l.jsxs(re,{variant:"ghost",className:"h-8 w-full justify-between px-2 text-left text-muted-foreground hover:text-foreground",children:["Email Content",l.jsx(pr,{className:Q("h-4 w-4 transition-transform",v&&"rotate-180")})]})}),l.jsxs(ao,{className:"mt-1.5 space-y-3 rounded-md border p-3",children:[l.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional. If unchanged, the default subject and message are used."}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"subject",children:"Subject"}),l.jsx(lt,{id:"subject",value:u,onChange:fe=>d(fe.target.value),placeholder:"Enter email subject"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"message",children:"Message"}),l.jsx(yi,{className:"ring-inset focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",id:"message",value:f,onChange:fe=>h(fe.target.value),placeholder:"Enter email message",rows:4})]})]})]})]}),l.jsx(sr,{value:"active",className:"mt-4 max-h-[calc(80vh-200px)] overflow-y-auto",children:K&&K.length>0?l.jsx(XUe,{schedules:K,onEdit:me,onDelete:ie,isDeleting:ne,isUpdating:be,isLoading:z,onRefresh:te}):l.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[l.jsx(Yu,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),l.jsx("p",{className:"text-sm font-medium",children:"No active schedules"}),l.jsx("p",{className:"mt-1 text-xs",children:'Switch to the "Schedule" tab to add your first schedule'})]})})]}),o==="schedule"&&l.jsxs(Ds,{className:"mt-1",children:[l.jsx(re,{variant:"outline",onClick:()=>ce?Me():de(!1),disabled:se,children:ce?"Cancel Edit":"Cancel"}),l.jsx(re,{onClick:Se,disabled:!Ne||se,children:se?l.jsx(l.Fragment,{children:ce?"Saving...":"Scheduling..."}):l.jsxs(l.Fragment,{children:[l.jsx(KA,{className:"mr-2 h-4 w-4"}),ce?"Save Changes":"Schedule"]})})]})]})}),g&&l.jsx($Ue,{open:g,onOpenChange:b,dashboardId:n,onSelect:ue,existingAttachments:m})]})}const hT="/api";function aHe(e){const t=e.replace(/\/+$/,"");if(!t||t===hT)return"/";if(t.endsWith(hT)){const n=t.slice(0,-hT.length);return n?`${n}/`:"/"}return`${t}/`}function lHe(e){if(!e)return null;try{const t=new URL(e),n=t.hostname.startsWith("api.")?t.hostname.slice(4):t.hostname,r=`${t.protocol}//${n}${t.port?`:${t.port}`:""}`;return new URL(aHe(t.pathname),r).toString()}catch{return null}}function cHe({apiServiceUrl:e,dashboardId:t,cardId:n,params:r}){if(!t||!n)return null;const s=lHe(e);if(!s)return null;const o=new URL(`view/dashboard/${encodeURIComponent(t)}/visual/${encodeURIComponent(n)}`,s);return r&&(o.search=r.toString()),o.toString()}function UM(e){if(Array.isArray(e))return e.map(t=>UM(t)).join(", ");if(e==null)return"--";if(typeof e=="string")return e;if(typeof e=="object")try{return JSON.stringify(e)}catch{return"[object]"}return String(e)}function uHe(e){return e.split(/[_\s-]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}function dHe(e){const t=e.unit,n=r=>`${t}${r===1?"":"s"}`;return e.mode==="last"?`Last ${e.n} ${n(e.n)} (relative)`:e.mode==="this"?`This ${t}${e.toDate?" to date":""} (relative)`:e.mode==="previous"?`Previous ${t} (relative)`:`Between ${e.from} and ${e.to} ${n(Math.max(e.from,e.to))} ago (relative)`}function fHe(e,t){if(!e||typeof e!="object"||Array.isArray(e)){const f=UM(e);return{key:`filter_${t+1}`,value:f,summary:f}}const n=e,r=[n.name,n.field,n.fieldName,n.column,n.id].find(f=>typeof f=="string"&&f.trim().length>0),s=[n.operation,n.operator].find(f=>typeof f=="string"&&f.trim().length>0),o=n.relativeMeta,a=[o&&typeof o=="object"?dHe(o):void 0,n.values,n.value,n.selectedValues].find(f=>f!==void 0),c=r||`filter_${t+1}`,u=UM(a),d=s?`${c} ${s} ${u}`:`${c} = ${u}`;return{key:c,value:s?`${s} ${u}`:u,summary:d}}function hHe(e){var n;if(!e||e.type!=="dashboard_metric")return[];const t=(n=e.executionSnapshot.filterContext)==null?void 0:n.active_filters;return Array.isArray(t)?t.map((r,s)=>fHe(r,s)):[]}function mT(e){const t=e.trim().toLowerCase();return t==="day"?"Daily":t==="week"?"Weekly":t==="month"?"Monthly":t==="quarter"?"Quarterly":t==="year"?"Yearly":uHe(e)}function pT(e){if(!e||e.type!=="dashboard_metric")return"--";const t=e.executionSnapshot.queryConfig,n=t.granularity;if(typeof n=="string"&&n.trim().length>0)return mT(n);const r=t.trendlineGranularity;if(typeof r=="string"&&r.trim().length>0)return mT(r);const s=t.groupByColumns;if(Array.isArray(s))for(const o of s){if(!o||typeof o!="object"||Array.isArray(o))continue;const i=o.granularity;if(typeof i=="string"&&i.trim().length>0)return mT(i)}return"--"}function mHe(e){return e?e.type==="saved_metric"?e.title||e.visualId:e.title||e.cardId:"Select a metric source"}function pHe(e){return e===0?"Sunday":e===1?"Monday":e===void 0?"--":String(e)}function gHe(e,t){if(typeof e!="number"||!Number.isFinite(e))return"--";const n=Oa(t==null?void 0:t.format);return n!=null&&n.type&&n.type!=="auto"?kn(e,n.type,n):kn(e,"number",{maximumFractionDigits:Math.abs(e)>=100?0:2})}function bHe({source:e,currentValue:t,timezone:n,connectionName:r,dashboardName:s,expanded:o,onToggleExpanded:i}){const a=w.useMemo(()=>hHe(e),[e]),c=w.useMemo(()=>a.length===0?"No active filters":a.slice(0,2).map(m=>m.summary).join(" · "),[a]),u=(e==null?void 0:e.type)==="dashboard_metric"?e.executionSnapshot.calendarContext:void 0,d=(e==null?void 0:e.type)==="dashboard_metric"?`${pT(e)} · ${(u==null?void 0:u.tz)||n} · ${r||"Unknown connection"}`:`${e?"Saved metric source":"No metric selected"} · ${n}`,f=(e==null?void 0:e.type)==="dashboard_metric"?"Dashboard card":"Saved metric",h=gHe(t,e);return l.jsxs(xi,{className:"overflow-hidden border-border/70 bg-gradient-to-b from-background to-muted/20 shadow-sm",children:[l.jsxs(Na,{className:"space-y-3 p-4 pb-3",children:[l.jsxs("div",{className:"flex items-start justify-between gap-3",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Watch Context"}),l.jsx("p",{className:"text-base font-semibold leading-tight text-foreground",children:mHe(e)})]}),l.jsx(Xe,{variant:"secondary",className:"shrink-0 border border-border/60",children:f})]}),l.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[l.jsxs("div",{className:"rounded-md border bg-background/80 px-3 py-2",children:[l.jsx("p",{className:"text-xs text-muted-foreground",children:"Current value"}),l.jsx("p",{className:"text-xl font-semibold tracking-tight text-foreground",children:h})]}),l.jsxs("div",{className:"rounded-md border bg-background/80 px-3 py-2",children:[l.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters"}),l.jsx("p",{className:"truncate text-sm text-foreground",title:c,children:c})]})]}),l.jsxs("div",{className:"flex flex-wrap gap-2",children:[l.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border bg-background px-2.5 py-1 text-xs text-muted-foreground",children:[l.jsx(p0,{className:"h-3.5 w-3.5"}),pT(e)]}),l.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border bg-background px-2.5 py-1 text-xs text-muted-foreground",children:[l.jsx(IU,{className:"h-3.5 w-3.5"}),(u==null?void 0:u.tz)||n]}),l.jsxs("span",{className:"inline-flex max-w-full items-center gap-1 rounded-full border bg-background px-2.5 py-1 text-xs text-muted-foreground",title:d,children:[l.jsx(pl,{className:"h-3.5 w-3.5"}),l.jsx("span",{className:"truncate",children:r||"Unknown connection"})]})]})]}),(e==null?void 0:e.type)==="dashboard_metric"?l.jsxs(Ea,{className:"space-y-3 px-4 pb-4 pt-0",children:[l.jsx(re,{type:"button",variant:"outline",size:"sm",className:"h-8 rounded-full px-3 text-xs",onClick:i,children:o?l.jsxs(l.Fragment,{children:[l.jsx(Mf,{className:"mr-1 h-3.5 w-3.5"}),"Hide details"]}):l.jsxs(l.Fragment,{children:[l.jsx(pr,{className:"mr-1 h-3.5 w-3.5"}),"View details"]})}),o?l.jsxs("div",{className:"space-y-3 rounded-md border bg-background/90 p-3 text-xs",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"inline-flex items-center gap-1 text-foreground",children:[l.jsx(Ic,{className:"h-3.5 w-3.5"}),l.jsx("p",{className:"font-semibold",children:"Active filters"})]}),a.length===0?l.jsx("p",{className:"text-muted-foreground",children:"No active filters"}):l.jsx("div",{className:"space-y-1.5",children:a.map((m,p)=>l.jsxs("div",{className:"grid grid-cols-[minmax(0,150px)_1fr] gap-2 rounded-sm border bg-muted/20 px-2 py-1.5",children:[l.jsx("p",{className:"truncate font-medium text-foreground",children:m.key}),l.jsx("p",{className:"truncate text-muted-foreground",children:m.value})]},`${m.key}-${p}`))})]}),l.jsxs("dl",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Aggregation"}),l.jsx("dd",{className:"font-medium text-foreground",children:pT(e)})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Timezone"}),l.jsx("dd",{className:"font-medium text-foreground",children:(u==null?void 0:u.tz)||n})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Week starts"}),l.jsx("dd",{className:"font-medium text-foreground",children:pHe(u==null?void 0:u.weekStart)})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Connection"}),l.jsx("dd",{className:"font-medium text-foreground",children:r||e.executionSnapshot.connectionId})]}),l.jsxs("div",{className:"space-y-0.5 sm:col-span-2",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Dashboard"}),l.jsx("dd",{className:"font-medium text-foreground",children:s||e.dashboardId})]})]}),l.jsx("div",{className:"rounded-md border bg-muted/30 px-3 py-2 text-muted-foreground",children:"This alert evaluates against a frozen snapshot of the card configuration."})]}):null]}):null]})}function xHe({candidates:e,selected:t,onToggle:n}){return e.length?l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(r=>l.jsx(Xe,{variant:t.includes(r.id)?"default":"outline",className:`cursor-pointer select-none ${t.includes(r.id),""}`,onClick:()=>n(r.id),children:r.label},r.id))}):l.jsx("p",{className:"text-xs text-muted-foreground",children:"No driver suggestions available for this signal."})}function yHe({wizard:e}){var o;const{state:t}=e,[n,r]=w.useState(!1);if(t.prefillLoading)return l.jsx("div",{className:"flex items-center justify-center py-12",children:l.jsxs("div",{className:"flex flex-col items-center gap-3",children:[l.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading signal context..."})]})});if(t.prefillError)return l.jsx("div",{className:"rounded border border-destructive/50 bg-destructive/10 p-4",children:l.jsx("p",{className:"text-sm text-destructive",children:t.prefillError})});if(!t.prefillData)return l.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No signal context available."});const{prefillData:s}=t;return l.jsxs("div",{className:"flex flex-col gap-5",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-semibold",children:"What should Semaphor watch?"}),l.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Start with the business change you care about, then add the context your team will need to investigate it quickly."})]}),l.jsxs("div",{className:"space-y-3",children:[l.jsx(bHe,{source:s.source,currentValue:s.currentValue,timezone:((o=s.calendarContext)==null?void 0:o.tz)??Intl.DateTimeFormat().resolvedOptions().timeZone,connectionName:s.connectionName??void 0,dashboardName:s.dashboardName??void 0,expanded:n,onToggleExpanded:()=>r(i=>!i)}),s.snapshotWarning&&s.snapshotWarning!=="invalid"&&l.jsx("p",{className:"text-xs text-amber-700",children:s.snapshotWarning==="stale"?"Snapshot is older than expected. Values may not reflect the latest data.":"Execution snapshot not available."})]}),s.driverCandidates.length>0&&l.jsxs("div",{children:[l.jsx("p",{className:"mb-2 text-sm font-medium",children:"Contributing factors"}),l.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"Select insights to explain what changed."}),l.jsx(xHe,{candidates:s.driverCandidates,selected:t.selectedDrivers,onToggle:e.toggleDriver})]}),l.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[l.jsx("span",{className:"text-xs text-muted-foreground",children:"Step 1 of 3"}),l.jsx(re,{onClick:e.nextStep,size:"sm",children:"Continue"})]})]})}const nx={low_noise:{label:"Low Noise",description:"Only major changes surface",relativeChangeThreshold:15,consecutiveCount:2},standard:{label:"Standard",description:"Balanced sensitivity",relativeChangeThreshold:10,consecutiveCount:1},early_warning:{label:"Early Warning",description:"Catches smaller changes sooner",relativeChangeThreshold:5,consecutiveCount:1}};function UO(e){const t=nx[e];return{sensitivityPreset:e,threshold:t.relativeChangeThreshold,consecutiveCount:t.consecutiveCount,operator:"pct_change_gt"}}function vHe({selected:e,onSelect:t,customValues:n,onCustomize:r}){const[s,o]=w.useState(!1),i=["low_noise","standard","early_warning"];return l.jsxs("div",{className:"space-y-4",children:[l.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:i.map(a=>{const c=nx[a];return l.jsxs("div",{className:`rounded border p-3 ${e===a?"border-primary bg-primary/5":""}`,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Xe,{variant:e===a?"default":"outline",className:"cursor-pointer",onClick:()=>{t(a),o(!1)},children:c.label}),a==="standard"&&l.jsx(Xe,{variant:"secondary",className:"text-[10px]",children:"Recommended"})]}),l.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:c.description}),l.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:[c.relativeChangeThreshold,"% move • ",c.consecutiveCount," check",c.consecutiveCount===1?"":"s"]}),l.jsx("button",{type:"button",className:"mt-2 text-xs font-medium text-primary",onClick:()=>{t(a),o(!0)},children:"Customize"})]},a)})}),s&&e&&l.jsxs("div",{className:"space-y-3 rounded border p-4",children:[l.jsxs("h4",{className:"text-sm font-medium",children:["Customize ",nx[e].label]}),l.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[l.jsxs("div",{children:[l.jsx("label",{className:"text-xs text-muted-foreground",children:"Threshold (%)"}),l.jsx(lt,{type:"number",value:(n==null?void 0:n.threshold)??nx[e].relativeChangeThreshold,onChange:a=>r==null?void 0:r({threshold:parseInt(a.target.value,10)||0}),className:"mt-1"})]}),l.jsxs("div",{children:[l.jsx("label",{className:"text-xs text-muted-foreground",children:"Consecutive checks"}),l.jsx(lt,{type:"number",min:1,value:(n==null?void 0:n.consecutiveCount)??nx[e].consecutiveCount,onChange:a=>r==null?void 0:r({consecutiveCount:parseInt(a.target.value,10)||1}),className:"mt-1"})]})]})]})]})}function wHe({wizard:e}){const{draftJobConfig:t}=e.state;return l.jsxs("div",{className:"flex flex-col gap-5",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-semibold",children:"Signal Sensitivity"}),l.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Choose how quickly Semaphor should surface meaningful changes in this signal."})]}),l.jsx("div",{className:"rounded border p-4",children:l.jsx(vHe,{selected:t.sensitivityPreset,onSelect:n=>e.setSensitivity(n),customValues:{threshold:t.threshold,consecutiveCount:t.consecutiveCount},onCustomize:n=>e.updateJobConfig(n)})}),l.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[l.jsx(re,{variant:"outline",size:"sm",onClick:e.prevStep,children:"Back"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Step 2 of 3"}),l.jsx(re,{size:"sm",onClick:e.nextStep,children:"Continue"})]})]})}var dE="Switch",[CHe]=us(dE),[SHe,NHe]=CHe(dE),Mre=F.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:s,defaultChecked:o,required:i,disabled:a,value:c="on",onCheckedChange:u,form:d,...f}=e,[h,m]=F.useState(null),p=Et(t,v=>m(v)),g=F.useRef(!1),b=h?d||!!h.closest("form"):!0,[x,y]=Ms({prop:s,defaultProp:o??!1,onChange:u,caller:dE});return l.jsxs(SHe,{scope:n,checked:x,disabled:a,children:[l.jsx(at.button,{type:"button",role:"switch","aria-checked":x,"aria-required":i,"data-state":Fre(x),"data-disabled":a?"":void 0,disabled:a,value:c,...f,ref:p,onClick:Ye(e.onClick,v=>{y(C=>!C),b&&(g.current=v.isPropagationStopped(),g.current||v.stopPropagation())})}),b&&l.jsx(Rre,{control:h,bubbles:!g.current,name:r,value:c,checked:x,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});Mre.displayName=dE;var Dre="SwitchThumb",Are=F.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,s=NHe(Dre,n);return l.jsx(at.span,{"data-state":Fre(s.checked),"data-disabled":s.disabled?"":void 0,...r,ref:t})});Are.displayName=Dre;var jHe="SwitchBubbleInput",Rre=F.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...s},o)=>{const i=F.useRef(null),a=Et(i,o),c=T0(n),u=y0(t);return F.useEffect(()=>{const d=i.current;if(!d)return;const f=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(f,"checked").set;if(c!==n&&m){const p=new Event("click",{bubbles:r});m.call(d,n),d.dispatchEvent(p)}},[c,n,r]),l.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...s,tabIndex:-1,ref:a,style:{...s.style,...u,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Rre.displayName=jHe;function Fre(e){return e?"checked":"unchecked"}var HO=Mre,Pre=Are;const EHe=Ki("peer inline-flex shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/20 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",{variants:{size:{default:"h-6 w-11",sm:"h-[22px] w-[36px]",xs:"h-4 w-7"}},defaultVariants:{size:"default"}}),kHe=Ki("pointer-events-none block rounded-full bg-background shadow-sm ring-0 transition-transform data-[state=unchecked]:translate-x-0",{variants:{size:{default:"h-5 w-5 data-[state=checked]:translate-x-5",sm:"size-4 data-[state=checked]:translate-x-4",xs:"h-3 w-3 data-[state=checked]:translate-x-3"}},defaultVariants:{size:"default"}}),gh=F.forwardRef(({className:e,size:t,...n},r)=>l.jsx(HO,{className:Q(EHe({size:t,className:e})),...n,ref:r,children:l.jsx(Pre,{className:Q(kHe({size:t}))})}));gh.displayName=HO.displayName;const THe=[{value:"concise",label:"Concise",description:"Key facts only"},{value:"balanced",label:"Balanced",description:"Summary + context"},{value:"detailed",label:"Detailed",description:"Full analysis"}];function _He({value:e,onChange:t}){return l.jsxs("div",{children:[l.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Format profile"}),l.jsx("div",{className:"mt-1 flex gap-2",children:THe.map(n=>l.jsx(Xe,{variant:e===n.value?"default":"outline",className:"cursor-pointer px-3 py-1.5",onClick:()=>t(n.value),children:l.jsx("span",{className:"text-xs",children:n.label})},n.value))})]})}const IHe={EMAIL:{label:"Email",icon:"✉️",description:"Email notifications"},SLACK:{label:"Slack",icon:"💬",description:"Slack messages"},TELEGRAM:{label:"Telegram",icon:"📱",description:"Telegram messages"},WEBHOOK:{label:"Webhook",icon:"🔗",description:"HTTP webhook calls"},IN_APP:{label:"In-App",icon:"🔔",description:"Dashboard notifications"}},MHe=["EMAIL","SLACK","TELEGRAM","WEBHOOK","IN_APP"];function DHe({enabledChannels:e,channelConfigs:t,onChannelToggle:n,onConfigChange:r}){const[s,o]=w.useState(null);return l.jsx("div",{className:"space-y-3",children:MHe.map(i=>{var f;const a=IHe[i],c=e.includes(i),u=t[i]??{formatProfile:"balanced"},d=s===i;return l.jsxs("div",{className:"rounded-lg border p-3",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(gh,{checked:c,onCheckedChange:h=>n(i,!!h)}),l.jsx("span",{className:"text-base",children:a.icon}),l.jsxs("div",{children:[l.jsx("div",{className:"text-sm font-medium text-foreground",children:a.label}),l.jsx("div",{className:"text-xs text-muted-foreground",children:a.description})]})]}),c&&l.jsx(re,{variant:"ghost",size:"sm",className:"text-xs",onClick:()=>o(d?null:i),children:d?"Collapse":"Customize"})]}),c&&d&&l.jsxs("div",{className:"mt-3 space-y-3 border-t pt-3",children:[l.jsx(_He,{value:u.formatProfile,onChange:h=>r(i,{...u,formatProfile:h})}),l.jsxs("div",{children:[l.jsx("label",{className:"text-xs text-muted-foreground",children:"Subject override (optional)"}),l.jsx(lt,{value:u.subjectOverride??"",onChange:h=>r(i,{...u,subjectOverride:h.target.value||void 0}),placeholder:"Auto-generated",className:"mt-1 text-sm"})]}),l.jsxs("div",{children:[l.jsx("label",{className:"text-xs text-muted-foreground",children:"Summary override (optional)"}),l.jsx(yi,{value:u.summaryOverride??"",onChange:h=>r(i,{...u,summaryOverride:h.target.value||void 0}),placeholder:"Auto-generated summary",className:"mt-1 text-sm",rows:2})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(gh,{checked:u.actionBlockVisible!==!1,onCheckedChange:h=>r(i,{...u,actionBlockVisible:!!h})}),l.jsx("label",{className:"text-xs",children:"Show action block"})]}),i==="WEBHOOK"&&l.jsxs("div",{children:[l.jsx("label",{className:"text-xs text-muted-foreground",children:"Webhook URL"}),l.jsx(lt,{value:((f=u.webhookConfig)==null?void 0:f.url)??"",onChange:h=>{var m,p;return r(i,{...u,webhookConfig:{url:h.target.value,method:((m=u.webhookConfig)==null?void 0:m.method)??"POST",headers:((p=u.webhookConfig)==null?void 0:p.headers)??{}}})},placeholder:"https://...",className:"mt-1 text-sm"})]})]})]},i)})})}const AHe={EMAIL:"Email",SLACK:"Slack",TELEGRAM:"Telegram",WEBHOOK:"Webhook",IN_APP:"In-App"};function RHe({ruleId:e,metricName:t,channels:n,onClose:r}){const s=n.map(o=>AHe[o]??o).join(", ");return l.jsxs("div",{className:"flex flex-col items-center justify-center space-y-4 p-8",children:[l.jsx("div",{className:"flex h-16 w-16 items-center justify-center rounded-full bg-green-100 text-3xl",children:"✓"}),l.jsx("h2",{className:"text-xl font-bold",children:"Semaphor Is Watching This Signal"}),l.jsxs("p",{className:"max-w-md text-sm leading-6 text-muted-foreground",children:[l.jsx("span",{className:"font-medium text-foreground",children:t})," is now being watched. Semaphor will surface meaningful changes via ",s,"."]}),l.jsx("div",{className:"w-full max-w-sm space-y-2 rounded-lg bg-muted p-4 text-sm",children:l.jsxs("div",{children:[l.jsx("span",{className:"font-medium",children:"Where it surfaces:"})," ",s]})}),l.jsx(re,{onClick:r,variant:"outline",children:"Close"})]})}function Ore(e,t){switch(e){case"pct_change_gt":return`${t}% above the previous check`;case"pct_change_lt":return`${Math.abs(t)}% below the previous check`;case"gt":return`Value above ${t}`;case"gte":return`Value at or above ${t}`;case"lt":return`Value below ${t}`;case"lte":return`Value at or below ${t}`;case"eq":return`Value equal to ${t}`;case"neq":return`Value different from ${t}`;default:return`${e} ${t}`}}function FHe(e){switch(e){case"*/5 * * * *":return"Every 5 minutes";case"*/6 * * * *":return"Every 6 minutes";case"*/10 * * * *":return"Every 10 minutes";case"*/12 * * * *":return"Every 12 minutes";case"*/15 * * * *":return"Every 15 minutes";case"*/20 * * * *":return"Every 20 minutes";case"*/30 * * * *":return"Every 30 minutes";case"0 * * * *":return"Hourly";case"0 */2 * * *":return"Every 2 hours";case"0 */3 * * *":return"Every 3 hours";case"0 */4 * * *":return"Every 4 hours";case"0 */6 * * *":return"Every 6 hours";case"0 */8 * * *":return"Every 8 hours";case"0 */12 * * *":return"Every 12 hours";case"0 9 * * *":return"Daily";case"0 9 * * 1":return"Weekly";case"0 9 1 * *":return"Monthly";case"0 9 1 1 *":return"Yearly";default:return e}}function PHe(e){const t=[],n=new Set,r=(s,o)=>{n.has(s)||(n.add(s),t.push(o))};return e.orgUserId&&r(`user:${e.orgUserId}`,{type:"user",userId:e.orgUserId}),e.endUserId&&r(`tenant_user:${e.endUserId}`,{type:"tenant_user",tenantUserId:e.endUserId}),e.orgUserEmail&&r(`email:${e.orgUserEmail.toLowerCase()}`,{type:"email",address:e.orgUserEmail}),e.endUserEmail&&r(`email:${e.endUserEmail.toLowerCase()}`,{type:"email",address:e.endUserEmail}),t}function Lre(e,t){const n=e.recipients&&e.recipients.length>0?e.recipients:PHe(t);return{channels:e.channels,recipients:n,...e.channelConfigs?{channelConfigs:e.channelConfigs}:{}}}function OHe(e,t){if(t.length===0)return;const n=e.driverCandidates.filter(r=>t.includes(r.id));if(n.length!==0)return n.map((r,s)=>({kind:"related_metric",outputAs:`driver_${s+1}`,config:{referenceId:r.referenceId,label:r.label,sourceKind:r.sourceKind,provenance:r.provenance,metricType:r.metricType}}))}function HM(e,t,n=[]){const r=OHe(e,n),s=UO(t.sensitivityPreset??"standard");return{kind:"ALERT",source:e.source,...s,...t,...r?{contextSources:r}:{},notifyPolicy:"on_state_change",severity:t.severity??"MEDIUM",operator:t.operator??s.operator,threshold:t.threshold??s.threshold}}function $re(e){return{metricLabel:e.metricLabel,currentValue:e.currentValue,dashboardName:e.dashboardName,connectionName:e.connectionName,driverCandidates:e.driverCandidates}}function LHe(e){try{const t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{value:t}}catch{return null}}function $He(e,t){if(!t)return null;const n=Array.isArray(t.warnings)?t.warnings:void 0;if(e==="EMAIL")return{html:t.rendered,...n?{warnings:n}:{}};if(e==="TELEGRAM")return{text:t.rendered,...n?{warnings:n}:{}};if(t.contentType.includes("json")){const r=LHe(t.rendered);if(r)return n?{...r,warnings:n}:r}return{text:t.rendered,...n?{warnings:n}:{}}}const zHe=[5,6,10,12,15,20,30,60],VHe=[1,2,3,4,6,8,12,24],WM=60,WO=24*WM,BHe=7*WO,UHe=31*WO;function HHe(e){if(!Number.isFinite(e)||e<=5)return"*/5 * * * *";if(e<WM){const t=zHe.find(n=>n>=e)??60;return t===60?"0 * * * *":`*/${t} * * * *`}if(e<=WO){const t=Math.ceil(e/WM),n=VHe.find(r=>r>=t)??24;return n===24?"0 9 * * *":`0 */${n} * * *`}return e<=BHe?"0 9 * * 1":e<=UHe?"0 9 1 * *":"0 9 1 1 *"}function qM(e){return e==="SLACK"?"Slack":"Telegram"}function WHe(e){if(!e)return null;const t=qM(e.channel);return e.error?`${t}: ${e.error}`:e.installed?e.status&&e.status!=="ACTIVE"?`${t} is not active for this workspace yet.`:e.userLinked?null:`Link your ${t} account before starting this watch.`:`${t} is not installed for this workspace yet.`}function qHe({wizard:e,onClose:t}){var I,W,X,Z,H,K,z;const{authToken:n,tokenProps:r}=rt(),{state:s}=e,{createAlert:o,isCreating:i}=DF({enabled:!1}),[a,c]=w.useState(!1),[u,d]=w.useState(null),[f,h]=w.useState(!1),[m,p]=w.useState(null),[g,b]=w.useState({}),[x,y]=w.useState(null),[v,C]=w.useState(null),[S,N]=w.useState(null),j=w.useMemo(()=>Lre(s.draftDeliveryConfig,r),[s.draftDeliveryConfig,r]),T=j.recipients.length>0?null:"No recipient identity was found in this token. Semaphor will fall back to the current signed-in workspace identity when you start watching.",_=s.draftDeliveryConfig.channels.includes("WEBHOOK")&&!((Z=(X=(W=(I=j.channelConfigs)==null?void 0:I.WEBHOOK)==null?void 0:W.webhookConfig)==null?void 0:X.url)!=null&&Z.trim())?"Configure a webhook URL before sending or starting a webhook-based signal watch.":null,M=((K=(H=s.prefillData)==null?void 0:H.calendarContext)==null?void 0:K.tz)??Intl.DateTimeFormat().resolvedOptions().timeZone,P=w.useMemo(()=>s.draftDeliveryConfig.channels.filter(q=>q==="SLACK"||q==="TELEGRAM"),[s.draftDeliveryConfig.channels]),D=w.useMemo(()=>(u==null?void 0:u.minCadenceMinutes)??15,[u]),A=w.useMemo(()=>HHe(D),[D]),L=w.useMemo(()=>FHe(A),[A]),$=P.length>0&&P.some(q=>g[q]===void 0),B=w.useMemo(()=>{const q=P.map(Y=>WHe(g[Y])).filter(Y=>!!Y);return q.length>0?q.join(" "):null},[P,g]);w.useEffect(()=>{const q=r==null?void 0:r.apiServiceUrl,Y=n==null?void 0:n.accessToken;if(!q||!Y){d(null),h(!1),p(null);return}let G=!1;return h(!0),p(null),(async()=>{var J;try{const ne=await fetch(`${q}/v1/alerts/quota`,{headers:{Authorization:`Bearer ${Y}`}}),be=await ne.json().catch(()=>({}));if(!ne.ok)throw new Error(be.error??"Unable to load this workspace cadence policy right now.");G||d({minCadenceMinutes:((J=be.quota)==null?void 0:J.minCadenceMinutes)??15})}catch(ne){G||(d(null),p(ne instanceof Error?ne.message:"Unable to load this workspace cadence policy right now."))}finally{G||h(!1)}})(),()=>{G=!0}},[n==null?void 0:n.accessToken,r==null?void 0:r.apiServiceUrl]),w.useEffect(()=>{const q=r==null?void 0:r.apiServiceUrl,Y=n==null?void 0:n.accessToken;if(!q||!Y||P.length===0){b({});return}let G=!1;return(async()=>{const J=await Promise.all(P.map(async ne=>{try{const be=await fetch(`${q}/v1/integrations/${ne.toLowerCase()}/status`,{headers:{Authorization:`Bearer ${Y}`}}),te=await be.json().catch(()=>({}));return be.ok?[ne,{channel:ne,installed:!!te.installed,status:te.status,userLinked:!!te.userLinked}]:[ne,{channel:ne,installed:!1,userLinked:!1,error:te.error??`Unable to verify ${qM(ne)} availability`}]}catch(be){return[ne,{channel:ne,installed:!1,userLinked:!1,error:be instanceof Error?be.message:`Unable to verify ${qM(ne)} availability`}]}}));G||b(Object.fromEntries(J))})(),()=>{G=!0}},[n==null?void 0:n.accessToken,P,r==null?void 0:r.apiServiceUrl]);const V=w.useCallback((q,Y)=>{const G=s.draftDeliveryConfig.channels,J=Y?[...G,q]:G.filter(ne=>ne!==q);e.updateDeliveryConfig({channels:J})},[s.draftDeliveryConfig.channels,e]),R=w.useCallback((q,Y)=>{e.updateDeliveryConfig({channelConfigs:{...s.draftDeliveryConfig.channelConfigs,[q]:Y}})},[s.draftDeliveryConfig.channelConfigs,e]),U=w.useCallback(async()=>{const q=r==null?void 0:r.apiServiceUrl,Y=n==null?void 0:n.accessToken;if(!(!q||!Y||!s.prefillData)){c(!0),C(null),N(null);try{if(_)throw new Error(_);const G=HM(s.prefillData,s.draftJobConfig,s.selectedDrivers),J=j,ne=await fetch(`${q}/v1/alerts/wizard/sample-send`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Y}`},body:JSON.stringify({jobConfig:G,deliveryConfig:J,channels:J.channels,metricContext:$re(s.prefillData)})}),be=await ne.json().catch(()=>({})),te=Array.isArray(be.results)?be.results:[],ce=te.filter(ue=>ue.status==="FAILED"),se=te.filter(ue=>ue.status==="SENT");if(!ne.ok)throw ce.length>0?new Error(ce.map(ue=>`${ue.channel??"Channel"}: ${ue.error??"Failed"}`).join("; ")):new Error(be.error||"Preview send failed");if(ce.length>0){const ue=se.length>0?`Preview sent for ${se.length} channel(s).`:null;C(ue),N(ce.map(Re=>`${Re.channel??"Channel"}: ${Re.error??"Failed"}`).join("; "));return}C("Preview sent successfully")}catch(G){N(G instanceof Error?G.message:"Preview send failed")}finally{c(!1)}}},[n,j,s,r,_]),O=w.useCallback(async()=>{if(s.prefillData){N(null);try{if($)throw new Error("Checking Slack and Telegram delivery readiness. Try again in a moment.");if(B)throw new Error(B);if(_)throw new Error(_);const q=HM(s.prefillData,s.draftJobConfig,s.selectedDrivers),Y=j,J=(await o({kind:"ALERT",name:s.prefillData.suggestedName,scheduleExpr:A,timezone:M,jobConfig:q,deliveryConfig:Y})).alert.id;y({ruleId:J})}catch(q){N(q instanceof Error?q.message:"Unable to start watching")}}},[o,B,$,j,A,M,s,_]);return x?l.jsx(RHe,{ruleId:x.ruleId,metricName:((z=s.prefillData)==null?void 0:z.metricLabel)??"Metric",channels:s.draftDeliveryConfig.channels,onClose:t}):l.jsxs("div",{className:"flex flex-col gap-5",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-semibold",children:"Where should this surface?"}),l.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Choose where Semaphor should surface this signal for your team."})]}),l.jsx("div",{className:"rounded border p-4",children:l.jsx(DHe,{enabledChannels:s.draftDeliveryConfig.channels,channelConfigs:s.draftDeliveryConfig.channelConfigs??{},onChannelToggle:V,onConfigChange:R})}),T&&l.jsx("div",{className:"rounded border border-amber-200 bg-amber-50 p-4",children:l.jsx("p",{className:"text-xs text-amber-800",children:T})}),_&&l.jsx("div",{className:"rounded border border-amber-200 bg-amber-50 p-4",children:l.jsx("p",{className:"text-xs text-amber-800",children:_})}),f&&l.jsx("div",{className:"rounded border border-muted bg-muted/30 p-4",children:l.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading workspace cadence policy..."})}),m&&l.jsx("div",{className:"rounded border border-amber-200 bg-amber-50 p-4",children:l.jsxs("p",{className:"text-xs text-amber-800",children:[m," Semaphor will fall back to the default cadence if this check stays unavailable."]})}),$&&l.jsx("div",{className:"rounded border border-muted bg-muted/30 p-4",children:l.jsx("p",{className:"text-xs text-muted-foreground",children:"Checking Slack and Telegram delivery readiness..."})}),B&&l.jsx("div",{className:"rounded border border-amber-200 bg-amber-50 p-4",children:l.jsx("p",{className:"text-xs text-amber-800",children:B})}),S&&l.jsx("div",{className:"rounded border border-destructive/50 bg-destructive/10 p-4",children:l.jsx("p",{className:"text-xs text-destructive",children:S})}),v&&l.jsx("div",{className:"rounded border border-emerald-200 bg-emerald-50 p-4",children:l.jsx("p",{className:"text-xs text-emerald-700",children:v})}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Semaphor will evaluate this signal on the nearest supported workspace cadence:"," ",L,"."]}),l.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[l.jsx(re,{variant:"outline",size:"sm",onClick:e.prevStep,children:"Back"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Step 3 of 3"}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(re,{variant:"outline",size:"sm",onClick:U,disabled:a||s.draftDeliveryConfig.channels.length===0||!!_,children:a?"Sending...":"Send Preview"}),l.jsx(re,{size:"sm",onClick:O,disabled:i||s.draftDeliveryConfig.channels.length===0||!!_||$||!!B,children:i?"Starting...":"Start Watching"})]})]})]})}function YHe({wizard:e,onClose:t}){const{step:n}=e.state;return l.jsxs("div",{className:"flex h-full flex-col",children:[l.jsx("div",{className:"mb-4 flex items-center gap-3",children:[1,2,3].map(r=>l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:`flex h-7 w-7 items-center justify-center rounded-full text-xs font-medium ${r===n?"bg-primary text-primary-foreground":r<n?"bg-primary/20 text-primary":"bg-muted text-muted-foreground"}`,children:r<n?"✓":r}),l.jsx("span",{className:`text-xs ${r===n?"font-medium text-foreground":"text-muted-foreground"}`,children:r===1?"Signal & Intent":r===2?"Signal Sensitivity":"Where It Surfaces"}),r<3&&l.jsx("div",{className:"mx-1 h-px w-6 bg-border"})]},r))}),l.jsxs("div",{className:"flex-1 overflow-y-auto",children:[n===1&&l.jsx(yHe,{wizard:e}),n===2&&l.jsx(wHe,{wizard:e}),n===3&&l.jsx(qHe,{wizard:e,onClose:t})]})]})}function GHe({content:e}){return e?typeof e.html=="string"?l.jsx("div",{className:"prose prose-sm max-w-none rounded border bg-white p-4",dangerouslySetInnerHTML:{__html:e.html}}):l.jsx("p",{className:"text-xs text-muted-foreground",children:"No email preview available."}):l.jsx(rs,{className:"h-64 w-full"})}function KHe({content:e}){if(!e)return l.jsx(rs,{className:"h-64 w-full"});const t=Array.isArray(e.blocks)?e.blocks:[],n=typeof e.text=="string"?e.text:null;return l.jsxs("div",{className:"space-y-2 rounded bg-slate-50 p-4",children:[t.length>0?t.map((r,s)=>{var o,i;return l.jsxs("div",{className:"text-sm",children:[r.type==="header"&&l.jsx("h4",{className:"font-bold",children:String(((o=r.text)==null?void 0:o.text)??"")}),r.type==="section"&&l.jsx("p",{children:String(((i=r.text)==null?void 0:i.text)??"")}),r.type==="divider"&&l.jsx("hr",{className:"my-2"})]},s)}):n&&l.jsx("p",{className:"whitespace-pre-wrap text-sm",children:n}),t.length===0&&!n&&l.jsx("p",{className:"text-xs text-muted-foreground",children:"No Slack preview available."})]})}function ZHe({content:e}){if(!e)return l.jsx(rs,{className:"h-64 w-full"});const t=typeof e.text=="string"?e.text:null;return t?l.jsx("div",{className:"rounded-lg bg-blue-50 p-4",children:l.jsx("p",{className:"whitespace-pre-wrap text-sm",children:t})}):l.jsx("p",{className:"text-xs text-muted-foreground",children:"No Telegram preview available."})}function XHe({content:e}){return e?l.jsx("pre",{className:"overflow-auto rounded bg-gray-900 p-4 text-xs text-gray-100",children:JSON.stringify(e,null,2)}):l.jsx(rs,{className:"h-64 w-full"})}function QHe({content:e}){if(!e)return l.jsx(rs,{className:"h-64 w-full"});const t=typeof e.title=="string"?e.title:"Alert",n=typeof e.body=="string"?e.body:"",r=typeof e.actionUrl=="string"?e.actionUrl:null;return l.jsxs("div",{className:"rounded-lg border p-4",children:[l.jsx("div",{className:"font-semibold text-sm",children:t}),n&&l.jsx("div",{className:"mt-1 text-sm text-muted-foreground",children:n}),r&&l.jsx(re,{variant:"link",className:"mt-2 h-auto p-0 text-xs",children:"View Details →"})]})}function JHe({wizard:e}){const{authToken:t,tokenProps:n}=rt(),{state:r}=e,{draftDeliveryConfig:s,draftJobConfig:o,prefillData:i}=r,[a,c]=w.useState({}),[u,d]=w.useState(""),f=w.useRef(null),h=w.useRef(0),m=s.channels;return w.useEffect(()=>{m.length>0&&!m.includes(u)&&d(m[0])},[m,u]),w.useEffect(()=>{if(!u||!i)return;const p=n==null?void 0:n.apiServiceUrl,g=t==null?void 0:t.accessToken;if(!p||!g)return;f.current&&clearTimeout(f.current);const b=Lre(s,n),x=HM(i,o,r.selectedDrivers),y=h.current+1;return h.current=y,f.current=setTimeout(async()=>{try{const v=await fetch(`${p}/v1/alerts/preview-deliverable`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${g}`},body:JSON.stringify({channels:[u],jobConfig:x,deliveryConfig:b,metricContext:$re(i)})});if(v.ok){const C=await v.json();if(h.current!==y)return;c(S=>{var N;return{...S,[u]:$He(u,(N=C.previews)==null?void 0:N[u])}})}else h.current===y&&c(C=>({...C,[u]:null}))}catch{h.current===y&&c(v=>({...v,[u]:null}))}},300),()=>{f.current&&clearTimeout(f.current)}},[u,t==null?void 0:t.accessToken,s,o,i,r.selectedDrivers,n]),m.length===0?l.jsx("div",{className:"flex h-full flex-col items-center justify-center text-center",children:l.jsx("p",{className:"text-sm text-muted-foreground",children:"Enable a channel to see preview."})}):l.jsxs("div",{className:"flex h-full flex-col",children:[l.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Live Preview"}),l.jsxs(As,{value:u,onValueChange:d,className:"flex-1",children:[l.jsx(ys,{className:"w-full",children:m.map(p=>l.jsx(on,{value:p,className:"text-xs",children:p},p))}),m.map(p=>l.jsxs(sr,{value:p,className:"mt-3 h-[calc(100%-3rem)]",children:[p==="EMAIL"&&l.jsx(GHe,{content:a[p]??null}),p==="SLACK"&&l.jsx(KHe,{content:a[p]??null}),p==="TELEGRAM"&&l.jsx(ZHe,{content:a[p]??null}),p==="WEBHOOK"&&l.jsx(XHe,{content:a[p]??null}),p==="IN_APP"&&l.jsx(QHe,{content:a[p]??null})]},p))]})]})}const eWe="standard";function YM(){return UO(eWe)}function tWe(e,t){switch(t.type){case"START_PREFILL":return{...e,step:1,prefillData:null,prefillLoading:!0,prefillError:null,draftJobConfig:YM(),draftDeliveryConfig:{channels:["EMAIL"]},selectedDrivers:[]};case"RESET_PREFILL":return{...e,step:1,prefillData:null,prefillLoading:!1,prefillError:null,draftJobConfig:YM(),draftDeliveryConfig:{channels:["EMAIL"]},selectedDrivers:[]};case"SET_PREFILL":return{...e,prefillData:t.payload,prefillLoading:!1,prefillError:null,draftJobConfig:{...e.draftJobConfig,source:t.payload.source}};case"SET_PREFILL_ERROR":return{...e,prefillLoading:!1,prefillError:t.error};case"NEXT_STEP":return{...e,step:Math.min(3,e.step+1)};case"PREV_STEP":return{...e,step:Math.max(1,e.step-1)};case"SET_SENSITIVITY":return{...e,draftJobConfig:{...e.draftJobConfig,...UO(t.payload)}};case"TOGGLE_DRIVER":{const n=e.selectedDrivers.includes(t.driverId)?e.selectedDrivers.filter(r=>r!==t.driverId):[...e.selectedDrivers,t.driverId];return{...e,selectedDrivers:n}}case"UPDATE_JOB_CONFIG":return{...e,draftJobConfig:{...e.draftJobConfig,...t.payload}};case"UPDATE_DELIVERY_CONFIG":return{...e,draftDeliveryConfig:{...e.draftDeliveryConfig,...t.payload}};default:return e}}function nWe(e,t){const n=t!=null&&t.format&&(!e.source.format||JSON.stringify(e.source.format)!==JSON.stringify(t.format))?{...e.source,format:t.format}:e.source,r=e.currentValue!==null||typeof(t==null?void 0:t.currentValue)!="number"||!Number.isFinite(t.currentValue)?e.currentValue:t.currentValue;return n===e.source&&r===e.currentValue?e:{...e,source:n,currentValue:r}}const gT=new Map;function zre({cardSnapshot:e}){const{authToken:t,tokenProps:n}=rt(),r=e==null?void 0:e.dashboardId,s=e==null?void 0:e.visualId,o=e==null?void 0:e.cardId,i=e==null?void 0:e.executionSnapshot,a=w.useMemo(()=>!r||!s||!o?null:JSON.stringify({dashboardId:r,visualId:s,cardId:o,executionSnapshot:i}),[o,r,i,s]),c=w.useMemo(()=>a?JSON.parse(a):null,[a]),[u,d]=w.useReducer(tWe,{step:1,prefillData:null,prefillLoading:!0,prefillError:null,draftJobConfig:YM(),draftDeliveryConfig:{channels:["EMAIL"]},selectedDrivers:[]}),f=w.useRef(e),h=w.useRef(null);f.current=e,w.useEffect(()=>{if(!c){h.current=null,d({type:"RESET_PREFILL"});return}const v=n==null?void 0:n.apiServiceUrl,C=t==null?void 0:t.accessToken;if(!v||!C){h.current=null,d({type:"START_PREFILL"});return}const S=`${v}:${a}`;let N=!1;h.current!==S&&(h.current=S,d({type:"START_PREFILL"}));let j=gT.get(S);return j||(j=fetch(`${v}/v1/alerts/wizard/prefill`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C}`},body:JSON.stringify({sourceType:"dashboard_metric",...c})}).then(async k=>{if(!k.ok){const T=await k.json().catch(()=>({}));throw new Error(T.error||"Failed to load wizard data")}return await k.json()}),gT.set(S,j),j.finally(()=>{gT.delete(S)})),j.then(k=>{N||d({type:"SET_PREFILL",payload:nWe(k,f.current)})}).catch(k=>{N||d({type:"SET_PREFILL_ERROR",error:k instanceof Error?k.message:"Failed to load wizard data"})}),()=>{N=!0}},[t==null?void 0:t.accessToken,a,c,n==null?void 0:n.apiServiceUrl]);const m=w.useCallback(()=>d({type:"NEXT_STEP"}),[]),p=w.useCallback(()=>d({type:"PREV_STEP"}),[]),g=w.useCallback(v=>d({type:"TOGGLE_DRIVER",driverId:v}),[]),b=w.useCallback(v=>d({type:"UPDATE_JOB_CONFIG",payload:v}),[]),x=w.useCallback(v=>d({type:"UPDATE_DELIVERY_CONFIG",payload:v}),[]),y=w.useCallback(v=>d({type:"SET_SENSITIVITY",payload:v}),[]);return{state:u,dispatch:d,nextStep:m,prevStep:p,toggleDriver:g,updateJobConfig:b,updateDeliveryConfig:x,setSensitivity:y}}function qO({open:e,onOpenChange:t,cardSnapshot:n}){const r=zre({cardSnapshot:e?n:null}),s=()=>t(!1);return l.jsx(zr,{open:e,onOpenChange:t,children:l.jsxs(Tr,{className:"max-w-7xl h-[90vh] flex flex-col gap-0 p-0",children:[l.jsx(_r,{className:"border-b px-6 py-4",children:l.jsx(Ir,{className:"text-base",children:"Watch this metric?"})}),l.jsxs("div",{className:"flex flex-1 gap-0 overflow-hidden",children:[l.jsx("div",{className:"w-3/5 overflow-y-auto border-r p-6",children:l.jsx(YHe,{wizard:r,onClose:s})}),l.jsx("div",{className:"w-2/5 overflow-y-auto bg-muted/30 p-6",children:l.jsx(JHe,{wizard:r})})]})]})})}function GM(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(Array.isArray(e)){for(const t of e){const n=GM(t);if(n!==null)return n}return null}if(e&&typeof e=="object")for(const t of Object.values(e)){const n=GM(t);if(n!==null)return n}return null}function X8(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return typeof t.connectionId!="string"||typeof t.connectionType!="string"||!Array.isArray(t.selectedEntities)?null:t}function rWe(e){if(e!=null&&e.dataSource)return e.dataSource;if(!(e!=null&&e.queryConfig)||typeof e.queryConfig!="object"||Array.isArray(e.queryConfig))return null;const t=e.queryConfig;return X8(t.cardDataSource)??X8(t.dataSource)}function sWe({card:e,dashboardId:t,visualId:n,accessToken:r,activeFilters:s,controlValues:o,controlDefinitions:i,cardControlDefinitions:a,controlBindings:c,calendarContext:u}){if(!e||!t||!n||!e.connectionId)return;const d=rWe(e);if(d)return{type:"dashboard_metric",dashboardId:t,visualId:n,cardId:e.id,title:e.title||"Metric card",format:u7e({card:e,accessToken:r}),executionSnapshot:{queryConfig:{cardType:e.type,cardMode:"explorer",cardConfig:e.config||{},cardDataSource:d,connectionId:e.connectionId},filterContext:{active_filters:s},...o!==void 0?{controlContext:{values:o}}:{},...i&&i.length>0?{controlDefinitions:i}:{},...a&&a.length>0?{cardControlDefinitions:a}:{},...c&&c.length>0?{controlBindings:c}:{},connectionId:e.connectionId,calendarContext:u}}}function Vre(e,t){return(e==null?void 0:e.type)!=="dashboard_metric"?null:{dashboardId:e.dashboardId,visualId:e.visualId,cardId:e.cardId,title:e.title,...t!==void 0?{currentValue:GM(t)}:{},format:e.format,executionSnapshot:e.executionSnapshot}}const oWe=[{key:"all",label:"All"},{key:"ACTIVE",label:"Watching"},{key:"firing",label:"Surfaced"},{key:"PAUSED",label:"Paused"}];function iWe(e){if(!e)return"--";const t=new Date(e);return Number.isNaN(t.getTime())?"--":t.toLocaleString()}function aWe(e){var t;return((t=e.alertState)==null?void 0:t.currentState)==="FIRING"?"destructive":e.status==="ACTIVE"?"default":e.status==="PAUSED"?"secondary":"outline"}function lWe(e){var t;return((t=e.alertState)==null?void 0:t.currentState)==="FIRING"?"Signal surfaced":e.status==="ACTIVE"?"Watching":e.status==="PAUSED"?"Paused":"Inactive"}function cWe(e,t){return!(t!=null&&t.dashboardId)&&!(t!=null&&t.cardId)?!0:!(e.jobConfig.source.type!=="dashboard_metric"||t.dashboardId&&e.jobConfig.source.dashboardId!==t.dashboardId||t.cardId&&e.jobConfig.source.cardId!==t.cardId)}function Bre({scope:e,prefilledSource:t,allowCreateSignalWatch:n=!0,onOpenAlertDetail:r,onCreateSignalWatch:s}){const{tokenProps:o}=rt(),{alerts:i,isLoading:a,error:c,refetch:u,updateAlert:d,deleteAlert:f,triggerAlert:h,isUpdating:m,isDeleting:p,isTriggering:g}=DF(),[b,x]=w.useState("all"),[y,v]=w.useState(""),[C,S]=w.useState(!1),[N,j]=w.useState(null),k=w.useMemo(()=>i.filter(D=>cWe(D,e)),[i,e]),T=w.useMemo(()=>{const D=y.trim().toLowerCase();return k.filter(A=>{var L,$;return b==="ACTIVE"&&(A.status!=="ACTIVE"||((L=A.alertState)==null?void 0:L.currentState)==="FIRING")||b==="PAUSED"&&A.status!=="PAUSED"||b==="firing"&&(($=A.alertState)==null?void 0:$.currentState)!=="FIRING"?!1:D?A.name.toLowerCase().includes(D)||(A.description||"").toLowerCase().includes(D):!0})},[k,y,b]),E=w.useMemo(()=>({all:k.length,ACTIVE:k.filter(D=>{var A;return D.status==="ACTIVE"&&((A=D.alertState)==null?void 0:A.currentState)!=="FIRING"}).length,PAUSED:k.filter(D=>D.status==="PAUSED").length,firing:k.filter(D=>{var A;return((A=D.alertState)==null?void 0:A.currentState)==="FIRING"}).length}),[k]),_=w.useMemo(()=>{if((t==null?void 0:t.type)==="dashboard_metric")return t},[t]),M=w.useMemo(()=>Vre(_),[_]),P=n&&!!M;return l.jsxs("div",{className:"space-y-4 p-4",children:[l.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-xl font-semibold",children:"Signals"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:e!=null&&e.cardId?"Manage signal watches for this card and investigate what changes.":"See what changed, why it matters, and where to investigate."}),n?P?null:l.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Start a new watch from a dashboard signal card so Semaphor can use that signal context."}):l.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Start new signal watches from a dashboard signal card."})]}),l.jsxs("div",{className:"inline-flex items-center gap-2",children:[l.jsxs(re,{size:"sm",variant:"outline",onClick:()=>u(),children:[l.jsx(WU,{className:"mr-1 h-4 w-4"}),"Refresh"]}),n?l.jsxs(re,{onClick:()=>S(!0),variant:"default",size:"sm",disabled:!P,title:P?"Watch this signal":"Open this from a dashboard signal card to start watching it",children:[l.jsx(Y_,{className:"mr-1 h-4 w-4"}),"Watch a Signal"]}):s?l.jsxs(re,{onClick:s,variant:"default",size:"sm",children:[l.jsx(Y_,{className:"mr-1 h-4 w-4"}),"Choose a Signal"]}):null]})]}),l.jsx("div",{className:"flex flex-wrap items-center gap-2",children:oWe.map(D=>l.jsxs(re,{size:"sm",variant:b===D.key?"default":"outline",onClick:()=>x(D.key),children:[D.label,l.jsx("span",{className:"ml-1 text-xs opacity-80",children:E[D.key]})]},D.key))}),l.jsx(lt,{value:y,onChange:D=>v(D.target.value),placeholder:"Search signals and watches","aria-label":"Search signals and watches",className:"max-w-sm"}),a&&l.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading signals..."}),c&&l.jsx("p",{className:"text-sm text-destructive",children:"Failed to load signals."}),!a&&T.length===0&&l.jsx("div",{className:"rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground",children:"No signals configured yet. Start watching an important business change."}),T.length>0&&l.jsx("div",{className:"overflow-hidden rounded-lg border",children:l.jsxs("table",{className:"w-full text-sm",children:[l.jsx("thead",{className:"bg-muted/40",children:l.jsxs("tr",{children:[l.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Signal"}),l.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Status"}),l.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Where It Surfaces"}),l.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Watching For"}),l.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Last Check"}),l.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Actions"})]})}),l.jsx("tbody",{children:T.map(D=>{var A,L;return l.jsxs("tr",{className:"border-t",children:[l.jsxs("td",{className:"px-3 py-2 align-top",children:[l.jsx("p",{className:"font-medium",children:D.name}),D.description?l.jsx("p",{className:"text-xs text-muted-foreground",children:D.description}):null]}),l.jsx("td",{className:"px-3 py-2 align-top",children:l.jsx(Xe,{variant:aWe(D),children:lWe(D)})}),l.jsx("td",{className:"px-3 py-2 align-top",children:l.jsx("div",{className:"flex flex-wrap gap-1",children:(((A=D.deliveryConfig)==null?void 0:A.channels)??[]).map($=>l.jsx(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:$},$))})}),l.jsx("td",{className:"px-3 py-2 align-top text-xs text-muted-foreground",children:Ore(D.jobConfig.operator,D.jobConfig.threshold)}),l.jsx("td",{className:"px-3 py-2 align-top text-xs text-muted-foreground",children:iWe(((L=D.alertState)==null?void 0:L.lastEvaluatedAt)||D.lastRunAt)}),l.jsx("td",{className:"px-3 py-2 align-top",children:l.jsxs("div",{className:"inline-flex flex-wrap items-center gap-1",children:[l.jsxs(re,{size:"sm",variant:"outline",onClick:()=>r==null?void 0:r(D),disabled:!r,children:[l.jsx(Ws,{className:"mr-1 h-3.5 w-3.5"}),"Investigate"]}),l.jsxs(re,{size:"sm",variant:"outline",onClick:async()=>{try{await h(D.id),qe.success("Signal watch run started")}catch($){qe.error($ instanceof Error?$.message:"Failed to start signal watch run")}},disabled:g,title:"Run this signal watch now",children:[l.jsx(KA,{className:"mr-1 h-3.5 w-3.5"}),"Run Now"]}),D.status==="ACTIVE"?l.jsxs(re,{size:"sm",variant:"outline",onClick:async()=>{try{await d({id:D.id,payload:{status:"PAUSED"}}),qe.success("Signal watch paused")}catch($){qe.error($ instanceof Error?$.message:"Failed to pause signal watch")}},disabled:m,children:[l.jsx(kpe,{className:"mr-1 h-3.5 w-3.5"}),"Pause"]}):l.jsxs(re,{size:"sm",variant:"outline",onClick:async()=>{try{await d({id:D.id,payload:{status:"ACTIVE"}}),qe.success("Signal watch resumed")}catch($){qe.error($ instanceof Error?$.message:"Failed to resume signal watch")}},disabled:m,children:[l.jsx(YA,{className:"mr-1 h-3.5 w-3.5"}),"Resume"]}),l.jsxs(re,{size:"sm",variant:"outline",onClick:()=>j(D),disabled:p,children:[l.jsx(La,{className:"mr-1 h-3.5 w-3.5"}),"Remove Watch"]})]})})]},D.id)})})]})}),l.jsx(qO,{open:C,onOpenChange:S,cardSnapshot:M}),l.jsx(qc,{open:!!N,onOpenChange:D=>{D||j(null)},children:l.jsxs(Pl,{children:[l.jsxs(Ol,{children:[l.jsx($l,{children:"Remove This Signal Watch?"}),l.jsx(zl,{children:N?`This will permanently remove "${N.name}" and cannot be undone.`:"This action cannot be undone."})]}),l.jsxs(Ll,{children:[l.jsx(Bl,{disabled:p,children:"Cancel"}),l.jsx(Vl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:p||!N,onClick:async D=>{if(D.preventDefault(),!!N)try{await f(N.id),qe.success("Signal watch removed"),j(null)}catch(A){qe.error(A instanceof Error?A.message:"Failed to remove signal watch")}},children:"Remove Watch"})]})]})})]})}function Ure({frame:e,isHovered:t,isExpandedViewOpen:n=!1,onExpandClick:r}){var Ke,Ze,st;const{authToken:s,tokenProps:o}=rt(),[i,a]=w.useState(!1),{openPopover:c}=jP(),[u,d]=w.useState(!1),[f,h]=w.useState(!1),[m,p]=w.useState(!1),[g,b]=w.useState(!1),[x,y]=w.useState(!1),[v,C]=w.useState(""),[S,N]=w.useState(!1),[j,k]=w.useState(!1),T=r?n:j,E=r||(()=>k(!0)),_=w.useRef(null),M=w.useRef(null),P=ee(ae=>ae.isDashboardEditing),D=ee(ae=>ae.isDownloadingPdf),A=ee(ae=>ae.selectedSheetId),L=ee(ae=>{var Pe;return(Pe=ae.dashboard)==null?void 0:Pe.id}),$=ee(ae=>{var Pe;return(Pe=ae.dashboard)==null?void 0:Pe.title}),{removeFrame:B,addFrame:V,setSelectedFrameId:R}=ee(ae=>ae.actions),U=e.cards.find(ae=>ae.id===e.activeCardId),{handleEditVisual:O,card:I,data:W}=fPe(e),X=MF((I==null?void 0:I.id)||""),{cardFilterValues:Z}=NP((I==null?void 0:I.id)||""),H=bs(ae=>ae.selectedDashboard),K=bs(ae=>ae.initialDashboard),z=H?(Ze=H==null?void 0:H.permissions)==null?void 0:Ze.canEdit:(Ke=K==null?void 0:K.permissions)==null?void 0:Ke.canEdit,q=ee(ae=>ae.inlineFilterValuesMap[(I==null?void 0:I.id)||""]),Y=w.useMemo(()=>[...Z||[],...q||[]],[Z,q]),G=!!(I&&L&&I.type==="kpi"&&I.connectionId&&(o!=null&&o.apiServiceUrl)&&(s!=null&&s.accessToken)),J=X.length,ne=J>0,be=e.visualId||(I==null?void 0:I.id),te=(st=o==null?void 0:o.params)!=null&&st.calendarContext&&typeof o.params.calendarContext=="object"?o.params.calendarContext:void 0,ce=te&&typeof te.tz=="string"?te.tz:"UTC",se=te&&te.weekStart!==void 0?Number(te.weekStart):1,{controlValues:ue,controlDefinitions:Re,cardControlDefinitions:je,controlBindings:ke}=HN(I),me=w.useMemo(()=>{if(G)return sWe({card:I,dashboardId:L,visualId:be,accessToken:s==null?void 0:s.accessToken,activeFilters:Y,controlValues:ue,controlDefinitions:Re,cardControlDefinitions:je,controlBindings:ke,calendarContext:{tz:ce,weekStart:se}})},[s==null?void 0:s.accessToken,G,I,L,be,Y,ue,Re,je,ke,ce,se]),Me=w.useMemo(()=>Vre(me,(W==null?void 0:W.records)??W),[W,me]),Se=w.useMemo(()=>{if(!(!me||me.type!=="dashboard_metric"))return{dashboardId:me.dashboardId,cardId:me.cardId}},[me]);w.useEffect(()=>()=>{M.current&&clearTimeout(M.current)},[]);const ie=()=>{M.current&&clearTimeout(M.current),a(!0)},pe=()=>{M.current=setTimeout(()=>{a(!1)},300)},Ne=()=>{a(!1),M.current&&clearTimeout(M.current)},de=async()=>{if(!v)return;d(!1),C(""),N(!1);const ae=qe.loading("Generating protected PDF report... may take up to 60 seconds");try{await SPe(o.apiServiceUrl,s,e.activeCardId||"",e.id,(I==null?void 0:I.title)||"visual",I==null?void 0:I.type,v,void 0,void 0,void 0,Y),qe.dismiss(ae),qe.success("Protected visual PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(Pe){qe.dismiss(ae),qe.error("Failed to download protected visual PDF. Please try again."),console.error("Protected visual PDF download error:",Pe)}},fe=()=>{if(A)try{const ae=JSON.parse(JSON.stringify(e)),Pe=yre(ae),Ee=Pe.cards.findIndex(_e=>_e.id===Pe.activeCardId);Ee!==-1&&(Pe.cards[Ee].title=`${Pe.cards[Ee].title} (Copy)`),V(A,Pe,{insertAfterFrameId:e.id,copyLayoutFromFrameId:e.id}),R(Pe.id),qe.success("Card duplicated successfully")}catch(ae){console.error("Failed to duplicate frame:",ae),qe.error("Failed to duplicate card")}},Oe=()=>{const{theme:ae,defaultControlValues:Pe,controlDefinitions:Ee,cardControlDefinitions:_e,controlBindings:We,selectedSheetId:Te,dashboardId:Ue}=WJ(s,e.activeCardId,e.id,(I==null?void 0:I.title)||(U==null?void 0:U.title)||""),et=new URLSearchParams;et.set("token",(s==null?void 0:s.accessToken)||""),et.set("theme",ae),et.set("filterValues",JSON.stringify(Y||[])),et.set("controlValues",JSON.stringify(Pe||{})),BJ(et,{controlDefinitions:Ee,cardControlDefinitions:_e,controlBindings:We}),et.set("cardTitle",(I==null?void 0:I.title)||(U==null?void 0:U.title)||""),et.set("selectedSheetId",Te||""),et.set("dashboardId",Ue||"");const bt=e.activeCardId,dt=cHe({apiServiceUrl:o==null?void 0:o.apiServiceUrl,dashboardId:Ue,cardId:bt,params:et});if(!dt){qe.error("Unable to open this visual in a new window.");return}window.open(dt,"_blank","noopener,noreferrer")},ye=(I==null?void 0:I.type)==="kpi",Ce=(I==null?void 0:I.type)==="text",$e={editVisual:{visible:P&&z},duplicateFrame:{visible:P&&z},expand:{visible:!ye&&!Ce},export:{visible:!ye&&!Ce},alertAction:{visible:!!G},deleteCard:{visible:P&&z},moreOptions:{visible:!ye&&!Ce,submenu:{interactions:{visible:P&&z&&!!(U!=null&&U.config)&&!ye&&!Ce},schedule:{visible:!ye&&!Ce&&!P}}}},ze=$e.editVisual.visible||$e.duplicateFrame.visible||$e.expand.visible||$e.export.visible||$e.alertAction.visible||$e.deleteCard.visible||$e.moreOptions.visible,Ge=t&&!T&&ze;return l.jsxs(l.Fragment,{children:[Ge&&l.jsx("div",{ref:_,className:"absolute right-2 top-2 z-50 duration-200 animate-in fade-in-0 zoom-in-95",onMouseLeave:Ne,children:l.jsx(xi,{className:"min-w-[32px] border-border bg-popover p-0.5 shadow-lg",children:l.jsxs("div",{className:"flex flex-row gap-0.5",children:[$e.alertAction.visible&&l.jsxs(re,{variant:"ghost",size:"sm",className:"relative h-6 w-6 p-0 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:ae=>{ae.stopPropagation(),ne?y(!0):b(!0),a(!1)},disabled:!1,title:ne?`Manage watches (${J})`:"Watch this signal","aria-label":ne?`Manage ${J} signal watch${J===1?"":"es"}`:"Watch this signal",children:[ne?l.jsx(Fm,{className:"h-3.5 w-3.5"}):l.jsx(Y_,{className:"h-3.5 w-3.5"}),ne?l.jsx("span",{className:"absolute -right-1 -top-1 min-w-[0.85rem] rounded-full bg-primary px-[3px] text-[9px] leading-3 text-primary-foreground",children:J>9?"9+":J}):null]}),$e.moreOptions.visible&&l.jsxs("div",{className:"relative",children:[l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-accent hover:text-accent-foreground",onMouseEnter:ie,onMouseLeave:pe,onClick:ae=>ae.stopPropagation(),title:"More Options",children:l.jsx(_h,{className:"h-3.5 w-3.5"})}),i&&l.jsx("div",{className:"z-60 absolute right-full top-0 mr-0.5 duration-150 animate-in fade-in-0 zoom-in-95",onMouseEnter:ie,onMouseLeave:pe,children:l.jsx(xi,{className:"min-w-[140px] border-border bg-popover p-0.5 shadow-lg",children:l.jsxs("div",{className:"flex flex-col gap-0.5",children:[$e.moreOptions.submenu.interactions.visible&&l.jsxs(re,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:ae=>{ae.stopPropagation(),R(e.id);const Pe=e.activeCardId;Pe&&c(e.id,Pe,ae.currentTarget),a(!1)},children:[l.jsx(eg,{className:"mr-1.5 h-3.5 w-3.5"}),l.jsx("span",{className:"text-xs",children:"Interactions"})]}),$e.export.visible&&l.jsxs(re,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:ae=>{ae.stopPropagation(),h(!0),a(!1)},children:[l.jsx(Th,{className:"mr-1.5 h-3.5 w-3.5"}),l.jsx("span",{className:"text-xs",children:"Download"})]}),l.jsxs(re,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:ae=>{ae.stopPropagation(),Oe()},children:[l.jsx(pp,{className:"mr-1.5 h-3.5 w-3.5"}),l.jsx("span",{className:"text-xs",children:"Open in New Window"})]}),$e.moreOptions.submenu.schedule.visible&&l.jsxs(re,{variant:"ghost",size:"sm",className:"h-6 justify-start px-1.5 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:ae=>{ae.stopPropagation(),p(!0),a(!1)},children:[l.jsx(Yu,{className:"mr-1.5 h-3.5 w-3.5"}),l.jsx("span",{className:"text-xs",children:"Schedule Export"})]})]})})})]}),$e.deleteCard.visible&&l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-destructive hover:text-destructive-foreground",onClick:ae=>{ae.stopPropagation(),B(A,e.id)},disabled:!1,title:"Delete Card",children:l.jsx(La,{className:"h-3.5 w-3.5"})}),$e.duplicateFrame.visible&&l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:ae=>{ae.stopPropagation(),fe()},disabled:!1,title:"Duplicate Card",children:l.jsx(PU,{className:"h-3.5 w-3.5"})}),$e.expand.visible&&l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-accent hover:text-accent-foreground",onClick:ae=>{ae.stopPropagation(),E(),a(!1)},disabled:!1,title:"Expand View",children:l.jsx(xN,{className:"h-3.5 w-3.5"})}),$e.editVisual.visible&&l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 transition-colors hover:bg-primary hover:text-primary-foreground",onClick:ae=>{ae.stopPropagation(),O()},disabled:!1,title:"Edit Visual",children:l.jsx(yN,{className:"h-3.5 w-3.5"})})]})})}),l.jsx(zr,{open:u,onOpenChange:d,children:l.jsxs(Tr,{className:"sm:max-w-[425px]",children:[l.jsxs(_r,{children:[l.jsx(Ir,{children:"Download Protected Visual PDF"}),l.jsx(ss,{children:"Enter a password to protect your visual PDF. The PDF will be encrypted and require this password to open."})]}),l.jsx("div",{className:"grid gap-4 py-4",children:l.jsxs("div",{className:"grid gap-2",children:[l.jsx(ge,{htmlFor:"password",children:"Password"}),l.jsxs("div",{className:"relative",children:[l.jsx(lt,{id:"password",type:S?"text":"password",value:v,onChange:ae=>C(ae.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:ae=>{ae.key==="Enter"&&v&&de()}}),l.jsx(re,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>N(!S),children:S?l.jsx(mN,{className:"h-4 w-4 text-muted-foreground"}):l.jsx(Gu,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),l.jsxs(Ds,{children:[l.jsx(re,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),l.jsx(re,{onClick:de,disabled:!v||D,children:"Download"})]})]})}),!r&&j&&l.jsx(CUe,{isOpen:j,onClose:()=>k(!1),frame:e,card:I,data:W}),l.jsx(FP,{isOpen:f,onClose:()=>h(!1),frame:e,card:I,data:W}),l.jsx(Ire,{open:m,onOpenChange:p,dashboardId:L||"",dashboardName:$,preSelectedVisual:I?{visualId:I.id,cardType:I.type,title:I.title||"Visual",type:"visual",format:RP(I.type),supportedFormats:AP(I.type),settings:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0,inlineFilterValues:q}}:void 0}),l.jsx(qO,{open:g,onOpenChange:b,cardSnapshot:Me}),l.jsx(zr,{open:x,onOpenChange:y,children:l.jsxs(Tr,{className:"max-h-[92vh] overflow-auto sm:max-w-5xl",children:[l.jsxs(_r,{children:[l.jsx(Ir,{children:"Manage Signal Watches"}),l.jsx(ss,{children:"Review surfaced signals, pause watches, send previews, and remove watches for this dashboard."})]}),l.jsx(Bre,{scope:Se,prefilledSource:me})]})})]})}Ure.displayName="CardControlsToolbar";const Hre=w.memo(Ure);function YO({card:e}){const t=ee(v=>v.isVisualEditing),{setCardInfo:n}=lr(),[r,s]=w.useState(!1),[o,i]=w.useState(!1),[a,c]=w.useState(e.info||""),u=w.useRef(null),d=e.info||"",f=d.trim(),h=a.trim(),m=w.useMemo(()=>h!==f,[f,h]);w.useEffect(()=>{o||c(d)},[d,o]),w.useEffect(()=>{if(!o)return;const v=u.current;if(!v)return;v.focus();const C=v.value.length;v.setSelectionRange(C,C)},[o]);const p=()=>{t&&(c(d),i(!0))},g=()=>{c(d),i(!1)},b=()=>{if(t){if(!m){i(!1);return}n(h),i(!1)}},x=v=>{v||g(),s(v)},y="Describe what this card shows";return l.jsxs(Gr,{open:r,onOpenChange:x,children:[l.jsx(Kr,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":f?"View card info":"Add card info",className:"inline-flex items-center justify-center text-muted-foreground/40 transition-colors hover:text-muted-foreground",onMouseDown:v=>v.stopPropagation(),onClick:v=>v.stopPropagation(),children:l.jsx(hr,{className:"size-4"})})}),l.jsx(Zr,{align:"start",className:"w-[340px] p-3",onMouseDown:v=>v.stopPropagation(),onClick:v=>v.stopPropagation(),children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"About this visual"}),o?l.jsxs(l.Fragment,{children:[l.jsx(yi,{ref:u,value:a,onChange:v=>c(v.target.value),onKeyDown:v=>{v.key==="Escape"&&(v.preventDefault(),g()),(v.metaKey||v.ctrlKey)&&v.key==="Enter"&&(v.preventDefault(),b())},className:"min-h-[120px] resize-y text-sm",placeholder:y}),l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("span",{className:"text-xs text-muted-foreground",children:"Press Ctrl/Cmd+Enter to save"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(re,{size:"sm",variant:"outline",onClick:g,children:"Cancel"}),l.jsx(re,{size:"sm",onClick:b,disabled:!m,children:"Save"})]})]})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"max-h-52 overflow-y-auto whitespace-pre-wrap text-sm text-muted-foreground",children:f?d:l.jsx("span",{className:"italic text-muted-foreground/80",children:y})}),t&&l.jsx("div",{className:"flex justify-end",children:l.jsx(re,{size:"sm",variant:f?"outline":"default",onClick:p,children:f?"Edit":"Add info"})})]})]})})]})}function uWe({card:e,renderFilterInfo:t}){var y,v,C,S,N,j,k,T,E;ee(_=>_.themeStyle);const{data:n,isLoading:r}=kl(e),s=(n==null?void 0:n.records)||[],{getCurrency:o,getLocale:i,getPrimaryFormat:a}=rE(e),c=(v=(y=e.preferences)==null?void 0:y.formatNumber)==null?void 0:v.colorRanges,u=Oa(a()),d=(S=(C=e.preferences)==null?void 0:C.formatNumber)==null?void 0:S.enabled,f=d===!1||d==="false",{keys:h}=Qn(s||[]),m=(N=s==null?void 0:s[0])==null?void 0:N[h==null?void 0:h[0]],p=(j=s==null?void 0:s[0])==null?void 0:j[h==null?void 0:h[1]],g=(s==null?void 0:s.length)>0,b=p&&p-m!==0?(m-p)/p:null,x=_=>{var M,P,D,A,L,$;return f?String(_):u!=null&&u.type&&u.type!=="auto"?kn(_,u.type,{...u,locale:u.locale||i()||"",currency:u.currency||o()||""}):Lp({number:_,decimalPlaces:((P=(M=e.preferences)==null?void 0:M.formatNumber)==null?void 0:P.decimalPlaces)||0,useSuffix:!!((A=(D=e.preferences)==null?void 0:D.formatNumber)!=null&&A.suffix),customSuffix:(($=(L=e.preferences)==null?void 0:L.formatNumber)==null?void 0:$.suffix)||"",locale:i()||"",currency:o()||""})};return l.jsx("div",{className:"flex min-w-fit grow flex-col overflow-auto",children:l.jsxs("div",{className:"grow",children:[g?l.jsx("div",{className:"",children:l.jsxs("div",{className:Q("flex items-end gap-1.5",{"animate-pulse":r}),children:[l.jsx("p",{style:{color:qj(m,c)},className:"text-3xl font-semibold",children:x(m)}),b&&l.jsxs("div",{className:"flex items-end gap-1",children:[l.jsx(bre,{isLowerIsBetter:(T=(k=e.preferences)==null?void 0:k.kpiVisualOptions)==null?void 0:T.lowerIsBetter,className:"",children:b}),p&&l.jsx("div",{className:"ml-0.5 mr-1 min-w-fit text-sm font-normal text-muted-foreground",children:`from ${x(p)}`})]})]})}):l.jsx("div",{className:"flex h-9 items-center justify-center"}),l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsxs(ja,{className:"flex items-center gap-2 text-base font-medium text-muted-foreground",children:[e.title,((E=e.info)==null?void 0:E.trim())&&l.jsx(YO,{card:e})]}),t==null?void 0:t()]})]})})}function dWe({cardId:e}){const t=h7(e||""),n=Vt(c=>c.removeClickFiltersByValue),r=t.map((c,u)=>{const d=c.filterGroups.flatMap(f=>f.filters.map(h=>({field:h.field.label||h.field.name,value:h.value})));return{id:`click-filter-${c.sourceCardId}-${u}`,sourceCardId:c.sourceCardId,name:`Click Filter from ${c.sourceCardId}`,values:d,applyToCardIds:c.applyToCardIds,excludeCardIds:c.excludeCardIds,originalEvent:c}}),s=r.reduce((c,u)=>(u.values.forEach(d=>{var h,m;const f=c.find(p=>p.fieldName===d.field);f?f.filters.some(g=>g.values.some(b=>b.field===d.field&&b.value===d.value))||f.filters.push(u):c.push({fieldName:d.field,fieldLabel:d.field,filters:[u],targetingInfo:(h=u.applyToCardIds)!=null&&h.length?`Applied to: ${u.applyToCardIds.join(", ")}`:(m=u.excludeCardIds)!=null&&m.length?`Excluded from: ${u.excludeCardIds.join(", ")}`:"Applied to all cards"})}),c),[]);function o(c,u){const d=r.filter(f=>f.values.some(h=>h.field===c&&h.value===u));if(d.length>0){const h=d.sort((m,p)=>{const g=t.findIndex(x=>Pi(x,m.originalEvent));return t.findIndex(x=>Pi(x,p.originalEvent))-g})[0];n(h.sourceCardId,c,u)}}function i(c){const u=r.flatMap(f=>f.values.filter(h=>h.field===c)).map(f=>f.value);[...new Set(u)].forEach(f=>{o(c,f)})}function a(c){const u=c.filters.flatMap(h=>h.values.filter(m=>m.field===c.fieldName)).map(h=>h.value),d=[...new Set(u)],f=d.filter(h=>{const g=c.filters.filter(y=>y.values.some(v=>v.field===c.fieldName&&v.value===h)).sort((y,v)=>{const C=t.findIndex(N=>Pi(N,y.originalEvent));return t.findIndex(N=>Pi(N,v.originalEvent))-C})[0];return t.findIndex(y=>Pi(y,g.originalEvent))===t.length-1});return l.jsxs("div",{className:"space-y-3 rounded-lg border border-border/50 bg-muted/30 p-3",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"h-2 w-2 flex-shrink-0 rounded-full bg-blue-500"}),l.jsx(ge,{className:"text-sm font-medium text-foreground",children:c.fieldLabel})]}),l.jsxs(re,{variant:"ghost",size:"sm",onClick:()=>i(c.fieldName),className:"h-7 px-2.5 text-xs text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive",children:[l.jsx(La,{className:"mr-1.5 h-3.5 w-3.5"}),"Clear"]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"flex flex-wrap gap-1.5",children:d.map((h,m)=>{const p=f.includes(h);return l.jsxs(Xe,{variant:"secondary",className:`group relative ${p?"cursor-pointer border border-blue-500/20 bg-blue-500/10 text-blue-600 transition-colors hover:bg-blue-500/15":"cursor-not-allowed border border-border/30 bg-muted/50 text-muted-foreground"}`,onClick:()=>{p&&o(c.fieldName,h)},children:[h,l.jsx(Mt,{className:`ml-1.5 h-3 w-3 ${p?"opacity-60 transition-opacity group-hover:opacity-100":"cursor-not-allowed opacity-40"}`})]},m)})}),d.length>1&&l.jsx("div",{className:"text-xs text-muted-foreground",children:'Clear filters in sequence (most recent first) or use "Clear" to remove all'})]})]})}return s.length===0?null:l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Cpe,{className:"h-3.5 w-3.5 text-muted-foreground"}),l.jsx("span",{className:"text-xs font-medium text-foreground",children:"Click Filters"})]}),l.jsx("div",{className:"space-y-3",children:s==null?void 0:s.map(c=>l.jsx("div",{children:a(c)},c.fieldName))})]})}function KM({cardId:e,cardFilters:t,cardFilterCount:n=0,onFiltersClick:r,inlineFilters:s,inlineFilterValues:o,sheetId:i,removeInlineFilterValue:a}){var de,fe,Oe;const[c,u]=w.useState(!1),d=ee(ye=>ye.isDashboardEditing),f=ee(ye=>ye.isVisualEditing),h=ee(ye=>ye.dashboard.defaultFilterValues),m=ee(ye=>ye.themeStyle),p=ee(ye=>ye.filterValues),g=ee(ye=>ye.dashboard.filters),b=ee(ye=>ye.filteringCards),x=ee(ye=>ye.selectedSheetId),y=ee(ye=>ye.onSaveFunction),{removeFilterValues:v,removeFilteringCard:C,setFilterValues:S,setFilteringCards:N,setDefaultFilterValues:j,getDashboard:k}=en(),{tokenProps:T}=rt(),_=((fe=(de=T==null?void 0:T.params)==null?void 0:de.calendarContext)==null?void 0:fe.tz)||((Oe=T==null?void 0:T.params)==null?void 0:Oe.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone,{updateFilters:M,clearFilters:P}=lr(),{updateCardFilters:D,clearCardFilters:A}=en(),L=ee(ye=>ye.actions.removeCardInlineFilterValue),$=Vt(ye=>ye.clearAllClickFilters),B=e?zR(g,p,x,e).cardFilterValues:(()=>{const ye=Yl(g,x);return p==null?void 0:p.filter(Ce=>(ye==null?void 0:ye.some($e=>$e.id===Ce.filterId))||Ce.filterId.endsWith(x))})(),V=(B==null?void 0:B.map(ye=>{const Ce=g==null?void 0:g.find($e=>$e.id===ye.filterId);return{filterId:ye.filterId,fieldName:(Ce==null?void 0:Ce.title)||ye.name,fieldLabel:(Ce==null?void 0:Ce.title)||ye.name,values:ye.values,dataType:Ce==null?void 0:Ce.dataType,operation:Ce==null?void 0:Ce.operation,isDateFilter:Ca((Ce==null?void 0:Ce.dataType)||"")}}))||[],R=h7(e||""),U=(o==null?void 0:o.length)||0;if(!f&&V.length===0&&R.length===0&&n===0&&U===0)return null;const O=V.length+R.length+n+U,I={dashboard:V.length,card:n,inline:U,click:R.length},W=[I.dashboard>0?"dashboard":null,I.card>0?"card":null,I.inline>0?"inline":null,I.click>0?"click":null].filter(ye=>ye!==null),X=W.length===0?"none":W.length===1?W[0]:"mixed",Z={dashboard:"Dashboard",card:"Card",inline:"Inline",click:"Click",mixed:"Mixed"},H={none:"border-border/70 bg-muted/30 text-muted-foreground hover:bg-muted/50",dashboard:"border-purple-200/70 bg-purple-50/60 text-purple-700 hover:bg-purple-100/70 dark:border-purple-800/50 dark:bg-purple-950/40 dark:text-purple-300 dark:hover:bg-purple-900/50",card:"border-blue-200/70 bg-blue-50/60 text-blue-700 hover:bg-blue-100/70 dark:border-blue-800/50 dark:bg-blue-950/40 dark:text-blue-300 dark:hover:bg-blue-900/50",inline:"border-green-200/70 bg-green-50/60 text-green-700 hover:bg-green-100/70 dark:border-green-800/50 dark:bg-green-950/40 dark:text-green-300 dark:hover:bg-green-900/50",click:"border-amber-200/70 bg-amber-50/60 text-amber-700 hover:bg-amber-100/70 dark:border-amber-800/50 dark:bg-amber-950/40 dark:text-amber-300 dark:hover:bg-amber-900/50",mixed:"border-indigo-200/70 bg-indigo-50/60 text-indigo-700 hover:bg-indigo-100/70 dark:border-indigo-800/50 dark:bg-indigo-950/40 dark:text-indigo-300 dark:hover:bg-indigo-900/50"},K=X==="none"?0:X==="mixed"?O:I[X],z=f,q=z?H[X]:"border-border/70 bg-muted/30 text-muted-foreground hover:bg-muted/50",Y=z&&X!=="none"?Z[X]:null,G=z?K:O;function J(ye){return ye instanceof Date?ot.formatInTimeZone(ye,_,"MM/dd/yyyy"):ye}function ne(ye){const Ce=b==null?void 0:b.find($e=>ye.filterId.startsWith($e.id));Ce&&C(Ce),v(ye.filterId)}function be(ye){V.filter($e=>$e.fieldName===ye).forEach($e=>{ne($e)})}function te(ye){if(e){if(a){a(ye);return}L(e,ye)}}function ce(){!e||!(o!=null&&o.length)||o.forEach(ye=>{a?a(ye.filterId):L(e,ye.filterId)})}function se(){N([]),S([]),$(),e&&f&&P(e),ce()}function ue(ye){function Ce(){return ye.values.map((ze,Ge)=>l.jsx(Xe,{variant:"outline",className:"cursor-pointer select-none border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm transition-all hover:shadow-md hover:from-purple-100/60 hover:to-purple-100/50 dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",onClick:()=>ne(ye),children:l.jsxs("span",{className:"flex items-center gap-1.5",children:[l.jsx("span",{className:"font-medium",children:J(ze)}),l.jsx(Mt,{className:"h-3 w-3"})]})},(ze==null?void 0:ze.toString())+Ge))}function $e(){const ze=ye.values[0],Ge=ye.values[1];if(!ze||!Ge)return null;const Ke=new Date(ze),Ze=new Date(Ge),st=ot.formatInTimeZone(Ke,_,"MM/dd/yyyy"),ae=ot.formatInTimeZone(Ze,_,"MM/dd/yyyy");return l.jsx(Xe,{variant:"outline",className:"cursor-pointer select-none border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm transition-all hover:shadow-md hover:from-purple-100/60 hover:to-purple-100/50 dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",onClick:()=>ne(ye),children:l.jsxs("span",{className:"flex items-center gap-1.5",children:[l.jsx("span",{className:"font-medium",children:`${st} - ${ae}`}),l.jsx(Mt,{className:"h-3 w-3"})]})})}return l.jsxs("div",{className:"group space-y-1.5 rounded-lg border border-border/50 bg-muted/30 p-2 transition-colors hover:bg-muted/50",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:ye.fieldLabel}),!ye.isDateFilter&&ye.operation==="not in"&&l.jsx("span",{className:"text-xs text-muted-foreground/70",children:rC(ye.operation)})]}),l.jsx(re,{variant:"ghost",size:"sm",onClick:()=>be(ye.fieldName),className:"h-4 w-4 p-0 text-muted-foreground/70 opacity-0 transition-all hover:bg-muted/60 hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100","aria-label":"Clear filter",children:l.jsx(Mt,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex flex-wrap gap-1.5",children:ye.isDateFilter?$e():Ce()})]})}function Re(ye){return{"=":"equals","!=":"not equals",">":"greater than",">=":"greater than or equals","<":"less than","<=":"less than or equals",contains:"contains",startsWith:"starts with",endsWith:"ends with",in:"in","not in":"not in",between:"between",isNull:"is null",isNotNull:"is not null","not between":"not between"}[ye]||ye}function je(ye){const Ce=$e=>$e instanceof Date?ot.formatInTimeZone($e,_,"MM/dd/yyyy"):String($e);if(Array.isArray(ye.value)){if(ye.operator==="between"){const $e=Ce(ye.value[0]),ze=Ce(ye.value[1]);return`${$e} and ${ze}`}return ye.value.map(Ce).join(", ")}return ye.value instanceof Date?ot.formatInTimeZone(ye.value,_,"MM/dd/yyyy"):String(ye.value||"")}function ke(ye){if(!t||!e)return;const Ce=ze=>({...ze,conditions:ze.conditions.filter(Ge=>Ge.id!==ye),groups:ze.groups.map(Ce)}),$e=Ce(t);f?M(e,$e):D(e,$e)}function me(){e&&(f?P(e):A(e),ce())}function Me(ye){const Ce=[...ye.conditions];return ye.groups.forEach($e=>{Ce.push(...Me($e))}),Ce}function Se(){if(!t)return null;const ye=Me(t);return ye.length===0?null:l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Card Filters"}),f&&l.jsxs(re,{variant:"ghost",size:"sm",onClick:me,className:"h-6 px-2 text-xs text-muted-foreground/70 transition-colors hover:bg-muted/60 hover:text-foreground",children:[l.jsx(Mt,{className:"mr-1 h-3 w-3"}),"Clear All"]})]}),l.jsx("div",{className:"space-y-1.5",children:ye.map(Ce=>l.jsxs("div",{className:"group space-y-1.5 rounded-lg border border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 p-2 transition-colors hover:from-blue-100/60 hover:to-blue-100/50 dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:Ce.field.label||Ce.field.name}),l.jsx("span",{className:"text-xs text-muted-foreground/70",children:Re(Ce.operator)})]}),f&&l.jsx(re,{variant:"ghost",size:"sm",onClick:()=>ke(Ce.id),className:"h-4 w-4 p-0 text-muted-foreground/70 opacity-0 transition-all hover:bg-muted/60 hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100","aria-label":"Clear filter",children:l.jsx(Mt,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.jsx(Xe,{variant:"outline",className:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100",children:l.jsx("span",{className:"font-medium",children:je(Ce)})})})]},Ce.id))})]})}function ie(){return!o||o.length===0?null:l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Inline Filters"}),l.jsx("div",{className:"space-y-1.5",children:o.map(ye=>{const Ce=s==null?void 0:s.find(ze=>ze.id===ye.filterId);if(!Ce)return null;const $e=Ca(Ce.dataType);return l.jsxs("div",{className:"group space-y-1.5 rounded-lg border border-green-200/70 bg-gradient-to-r from-green-50/50 to-green-100/30 p-2 transition-colors hover:from-green-100/60 hover:to-green-100/50 dark:border-green-800/50 dark:from-green-950/40 dark:to-green-900/30",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:Ce.title}),!$e&&ye.operation==="not in"&&l.jsx("span",{className:"text-xs text-muted-foreground/70",children:rC(ye.operation)})]}),l.jsx(re,{variant:"ghost",size:"sm",onClick:()=>{te(ye.filterId)},className:"h-4 w-4 p-0 text-muted-foreground/70 opacity-0 transition-all hover:bg-muted/60 hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100","aria-label":"Clear filter",children:l.jsx(Mt,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex flex-wrap gap-1.5",children:$e?(()=>{const ze=ye.values;if(!ze[0]||!ze[1])return null;const Ge=new Date(ze[0]),Ke=new Date(ze[1]),Ze=ot.formatInTimeZone(Ge,_,"MM/dd/yyyy"),st=ot.formatInTimeZone(Ke,_,"MM/dd/yyyy");return l.jsx(Xe,{variant:"outline",className:"border-green-200/70 bg-gradient-to-r from-green-50/50 to-green-100/30 text-green-900 shadow-sm dark:border-green-800/50 dark:from-green-950/40 dark:to-green-900/30 dark:text-green-100",children:l.jsx("span",{className:"font-medium",children:`${Ze} - ${st}`})})})():ye.values.map((ze,Ge)=>l.jsx(Xe,{variant:"outline",className:"border-green-200/70 bg-gradient-to-r from-green-50/50 to-green-100/30 text-green-900 shadow-sm dark:border-green-800/50 dark:from-green-950/40 dark:to-green-900/30 dark:text-green-100",children:l.jsx("span",{className:"font-medium",children:J(ze)})},String(ze)+Ge))})]},ye.filterId)})})]})}function pe(ye){const Ce=k();Ce&&(y==null||y(Ce,ye))}function Ne(){return l.jsxs(l.Fragment,{children:[l.jsx(Vs,{className:"my-4"}),l.jsxs("div",{className:"space-y-3",children:[l.jsx("p",{className:"text-xs text-muted-foreground",children:"Start with these filters? Set them as default."}),l.jsxs("div",{className:"flex flex-row-reverse gap-2",children:[l.jsxs(re,{onClick:()=>{j(p||[]),pe("Default filters saved successfully")},style:{borderRadius:m==null?void 0:m.controlInputRadius},className:"h-8 text-xs font-medium",variant:"outline",children:[h&&(h==null?void 0:h.length)>0&&l.jsx(qr,{className:"mr-1.5 h-3.5 w-3.5 text-green-500"}),"Set Default"]}),l.jsx(re,{onClick:()=>{j(void 0),pe("Default filters cleared")},style:{borderRadius:m==null?void 0:m.controlInputRadius},className:"h-8 text-xs font-medium",variant:"secondary",children:"Reset"})]})]})]})}return l.jsxs(Yc,{open:c,onOpenChange:u,openDelay:50,children:[l.jsx(Gc,{asChild:!0,children:l.jsxs(Xe,{variant:"outline",className:Q("h-6 cursor-pointer select-none gap-1.5 transition-all",q),onClick:ye=>{ye.stopPropagation(),u(!1),r==null||r()},children:[l.jsx(Ic,{className:"h-3 w-3"}),Y&&l.jsx("span",{className:"text-[10px] font-medium",children:Y}),G>0&&l.jsx("span",{className:"text-xs font-medium",children:G})]})}),l.jsx(Ia,{onMouseDown:ye=>ye.stopPropagation(),style:{borderRadius:m==null?void 0:m.cardBorderRadius},className:"w-[380px] border border-border/50 p-0 text-xs shadow-lg",align:"start",children:O===0?l.jsxs("div",{className:"p-6 text-center",children:[l.jsx(Ic,{className:"mx-auto mb-3 h-8 w-8 text-muted-foreground/50"}),l.jsx("p",{className:"text-sm font-medium text-foreground",children:"No filters applied"}),l.jsx("p",{className:"mb-4 mt-1 text-xs text-muted-foreground",children:"Add filters to narrow down your data"}),l.jsxs(re,{variant:"outline",size:"sm",onClick:ye=>{ye.stopPropagation(),u(!1),r==null||r()},className:"mx-auto",children:[l.jsx(Ic,{className:"mr-2 h-3.5 w-3.5"}),"Add Filters"]})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"border-b border-border/50 bg-muted/30 px-3 py-2",children:l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-sm font-medium text-foreground",children:"Active Filters"}),l.jsx(Xe,{variant:"secondary",className:"h-5 px-1.5 text-[10px] font-medium",children:O})]}),l.jsxs(re,{variant:"ghost",size:"sm",onClick:se,className:"h-6 px-2 text-xs text-muted-foreground/70 transition-colors hover:bg-muted/60 hover:text-foreground",children:[l.jsx(Mt,{className:"mr-1 h-3 w-3"}),"Clear All"]})]})}),l.jsxs("div",{className:"space-y-2.5 p-3",children:[l.jsxs("div",{className:"max-h-[280px] space-y-2.5 overflow-y-auto",children:[V.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Dashboard Filters"}),l.jsx("div",{className:"space-y-1.5",children:V==null?void 0:V.map(ye=>l.jsx("div",{children:ue(ye)},ye.filterId))})]}),l.jsx(dWe,{cardId:e}),Se(),ie()]}),d&&!f&&Ne()]})]})})]})}function Wre({columns:e=5,rows:t=10}){const n=ee(r=>r.themeStyle);return l.jsxs(za,{style:{borderRadius:n==null?void 0:n.cardBorderRadius},className:"relative h-full w-full rounded-none border border-border/60 bg-background/95",children:[l.jsxs("table",{className:"w-full text-sm [border-spacing:0]",children:[l.jsx(Mg,{className:"sticky top-0 z-10 border-b border-border/60 bg-muted",children:l.jsx(Pr,{children:Array.from({length:e}).map((r,s)=>l.jsx(Go,{className:"h-10 border-r border-border/20 text-foreground/80 last:border-r-0",children:l.jsx(rs,{className:"h-4 w-full"})},s))})}),l.jsx(fh,{children:Array.from({length:t}).map((r,s)=>l.jsx(Pr,{className:Q("border-border/35 transition-colors duration-150",s%2===1&&"bg-muted/[0.14]"),children:Array.from({length:e}).map((o,i)=>l.jsx(Un,{className:"overflow-hidden border-r border-border/20 py-2.5 text-foreground/90 last:border-r-0",children:l.jsx(rs,{className:"h-4 w-full"})},i))},s))})]}),l.jsx(Da,{orientation:"horizontal"})]})}const wS=e=>{if(!e)return 0;let t=e.conditions.length;return e.groups.forEach(n=>{t+=wS(n)}),t};function ZM(e,t){const{function:n,rowLevel:r,columnLevel:s}=e,o={...t};if(r!==void 0){const i=o.rowAggregates||[],a=r==="all"?"ALL":r,c=i.findIndex(u=>u.groupLevel===a&&u.function===n);c>=0?o.rowAggregates=i.filter((u,d)=>d!==c):o.rowAggregates=[...i,{function:n,groupLevel:a}]}if(s!==void 0){const i=o.columnAggregates||[],a=s==="all"?"ALL":s,c=i.findIndex(u=>u.pivotLevel===a&&u.function===n);c>=0?o.columnAggregates=i.filter((u,d)=>d!==c):o.columnAggregates=[...i,{function:n,pivotLevel:a}]}return o}function qre(e,t){const n={...t};return e.type==="row"&&n.rowAggregates?n.rowAggregates=n.rowAggregates.map(r=>r.function===e.function&&r.groupLevel===e.level?{...r,label:e.label}:r):e.type==="column"&&n.columnAggregates&&(n.columnAggregates=n.columnAggregates.map(r=>r.function===e.function&&r.pivotLevel===e.level?{...r,label:e.label}:r)),n}function Q8({frame:e}){var f,h;const[t,n]=w.useState(!1),r=e==null?void 0:e.cards[0],{data:s,isPending:o,isError:i}=kl(r),a=e==null?void 0:e.cards[1],{data:c,isLoading:u,isFetching:d}=kl(a);return(a==null?void 0:a.type)!=="text"?l.jsx(ph,{card:r,data:(s==null?void 0:s.records)||[],isPending:o,isError:i,comparisonMetadata:(f=s==null?void 0:s.metadata)==null?void 0:f.comparisonMetadata}):l.jsxs(Fo,{className:Q("group relative overflow-y-auto",t?"m-4":"mx-0"),children:[t?l.jsx("div",{className:"overflow-y-auto break-words p-1",children:l.jsx($p,{card:a,data:(c==null?void 0:c.records)||[],isLoading:!1})}):l.jsx(ph,{card:r,data:(s==null?void 0:s.records)||[],isPending:o,isError:i,comparisonMetadata:(h=s==null?void 0:s.metadata)==null?void 0:h.comparisonMetadata}),l.jsx("div",{className:Q("fixed z-10",{"invisible bottom-4 right-4 group-hover:visible":t,"right-6 top-6":!t}),children:l.jsx(uv,{disabled:u||d,className:Q("h-7 p-1"),pressed:t,onPressedChange:n,"aria-label":"Toggle bold",children:t?l.jsx(xpe,{className:"size-4 text-muted-foreground/70"}):l.jsx(ype,{className:"size-4 text-muted-foreground/70"})})})]})}function CS(e){return{clickFilter:Ic,drillToDetail:XA,drillThrough:pp,drillToURL:pN,drillDown:Spe,drillUp:Npe,dynamicDrill:Ws,inlineDrill:bN}[e]||Ic}function Uh(e){return{clickFilter:"Filter Dashboard",drillToDetail:"Show Details",drillThrough:"Navigate to Dashboard",drillToURL:"Open External Link",drillDown:"Drill Down",drillUp:"Drill Up",dynamicDrill:"Explore Field",inlineDrill:"Drill"}[e]||"Interaction"}function fWe(e,t,n,r,s){const o=CS(e.mode),i=e.label||Uh(e.mode),a=hWe(e,t,n,r,s);return{label:i,icon:o,targetInfo:a,interaction:e}}function hWe(e,t,n=0,r,s){var o,i,a,c,u,d;switch(e.mode){case"clickFilter":{if((o=e.applyToCardIds)!=null&&o.length){const f=e.applyToCardIds.length;return`Apply to ${f} ${f===1?"card":"cards"}`}return(i=e.excludeCardIds)!=null&&i.length?"Apply to all cards":"Apply to other cards"}case"drillToDetail":{if(e.targetInsightId)return"Drill into Insight";const f=((a=e.detailFields)==null?void 0:a.length)||0;return f>0?`Show ${f} detail ${f===1?"field":"fields"}`:"Show detail table"}case"drillThrough":return e.targetDashboardId,"Navigate to dashboard";case"drillToURL":{if(e.urlTemplate)try{return`Open ${new URL(e.urlTemplate).hostname}`}catch{return"Open external link"}return"Open external link"}case"drillDown":{if(e.hierarchyId&&t){const f=t.find(h=>h.id===e.hierarchyId);if(f&&f.steps.length>0){let h;if((f.type==="date"||f.baseField)&&r&&f.baseField){const m=GD(f,r,s),p=YD(f,m);h=p==null?void 0:p.field}else h=(c=f.steps[n])==null?void 0:c.field;return h?h.label:n>=f.steps.length?"End of path":f.label||"Drill by hierarchy"}}return"Drill to next level"}case"drillUp":{if(n>0&&e.hierarchyId&&t){const f=t.find(h=>h.id===e.hierarchyId);if(f&&f.steps.length>0){const h=(u=f.steps[n-2])==null?void 0:u.field;return h?`Back to ${h.label}`:`Back to All: ${f.label||"Data"}`}}return"Go back one level"}case"dynamicDrill":{if(e.drillField)return`Drill into ${e.drillField.label} data`;if((d=e.availableFields)!=null&&d.length){const f=e.availableFields.length;return`Choose from ${f} ${f===1?"dimension":"dimensions"}`}return"Explore dimension"}case"inlineDrill":{const f=e.inlineLimit||100,h=e.displayMode||"table";return`Show ${f} records as ${h}`}default:return""}}function mWe(e,t,n,r,s){return e.map(o=>fWe(o,t,n,r,s))}const J8=[];function pWe({open:e,onOpenChange:t,position:n,interactions:r,selectedConditions:s,onSelectInteraction:o,drillHierarchies:i,cardId:a,card:c}){const{currentDepth:u,breadcrumbs:d}=Vt(Kp(C=>{var S,N,j;return{currentDepth:a?((N=(S=C.interactionStates[a])==null?void 0:S.breadcrumbs)==null?void 0:N.length)??0:0,breadcrumbs:a?((j=C.interactionStates[a])==null?void 0:j.breadcrumbs)??J8:J8}})),f=F.useMemo(()=>mWe(r,i,u,c,d),[r,i,u,c,d]),h=F.useMemo(()=>{if(s.length===0)return"";const C=s[0];if(C.label){const S=C.label.split(/[=><]/);if(S.length>1)return S[1].trim()}return String(C.value)},[s]);if(F.useEffect(()=>{if(!e)return;const C=S=>{S.key==="Escape"&&t(!1)};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[e,t]),!e||!n)return null;const m=280,p=80+f.length*60,g=window.innerWidth,b=window.innerHeight;let x=n.x,y=n.y+8;x+m>g&&(x=Math.max(8,g-m-8)),y+p>b&&(y=Math.max(8,n.y-p-8));const v=l.jsxs("div",{className:"semaphor-scope",style:{position:"fixed",inset:0,pointerEvents:"none",background:"transparent"},children:[l.jsx("div",{className:"fixed inset-0",style:{zIndex:50,pointerEvents:"auto",background:"transparent"},onClick:()=>t(!1),"aria-hidden":"true"}),l.jsxs("div",{className:Q("fixed rounded-lg border bg-popover shadow-lg","animate-in fade-in-0 zoom-in-95"),style:{left:`${x}px`,top:`${y}px`,zIndex:51,width:`${m}px`,maxHeight:"400px",pointerEvents:"auto"},role:"menu","aria-label":"Select interaction",children:[h&&l.jsxs("div",{className:"border-b px-4 py-3",children:[l.jsx("p",{className:"text-xs text-muted-foreground",children:"Selected"}),l.jsx("p",{className:"text-sm font-medium",children:h})]}),l.jsx("div",{className:"max-h-80 overflow-y-auto py-1",children:f.map((C,S)=>{var k;const N=C.icon,j=C.interaction.mode==="dynamicDrill"&&(S===0||((k=f[S-1])==null?void 0:k.interaction.mode)!=="dynamicDrill");return l.jsxs(F.Fragment,{children:[j&&l.jsx("div",{className:"border-t px-4 py-2",children:l.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"⚡ Explore Other Fields"})}),l.jsxs("button",{className:Q("flex w-full items-start gap-3 px-4 py-3","hover:bg-accent hover:text-accent-foreground","cursor-pointer transition-colors","border-b text-left last:border-b-0"),onClick:()=>{o(C.interaction),t(!1)},role:"menuitem",children:[l.jsx("div",{className:"mt-0.5 flex-shrink-0",children:l.jsx(N,{className:"h-4 w-4 text-muted-foreground"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("p",{className:"mb-1 text-sm font-medium leading-none",children:C.label}),C.targetInfo&&l.jsx("p",{className:"text-xs text-muted-foreground",children:C.targetInfo})]})]})]},S)})})]})]});return mr.createPortal(v,document.body)}function gWe(e){const t=w.useRef([]),n=w.useRef(null),r=w.useRef(null),o=gc(e.interactionConfig).some(h=>h.mode==="clickFilter"&&h.trigger!==void 0),i=ku(h=>h.registerClearBlurCallback),a=ku(h=>h.unregisterCard);w.useEffect(()=>{const h=()=>{r.current&&f(r.current)};return i(e.id,h),()=>{a(e.id)}},[e.id,i,a]);function c({chart:h,selectedSegments:m,storedOriginalColorsRef:p}){if(!h||!h.canvas||!h.canvas.ownerDocument){console.warn("Chart or canvas is null when trying to toggle blur segments");return}const g=h.data.datasets;p.current||(p.current=g.map((x,y)=>h.getDatasetMeta(y).data.map(C=>C.options.backgroundColor)));const b=p.current;g.forEach((x,y)=>{const v=b[y];if(m.length===0){x.backgroundColor=[...v];return}x.backgroundColor=v.map((C,S)=>m.some(j=>j.datasetIndex===y&&j.dataIndex===S)?C:u(C,.2))});try{h.update()}catch(x){console.warn("Failed to update chart during blur toggle:",x)}}function u(h,m=.2){if(h.startsWith("rgba"))return h.replace(/[\d.]+\)$/g,`${m})`);if(h.startsWith("#")){const p=parseInt(h.slice(1,3),16),g=parseInt(h.slice(3,5),16),b=parseInt(h.slice(5,7),16);return`rgba(${p}, ${g}, ${b}, ${m})`}return h}function d(h,m){var v;if(!o||!m)return;r.current=m;const p=m.getElementsAtEventForMode(h,"nearest",{intersect:!0},!0);if(!p.length)return;const{datasetIndex:g,index:b}=p[0],x={datasetIndex:g,dataIndex:b};if(((v=h.native)==null?void 0:v.shiftKey)||h.shiftKey){const C=t.current.findIndex(S=>S.datasetIndex===g&&S.dataIndex===b);C>=0?t.current.splice(C,1):t.current.push(x)}else{const C=t.current.length===1&&t.current[0].datasetIndex===g&&t.current[0].dataIndex===b;t.current=C?[]:[x]}c({chart:m,selectedSegments:t.current,storedOriginalColorsRef:n})}function f(h){h&&(t.current=[],n.current&&c({chart:h,selectedSegments:[],storedOriginalColorsRef:n}))}return{handleChartClick:d,clearBlur:f}}function Kw(e,t,n){var s;if(!e||!(t!=null&&t.id)||!n)return;const r=(s=n.byFieldId)==null?void 0:s[t.id];if(r){if(r.outputKey&&Object.prototype.hasOwnProperty.call(e,r.outputKey))return e[r.outputKey];if(r.rawKey&&Object.prototype.hasOwnProperty.call(e,r.rawKey))return e[r.rawKey]}}function bWe({resolvedCardConfig:e,card:t,records:n,chart:r,clickEvent:s,columnKeyMap:o}){var d,f,h,m,p,g,b,x,y,v;const i=r==null?void 0:r.getElementsAtEventForMode(s,"nearest",{intersect:!0},!0);if(!i.length)return;const a=i[0].datasetIndex,c=i[0].index,u=(f=(d=i[0].element)==null?void 0:d.$context)==null?void 0:f.raw;console.log("datasetIndex",a),console.log("clickIndex",c),console.log("value",u);try{if(!(n!=null&&n.length))return;const{keys:C}=Qn(n),{groupByColumns:S=[],pivotByColumns:N=[],metricColumns:j=[]}=e||t.config,k=T=>S.find(E=>E.label===T)||N.find(E=>E.label===T)||j.find(E=>E.label===T);if(t.type==="map"){const T=C[0],E=((m=(h=u==null?void 0:u.feature)==null?void 0:h.properties)==null?void 0:m.name)||((g=(p=u==null?void 0:u.feature)==null?void 0:p.properties)==null?void 0:g.NAME),_=S[0]||k(T);return!_||E==null?void 0:{conditions:[{field:_,operator:"=",value:E}]}}if(["pie","funnel","doughnut"].includes(t.type)){const T=C[0],E=C==null?void 0:C[1+a],_=S[0]||k(T),M=j[a]||j[0]||k(E),P=Kw(n==null?void 0:n[c],_,o)??((b=n==null?void 0:n[c])==null?void 0:b[T]),D=Kw(n==null?void 0:n[c],M,o)??u;if(!_||P==null){console.log("no dim field or value",T,P);return}return{conditions:[{field:_,operator:"=",value:P}],metrics:M?[{field:M,value:D}]:void 0}}if(["stackedBar","bar","line"].includes(t.type)){const T=C[0],E=S[0]||k(T),_=Kw(n==null?void 0:n[c],E,o)??((x=n==null?void 0:n[c])==null?void 0:x[T]);if(!E||_==null){console.log("no dim field or value for stacked bar",T,_);return}const M=j[a]||j[0];if(!M){console.log("no metric field found");return}const P=N[0],A=Object.keys(n[0]).filter(R=>R!==T)[a],B=Kw(n==null?void 0:n[c],M,o)??(A?(y=n==null?void 0:n[c])==null?void 0:y[A]:(v=n==null?void 0:n[c])==null?void 0:v[M.label])??u,V=[{field:E,operator:"=",value:_}];return P&&A&&V.push({field:P,operator:"=",value:A}),{conditions:V,metrics:[{field:M,value:B}]}}}catch(C){console.error("getClickContextFromChart error",C)}}function xWe(e){return e&&typeof e=="object"&&"field"in e&&"operator"in e}function yWe(e){return e&&typeof e=="object"&&"filterId"in e&&"operation"in e&&"values"in e}function Yre({filters:e,filterDefinitions:t,contextMode:n,className:r,showLabel:s=!0,labelText:o="Applied Filters:",icon:i}){if(!e||e.length===0)return n==="none"?l.jsx("div",{className:"px-6 pb-4",children:l.jsx("span",{className:"text-xs text-muted-foreground",children:"No filters applied"})}):null;const c=e.map(u=>{var d,f;if(xWe(u))return{fieldName:((d=u.field)==null?void 0:d.label)||((f=u.field)==null?void 0:f.name)||"Unknown",operator:u.operator,value:wWe(u)};if(yWe(u)){const h=t==null?void 0:t.find(m=>m.id===u.filterId);return{fieldName:(h==null?void 0:h.title)||u.name,operator:u.operation,value:vWe(u)}}else return{fieldName:"Unknown",operator:"=",value:String(u)}}).reduce((u,d)=>(u[d.fieldName]||(u[d.fieldName]=[]),u[d.fieldName].push(d),u),{});return l.jsxs("div",{className:r||"border-b px-6 pb-4",children:[l.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s&&i&&l.jsxs("div",{className:"flex items-center gap-2 text-foreground/80",children:[i,l.jsx("span",{className:"whitespace-nowrap text-sm font-medium",children:o})]}),s&&!i&&l.jsx("span",{className:"whitespace-nowrap text-sm text-muted-foreground",children:o}),l.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(c).map(([u,d])=>l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsxs("span",{className:"text-sm font-medium",children:[u,":"]}),d.map((f,h)=>l.jsx(Xe,{variant:"outline",className:"cursor-pointer select-none border-primary/20 bg-gradient-to-r from-primary/5 to-primary/10 text-primary shadow-sm transition-all hover:from-primary/10 hover:to-primary/15 hover:shadow-md dark:border-primary/30 dark:from-primary/10 dark:to-primary/20 dark:text-primary dark:hover:from-primary/15 dark:hover:to-primary/25",children:f.value},`${u}-${h}`))]},u))})]}),n&&l.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:[n==="interactionFilters"&&l.jsx("span",{children:"Showing data filtered by interaction only"}),n==="full"&&l.jsx("span",{children:"Showing data with all dashboard filters + interaction filters"}),n==="none"&&l.jsx("span",{children:"Showing all data (no filters applied)"})]})]})}function vWe(e){const{values:t,operation:n}=e;return!t||t.length===0?"":n==="="||n==="!="||n===">"||n==="<"||n===">="||n==="<="?String(t[0]):n==="in"||n==="not in"?t.map(r=>String(r)).join(", "):(n==="between"||n==="not between")&&t.length===2?`${t[0]} - ${t[1]}`:String(t[0])}function wWe(e){const{operator:t,value:n}=e;if(e.label){const r=e.label.split(/[=><]/);if(r.length>1)return r[1].trim()}switch(t){case"=":return String(n);case"!=":return`≠ ${n}`;case">":return`> ${n}`;case"<":return`< ${n}`;case">=":return`≥ ${n}`;case"<=":return`≤ ${n}`;case"in":return Array.isArray(n)?n.join(", "):String(n);case"not in":return`not ${Array.isArray(n)?n.join(", "):n}`;case"contains":return`contains ${n}`;case"startsWith":return`starts with ${n}`;case"endsWith":return`ends with ${n}`;case"between":return Array.isArray(n)?`between ${n[0]} and ${n[1]}`:String(n);case"not between":return Array.isArray(n)?`not between ${n[0]} and ${n[1]}`:String(n);case"isNull":return"is null";case"isNotNull":return"is not null";default:return String(n)}}function CWe({cardId:e,className:t}){const n=Vt(d=>d.interactionStates[e]),r=Vt(d=>d.popInteractionStep),s=Vt(d=>d.resetInteractionState),o=(n==null?void 0:n.breadcrumbs)??[];if(n==null||n.hierarchyId,o.length===0)return null;const i=d=>{const f=o.length-d-1;for(let h=0;h<f;h++)r(e)},a=()=>{s(e)},c=d=>(d.sourceFilterGroups[0],d.toField?d.toField.label||d.toField.name:"Drill Step"),u=d=>{const f=d.sourceFilterGroups.flatMap(h=>h.filters);return l.jsxs("div",{className:"max-w-xs space-y-2 text-sm",children:[f.length>0&&l.jsx(Yre,{filters:f,className:"pb-2",labelText:"Drill Down Filters:",icon:l.jsx(Ipe,{className:"h-4 w-4 text-foreground/80"})}),d.granularity&&l.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[l.jsx(js,{className:"h-4 w-4 text-foreground/80"}),l.jsxs("span",{className:"text-sm font-medium text-foreground/80",children:["Granularity: ",d.granularity]})]}),d.metric&&l.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[l.jsx(dpe,{className:"h-4 w-4 text-foreground/80"}),l.jsxs("span",{className:"text-sm font-medium text-foreground/80",children:["Value:"," ",d.metric.formattedValue||d.metric.value]})]})]})};return l.jsx(gr,{children:l.jsxs("div",{className:Q("flex items-center gap-1 text-sm",t),children:[l.jsx(wn,{children:l.jsx(Cn,{asChild:!0,children:l.jsx("button",{className:"flex items-center p-0 text-muted-foreground hover:text-foreground",onClick:a,"aria-label":"Reset drill path",children:l.jsx(Kx,{className:"h-3.5 w-3.5"})})})}),l.jsx(ms,{className:"ml-0.5 h-3 w-3 text-muted-foreground"}),l.jsx("div",{className:"flex items-center",children:o.map((d,f)=>l.jsxs("div",{className:"flex items-center",children:[f>0&&l.jsx(ms,{className:"mx-1 h-3 w-3 text-muted-foreground"}),l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(re,{variant:"link",size:"sm",className:"h-6 px-1 text-muted-foreground no-underline hover:text-foreground hover:no-underline",onClick:()=>i(f),"aria-label":`Go back to: ${c(d)}`,children:c(d)})}),l.jsx(Tn,{className:"ml-4",side:"bottom",children:u(d)})]})]},f))})]})})}function Gre(e){var t;if(e&&e.type!=="organization"&&e.type==="tenant")return((t=e.role)==null?void 0:t.toUpperCase())==="VIEWER"?{showFilters:!1}:void 0}function SWe(e){var t;return e?e.type==="organization"?!0:e.type==="tenant"?((t=e.role)==null?void 0:t.toUpperCase())!=="VIEWER":!1:!1}function NWe(e){var t;return e?e.type==="organization"?!0:e.type==="tenant"?((t=e.role)==null?void 0:t.toUpperCase())!=="VIEWER":!1:!1}function jWe(e){return!!e}function EWe(e){var t;return e?e.type==="organization"?!0:e.type==="tenant"?((t=e.role)==null?void 0:t.toUpperCase())!=="VIEWER":!1:!1}function kWe(e){var t;return e?e.type==="organization"?!0:e.type==="tenant"?((t=e.role)==null?void 0:t.toUpperCase())!=="VIEWER":!1:!1}function TWe(e){var t;return e?e.type==="organization"?!0:e.type==="tenant"?((t=e.role)==null?void 0:t.toUpperCase())==="POWER_USER":!1:!1}function _We(e){switch(e){case"print":return{showHeader:!0,showTitle:!0,showDescription:!0,showTabs:!1,showFilters:!1,showBreadcrumbs:!1,showRefreshIndicator:!1,showFilterInfo:!1,showTableToolbar:!1,showColumnSettings:!1};case"table-print":return{showHeader:!1,showTitle:!0,showDescription:!1,showTabs:!1,showFooter:!1,showFilters:!1,showBreadcrumbs:!1,showRefreshIndicator:!1,showFilterInfo:!1,showPagination:!1,showTableToolbar:!1,showColumnSettings:!1};case"full":default:return{showHeader:!0,showTitle:!0,showDescription:!0,showTabs:!0,showFooter:!0,showFilters:!0,showBreadcrumbs:!0,showRefreshIndicator:!0,showFilterInfo:!0}}}function GO({children:e,displayPreferences:t={mode:"full"},currentUser:n}){const r=w.useMemo(()=>{const s=t.mode||"full",o=_We(s),i=Gre(n||null),a={mode:s,overrides:{...o,...i,...t.overrides}};return{displayPreferences:a,shouldShowElement:u=>{var d;return((d=a.overrides)==null?void 0:d[u])??!0}}},[t,n]);return l.jsx($Y.Provider,{value:r,children:e})}function Kre({card:e,sheetId:t,inlineFilterValues:n,setInlineFilterValue:r,removeInlineFilterValue:s}){const o=e.inlineFilters,i=ee(c=>c.inlineFilterValuesMap[e.id]),a=n??i;return!o||o.length===0?null:l.jsx("div",{className:"flex flex-wrap items-start gap-2",children:o.map(c=>l.jsx(Zne,{inlineFilter:c,sheetId:t,cardId:e.id,inlineFilterValues:a,setInlineFilterValue:r,removeInlineFilterValue:s},c.id))})}const IWe={value:Tc.CONTROL_CARD_DEFAULT_VALUE,label:"Current card setup"};function fv(e){return e?u8e({sql:e.sql,controlBindings:e.controlBindings}):[]}function MWe(e){if(!e)return!1;const t=new Set(fv(e));return(e.controls||[]).some(n=>!n.hidden&&t.has(n.id))}function DWe(e){return e.controls||[]}function Ay(e){return e.placement?e.placement:e.scope==="dashboard"?"toolbar":"card_header"}function AWe(e){switch(e.source.kind){case"manual":return e.source.options;case"field_allowlist":return e.source.fieldIds.map(t=>({value:t,label:t}));case"metric_allowlist":return e.source.metricIds.map(t=>({value:t,label:t}));case"dataset_values":return[];default:return[]}}function RWe(e){return e.type==="enum"||e.type==="field_selector"||e.type==="metric_selector"||e.type==="aggregation_selector"||e.type==="grain_selector"}function Zw(e,t){return t==null?"":e.type==="date"&&t instanceof Date?t.toISOString().slice(0,10):String(t)}function XM({control:e,value:t,disabled:n=!1,onChange:r,className:s,showLabel:o=!0,density:i="default"}){var T;const a=o?"":"w-full min-w-0",c=i==="compact",u=c?"h-8":"h-9",d=c?"h-8":"h-9",f=c?"gap-0.5":"gap-1",h="focus:ring-0 focus:ring-offset-0 focus:border-input focus-visible:ring-0 focus-visible:ring-offset-0 focus-visible:border-input",m=ee(E=>E.themeStyle),p=(m==null?void 0:m.controlInputRadius)??(m==null?void 0:m.cardBorderRadius)??6,g=w.useMemo(()=>AWe(e),[e]),b=w.useMemo(()=>!(t===Tc.CONTROL_CARD_DEFAULT_VALUE||e.defaultValue===Tc.CONTROL_CARD_DEFAULT_VALUE)||g.some(_=>_.value===Tc.CONTROL_CARD_DEFAULT_VALUE)?g:[IWe,...g],[g,e.defaultValue,t]),x=n||e.locked===!0,y=!e.requiredAtExecution&&!x,v=t!=null&&(!Array.isArray(t)||t.length>0),[C,S]=w.useState(()=>Zw(e,t));w.useEffect(()=>{S(Zw(e,t))},[e,t]);const N=e.helpText||e.label;if(RWe(e))return l.jsxs("div",{className:Q(o?`flex min-w-[160px] flex-col ${f}`:`flex flex-col ${f}`,a,s),title:N,children:[o?l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx(ge,{className:"text-xs font-medium text-muted-foreground",children:e.label}),y&&v?l.jsx(re,{type:"button",variant:"ghost",className:"h-auto px-0 py-0 text-xs text-muted-foreground",onClick:()=>r(void 0),children:"Clear"}):null]}):null,l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs(pt,{value:typeof t=="string"?t:void 0,onValueChange:E=>r(E),disabled:x||b.length===0,children:[l.jsx(ft,{className:Q(u,h,"shadow-sm"),style:{borderRadius:p},children:l.jsx(gt,{placeholder:b.length===0?"No options":"Select"})}),l.jsx(ht,{children:b.map(E=>l.jsx(Ie,{value:E.value,children:E.label},E.value))})]}),!o&&y&&v?l.jsx(re,{type:"button",variant:"ghost",className:Q(d,"shrink-0 px-2 text-xs text-muted-foreground"),onClick:()=>r(void 0),children:"Clear"}):null]})]});if(e.type==="multi_enum"){const E=Array.isArray(t)?t.filter(M=>typeof M=="string"):[],_=E.length===0?"Select":E.length===1?((T=b.find(M=>M.value===E[0]))==null?void 0:T.label)||E[0]:`${E.length} selected`;return l.jsxs("div",{className:Q(o?`flex min-w-[180px] flex-col ${f}`:`flex flex-col ${f}`,a,s),title:N,children:[o?l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx(ge,{className:"text-xs font-medium text-muted-foreground",children:e.label}),y&&v?l.jsx(re,{type:"button",variant:"ghost",className:"h-auto px-0 py-0 text-xs text-muted-foreground",onClick:()=>r(void 0),children:"Clear"}):null]}):null,l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs(Gr,{children:[l.jsx(Kr,{asChild:!0,children:l.jsx(re,{type:"button",variant:"outline",className:Q(u,h,"w-full justify-between shadow-sm"),style:{borderRadius:p},disabled:x||b.length===0,children:l.jsx("span",{className:"truncate",children:_})})}),l.jsx(Zr,{align:"start",className:"w-64",children:l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("p",{className:"text-sm font-medium",children:e.label}),e.helpText&&l.jsx("p",{className:"text-xs text-muted-foreground",children:e.helpText})]}),l.jsx("div",{className:"space-y-2",children:b.map(M=>{const P=E.includes(M.value);return l.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[l.jsx(Jt,{checked:P,disabled:x||P&&E.length===1&&e.requiredAtExecution,onCheckedChange:D=>{if(D){r([...E,M.value]);return}E.length===1&&e.requiredAtExecution||r((()=>{const A=E.filter(L=>L!==M.value);return A.length===0&&!e.requiredAtExecution?void 0:A})())}}),l.jsx("span",{children:M.label})]},M.value)})})]})})]}),!o&&y&&v?l.jsx(re,{type:"button",variant:"ghost",className:Q(d,"shrink-0 px-2 text-xs text-muted-foreground"),onClick:()=>r(void 0),children:"Clear"}):null]})]})}if(e.type==="boolean")return t===void 0&&e.requiredAtExecution?l.jsxs("div",{className:Q("flex min-w-[180px] items-center justify-between gap-3 rounded-md border bg-background px-3",c?"py-1.5":"py-2",s),style:{borderRadius:p},title:N,children:[o?l.jsxs("div",{className:"min-w-0",children:[l.jsx(ge,{className:"text-xs font-medium text-muted-foreground",children:e.label}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Choose true or false"})]}):l.jsx("div",{className:"min-w-0 text-[11px] text-muted-foreground",children:"Choose true or false"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(re,{type:"button",size:"sm",variant:"outline",className:h,style:{borderRadius:p},disabled:x,onClick:()=>r(!0),children:"True"}),l.jsx(re,{type:"button",size:"sm",variant:"outline",className:h,style:{borderRadius:p},disabled:x,onClick:()=>r(!1),children:"False"})]})]}):l.jsxs("div",{className:Q(o?"flex min-w-[180px] items-center justify-between gap-3 rounded-md border bg-background px-3":"flex items-center justify-between gap-3 rounded-md border bg-background px-3",c?"py-1.5":"py-2",a,s),style:{borderRadius:p},title:N,children:[o?l.jsxs("div",{className:"min-w-0",children:[l.jsx(ge,{className:"text-xs font-medium text-muted-foreground",children:e.label}),e.helpText&&l.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:e.helpText})]}):null,l.jsxs("div",{className:"flex items-center gap-2",children:[y&&v?l.jsx(re,{type:"button",variant:"ghost",className:"h-auto px-0 py-0 text-xs text-muted-foreground",onClick:()=>r(void 0),children:"Clear"}):null,l.jsx(gh,{className:"focus-visible:ring-0",checked:!!t,disabled:x,onCheckedChange:E=>r(E)})]})]});const j=e.type==="number"?"number":e.type==="date"?"date":"text",k=()=>{const E=C.trim();if(E.length===0){if(!e.requiredAtExecution){r(void 0),S("");return}S(Zw(e,t));return}if(e.type==="number"){const _=Number(E);if(!Number.isNaN(_)){r(_);return}S(Zw(e,t));return}r(E)};return l.jsxs("div",{className:Q(o?`flex min-w-[160px] flex-col ${f}`:`flex flex-col ${f}`,a,s),title:N,children:[o&&l.jsx(ge,{className:"text-xs font-medium text-muted-foreground",children:e.label}),l.jsx(lt,{type:j,value:C,disabled:x,className:Q(u,h,"shadow-sm"),style:{borderRadius:p},onChange:E=>S(E.target.value),onBlur:k,onKeyDown:E=>{E.key==="Enter"&&k()}})]})}function Zre({title:e="Controls",controls:t,values:n,onChange:r,immediatePlacement:s,advancedLabel:o="More controls",density:i="default"}){const a=e||"Card controls",c=t.filter(f=>!f.hidden),u=c.filter(f=>Ay(f)===s),d=c.filter(f=>Ay(f)==="advanced");return u.length===0&&d.length===0?null:l.jsxs("div",{className:Q("flex min-w-0 flex-wrap items-start",i==="compact"?"gap-2":"gap-3"),children:[e?l.jsx("div",{className:Q("flex items-center",i==="compact"?"h-8":"h-9"),children:l.jsx(ge,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:e})}):null,u.map(f=>l.jsx(XM,{control:f,value:n==null?void 0:n[f.id],onChange:h=>r(f,h),density:i},f.id)),d.length>0&&l.jsxs(Gr,{children:[l.jsx(Kr,{asChild:!0,children:l.jsxs(re,{type:"button",variant:"outline",className:Q(i==="compact"?"h-8 gap-1.5":"h-9 gap-2"),children:[l.jsx(gl,{className:"h-4 w-4"}),o]})}),l.jsx(Zr,{align:"start",className:"w-80",children:l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("p",{className:"text-sm font-medium",children:a}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls that are available behind one more click."})]}),l.jsx("div",{className:"grid gap-3",children:d.map(f=>l.jsx(XM,{control:f,value:n==null?void 0:n[f.id],onChange:h=>r(f,h),density:i},f.id))})]})})]})]})}function FWe({card:e}){const t=ee(o=>o.cardControlValuesMap[e.id]),{setCardControlValue:n}=en(),r=new Set(fv(e)),s=(e.controls||[]).filter(o=>r.has(o.id));return s.length===0?null:l.jsx(Zre,{title:"",controls:s,values:t,onChange:(o,i)=>n(e.id,o.id,i),immediatePlacement:"card_header",advancedLabel:"More options",density:"compact"})}function QM({card:e,mode:t="dashboard"}){const{authToken:n}=rt(),{data:r,isLoading:s,isRefreshing:o,enabled:i,refresh:a,applyAction:c}=FO(e),[u,d]=w.useState(t==="editor");if(w.useEffect(()=>{d(t==="editor")},[t]),!i)return null;if(s&&!r)return l.jsxs("div",{className:"rounded-md border bg-muted/20 p-3",children:[l.jsx("div",{className:"mb-2 h-3 w-20 animate-pulse rounded bg-muted"}),l.jsx("div",{className:"h-3 w-4/5 animate-pulse rounded bg-muted"})]});if(!r)return null;const f=xS({card:e,accessToken:n==null?void 0:n.accessToken}),h=r.metadata.warnings.length,m=h>0,p=r.metadata.partial||m,g={narrative:r.narrative,generatedAt:r.generatedAt,keyChanges:r.keyChanges,drivers:r.drivers,anomalies:r.anomalies,suggestedActions:r.suggestedActions,metadata:r.metadata};return t==="editor"?l.jsxs("div",{className:"rounded-md border border-border bg-card",children:[l.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[l.jsx("div",{className:"min-w-0 flex-1",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Summary"}),r.metadata.partial&&l.jsx("span",{className:"rounded bg-amber-100 px-1.5 py-0.5 text-[10px] font-medium text-amber-800",children:"Partial"}),m&&l.jsxs("span",{className:"rounded bg-amber-100 px-1.5 py-0.5 text-[10px] font-medium text-amber-800",children:[h," warning",h>1?"s":""]})]})}),l.jsx(re,{size:"icon",variant:"ghost",className:"size-6 shrink-0",onClick:()=>a(),disabled:o,"aria-label":"Refresh summary",children:l.jsx(cC,{className:Q("h-3.5 w-3.5",o&&"animate-spin")})})]}),l.jsx("div",{className:"border-t border-border px-3 py-3",children:l.jsx(Iy,{data:g,applyAction:c,audience:"author",numberFormatter:f})})]}):l.jsxs("div",{className:"rounded-md border border-border bg-card",children:[l.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[l.jsx(re,{size:"icon",variant:"ghost",className:"size-6 shrink-0",onClick:()=>d(b=>!b),"aria-label":u?"Collapse summary":"Expand summary",children:l.jsx(pr,{className:Q("h-4 w-4 transition-transform",!u&&"-rotate-90")})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Summary"}),p&&l.jsx(OO,{className:"text-amber-500"})]}),l.jsx("p",{className:"truncate text-xs text-muted-foreground",children:r.narrative})]}),l.jsx(re,{size:"icon",variant:"ghost",className:"size-6 shrink-0",onClick:()=>a(),disabled:o,"aria-label":"Refresh summary",children:l.jsx(cC,{className:Q("h-3.5 w-3.5",o&&"animate-spin")})})]}),u&&l.jsx("div",{className:"border-t border-border px-3 py-3",children:l.jsx("div",{className:"max-h-56 overflow-y-auto pr-1",children:l.jsx(Iy,{data:g,applyAction:c,audience:"dashboard",numberFormatter:f})})})]})}function Xre({cardId:e}){const t=MF(e);if(t.length===0)return null;const n=t.filter(r=>{var s;return((s=r.alertState)==null?void 0:s.currentState)==="FIRING"}).length;return l.jsxs(wn,{children:[l.jsx(Cn,{asChild:!0,children:l.jsxs(re,{type:"button",variant:"ghost",size:"icon",className:"relative h-6 w-6 text-muted-foreground","aria-label":`${t.length} signal watch${t.length===1?"":"es"}${n>0?`, ${n} currently surfaced`:""}`,children:[l.jsx(Fm,{className:"h-4 w-4"}),n>0?l.jsx("span",{className:"absolute -right-1 -top-1 h-2.5 w-2.5 rounded-full bg-destructive"}):null]})}),l.jsx(Tn,{side:"top",align:"center",children:l.jsxs("p",{className:"text-xs",children:[t.length," signal watch",t.length===1?"":"es"," attached",n>0?`, ${n} surfaced`:""]})})]})}function PWe({canEditDashboard:e,isDashboardEditing:t,isMissingConnection:n,onConfigure:r}){return l.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-4 text-center",children:[l.jsx("div",{className:"rounded-full border border-border bg-muted/40 p-3",children:l.jsx(Ope,{className:"size-6 text-muted-foreground","aria-hidden":!0})}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("h3",{className:"text-sm font-semibold",children:"Set up this visual"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:n?"Choose a data source to begin.":"Add fields or SQL to show data."})]}),e?l.jsx(re,{type:"button",size:"sm",className:"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",onClick:r,children:t?"Configure visual":"Edit visual"}):l.jsx("p",{className:"text-xs text-muted-foreground",children:"You don't have permission to configure this visual."})]})}function OWe(e,t,n){const r=fl(e)==="dynamic",s=r?Wx(e):e,{data:o}=$0(s),i=w.useMemo(()=>(t==null?void 0:t.records)||[],[t==null?void 0:t.records]),a=w.useMemo(()=>{var d;return s.type!=="pivotTable"||!((d=t==null?void 0:t.records)!=null&&d.length)?null:{records:t.records,columnSubtotalMeta:t.columnSubtotalMeta,subtotalColumns:t.subtotalColumns||[],pivotSchema:t.pivotSchema||[],groupByColumns:t.groupByColumns}},[s.type,t==null?void 0:t.records,t==null?void 0:t.columnSubtotalMeta,t==null?void 0:t.subtotalColumns,t==null?void 0:t.pivotSchema,t==null?void 0:t.groupByColumns]),c=Ig(s,a),u=w.useMemo(()=>{var d;if(!(!((d=t==null?void 0:t.records)!=null&&d.length)||["kpi","text","table","detailTable","pivotTable","aggregateTable","custom"].includes(s.type)))return xg({card:s,data:t.records,cardType:s.type,queryConfig:s.queryConfig,customCfg:s.customCfg,preferences:s.preferences,topoJson:o})},[s,o,t==null?void 0:t.records,n]);return{isDynamicVisualizationMode:r,fallbackCard:s,tableRecords:i,pivotTableConfig:c,fallbackCfg:u}}const LWe=[];function e9({card:e,frame:t}){var Nr,Jr,ei,go,Ha,nu,yt,xe,he,Le,ut,It,zt,bn,cr,bo;const{customCards:n,placeholders:r,tokenProps:s}=rt(),{shouldShowElement:o}=Kc(),i=ee(Fe=>Fe.themeStyle),a=ee(Fe=>Fe.dashboard),c=ee(Fe=>Fe.selectedSheetId),u=ee(Fe=>Fe.isDashboardEditing);ee(Fe=>Fe.selectedLensId);const d=ee(Fe=>Fe.dashboard.filters),f=ee(Fe=>Fe.filterValues),h=ee(Fe=>Fe.inlineFilterValuesMap),m=Ve(Fe=>Fe.selectedConnectionId),p=Ve(Fe=>Fe.selectedDatabaseName),g=Ve(Fe=>Fe.selectedSchemaName),b=Ve(Fe=>Fe.selectedTableName),x=Ve(Fe=>Fe.selectedDatamodelId),y=TO(t,e),{manifest:v}=$h(((Nr=y==null?void 0:y.customCardPreferences)==null?void 0:Nr.url)||""),C=(Jr=v==null?void 0:v.visuals)==null?void 0:Jr.find(Fe=>{var Nt;return Fe.name===((Nt=y==null?void 0:y.customCardPreferences)==null?void 0:Nt.componentName)}),S=cv(y,C)==="multiple",N=S&&y?y:e,j=fl(N)==="dynamic",k=j?Wx(N):N,T=Vt(Fe=>Fe.interactionStates[N.id]),E=((ei=T==null?void 0:T.breadcrumbs)==null?void 0:ei.length)>0,_=ee(Fe=>Fe.inlineFilterValuesMap[N.id]),M=d==null?void 0:d.find(Fe=>Fe.id===t.filterId&&!Fe.hide),{clearSelectedVisual:P}=Jp(),D=bs(Fe=>Fe.selectedDashboard),A=bs(Fe=>Fe.initialDashboard),L=D?(Ha=D==null?void 0:D.permissions)==null?void 0:Ha.canEdit:(go=A==null?void 0:A.permissions)==null?void 0:go.canEdit,{setSelectedFrameId:$,updateFilter:B,updateFrame:V,setIsDashboardEditing:R,setIsVisualEditing:U}=en(),{handleChartClick:O}=gWe(N),{setCard:I,setFrame:W,setQueryResultColumns:X,setActiveTabCardId:Z,setIsDevMode:H,initializeModeDrafts:K,updateDataSource:z}=lr(),q=Ve(Fe=>Fe.actions.setSelectedConnectionId),Y=Ve(Fe=>Fe.actions.setSelectedDatamodelId),G=Ve(Fe=>Fe.actions.setSelectedDatabaseName),J=Ve(Fe=>Fe.actions.setSelectedSchemaName),ne=Ve(Fe=>Fe.actions.setSelectedTableName),be=Ve(Fe=>Fe.actions.setFilterValues),te=Ve(Fe=>Fe.actions.setInlineFilterValuesMap),ce=Ve(Fe=>Fe.actions.setApplyFilters),se=o("showHeader")&&(((nu=N.customCardPreferences)==null?void 0:nu.showCardHeader)??!0),ue=w.useMemo(()=>S&&N?{...N,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:N,[N,S]),Re=!(N.connectionId||(yt=N.dataSource)!=null&&yt.connectionId),je=!!(n!=null&&n.find(Fe=>Fe.cardId===e.id&&!!Fe.content)),ke=hhe(N,{skipSetupCheck:S&&!!y||je});function me(){L&&($(t.id),P(),SP({frame:t,card:e,setFrame:W,setCard:I,setIsDevMode:H,initializeModeDrafts:K,setActiveTabCardId:Z,updateDataSource:z,setQueryResultColumns:X,setSelectedConnectionId:q,setSelectedDatabaseName:G,setSelectedSchemaName:J,setSelectedTableName:ne,setSelectedDatamodelId:Y,setFilterValues:be,setInlineFilterValuesMap:te,setApplyFilters:ce,setIsDashboardEditing:R,setIsVisualEditing:U,dashboard:a,selectedSheetId:c,selectedFrameId:t.id,filterValues:f,inlineFilterValuesMap:h,currentSelections:{connectionId:m,databaseName:p,schemaName:g,tableName:b,datamodelId:x}}))}const{isError:Me,isLoading:Se,isFetching:ie,isPending:pe,data:Ne,handleDatapointClick:de,pagination:fe,comparisonMetadata:Oe}=z0(ue),{tableRecords:ye,pivotTableConfig:Ce,fallbackCfg:$e}=OWe(k,Ne,i),[ze,Ge]=w.useState({open:!1,position:null,interactions:[],context:null}),{breadcrumbs:Ke,hierarchyId:Ze}=Vt(Kp(Fe=>{var Nt,En;return{breadcrumbs:((Nt=Fe.interactionStates[N.id])==null?void 0:Nt.breadcrumbs)??LWe,hierarchyId:(En=Fe.interactionStates[N.id])==null?void 0:En.hierarchyId}})),st=(Fe,Nt,En)=>{var nr;const tn=Ke.length>0?[{mode:"drillUp",trigger:(nr=Fe[0])==null?void 0:nr.trigger,label:"Drill Up",hierarchyId:Ze}]:[],vt=[];for(const Ur of Fe)if(Ur.mode==="dynamicDrill"&&Ur.availableFields){const Rs=Ur.availableFields.filter(Zl=>!Ke.some(HE=>{var Iv;return((Iv=HE.toField)==null?void 0:Iv.id)===Zl.id}));for(const Zl of Rs)vt.push({mode:"dynamicDrill",trigger:Ur.trigger,drillField:Zl,label:Zl.label,availableFields:Ur.availableFields})}const Kn=Fe.filter(Ur=>Ur.mode!=="dynamicDrill"),tr=[...tn,...Kn,...vt];Ge({open:!0,position:En||{x:0,y:0},interactions:tr,context:Nt})},ae=N,{handlePointerInteraction:Pe,applySelectedInteraction:Ee}=d7(ae,t.id,c||"",st),_e=XD(ae),We=(Fe,Nt)=>{const En={...e,paginationConfig:{page:Fe+1,pageSize:Nt}},tn={...t,cards:t.cards.map(vt=>vt.id===e.id?En:vt)};c&&V(c,tn)},Te=Fe=>{var vt,Kn,tr;const Nt=Eee(Fe,(vt=e.config)==null?void 0:vt.metricColumns,(Kn=e.config)==null?void 0:Kn.groupByColumns,(tr=e.config)==null?void 0:tr.detailColumns),En={...e,config:{...e.config||{},sortByColumns:Nt}},tn={...t,cards:t.cards.map(nr=>nr.id===e.id?En:nr)};c&&V(c,tn)};function Ue(Fe,Nt){Fe.stopPropagation();const En=bWe({resolvedCardConfig:_e,card:ae,records:(Ne==null?void 0:Ne.records)||[],chart:Nt,clickEvent:Fe.nativeEvent,columnKeyMap:Ne==null?void 0:Ne.columnKeyMap});if(!En)return;const tn=gc(ae.interactionConfig),vt=eN(tn,En),Kn=vt.length===1&&vt[0].mode==="clickFilter",tr=vt.some(Rs=>Rs.mode==="dynamicDrill"),nr=vt.length>1||tr;Fe.button===0&&Kn&&!nr&&O(Fe.nativeEvent,Nt);const Ur={shift:Fe.shiftKey,ctrl:Fe.ctrlKey,meta:Fe.metaKey};Fe.button===0?Pe({context:En,gesture:"leftClick",modifierKeys:Ur,position:{x:Fe.clientX,y:Fe.clientY}}):Fe.button===2&&Pe({context:En,gesture:"rightClick",modifierKeys:Ur,position:{x:Fe.clientX,y:Fe.clientY}})}function et(){var Fe,Nt,En;if(S&&y)return pn;if(n&&n.length>0){const tn=n.find(vt=>vt.cardId===e.id);if(tn&&tn.replaceDefault){const vt=tn.content;if(vt)return l.jsx(vt,{card:e})}}if(!j&&e.type==="kpi"){if(((Fe=t==null?void 0:t.cards)==null?void 0:Fe.length)===1)return l.jsx(ph,{card:e,data:Me?[]:(Ne==null?void 0:Ne.records)||[],isPending:pe,isError:Me,comparisonMetadata:Oe});if(((Nt=t==null?void 0:t.cards)==null?void 0:Nt.length)>1)return l.jsx(Q8,{frame:t})}return!j&&e.type==="text"&&((En=t==null?void 0:t.cards)==null?void 0:En.length)===1?l.jsx(Fo,{className:"my-4 overflow-y-auto break-words px-4",children:l.jsx($p,{isLoading:Se||ie,card:e,data:(Ne==null?void 0:Ne.records)||[]})}):pn}function bt(){const Fe=k;if(S&&y)return l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(Ra,{FallbackComponent:My,children:l.jsx(mS,{frame:t,card:y})})});if(ke)return l.jsx(PWe,{canEditDashboard:!!L,isDashboardEditing:u,isMissingConnection:Re,onConfigure:me});if(Me)return l.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[l.jsx(GA,{className:"size-8 text-destructive"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Error fetching data. Check your card settings."})]});if((Se||ie)&&(!(Ne!=null&&Ne.records)||Ne.records.length===0))return e.type==="table"||e.type==="detailTable"?l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(Wre,{})}):l.jsx("div",{className:"flex h-full w-full items-center justify-center",children:l.jsx(ad,{size:"md",color:"muted","aria-label":"Loading data"})});if(Ne!=null&&Ne.records&&Ne.records.length===0&&!j)return r!=null&&r.NoRecords?l.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:r.NoRecords}):l.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[l.jsx(JA,{className:"size-8 text-muted-foreground"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});function Nt(){var En,tn,vt;if(Fe.type==="kpi"){if(((En=t==null?void 0:t.cards)==null?void 0:En.length)===1)return l.jsx(ph,{card:Fe,data:Me?[]:(Ne==null?void 0:Ne.records)||[],isPending:pe,isError:Me,comparisonMetadata:Oe});if(((tn=t==null?void 0:t.cards)==null?void 0:tn.length)>1)return l.jsx(Q8,{frame:t})}if(Fe.type==="table"||Fe.type==="detailTable")return l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(hh,{card:Fe,data:ye,comparisonMetadata:Oe,paginationMetadata:fe,onPaginationChange:We,onSortChange:Te,isLoading:Se||ie,frameId:t.id,sheetId:c||"",onMultipleInteractions:st})});if(Fe.type==="pivotTable"&&Ce)return l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(dv,{card:Fe,data:Ce.data,options:Ce.options,onAggregationChange:Kn=>{const tr=ZM(Kn,e.config),nr={...e,config:tr},Ur={...t,cards:t.cards.map(Rs=>Rs.id===e.id?nr:Rs)};c&&V(c,Ur)},onAggregationLabelChange:Kn=>{const tr=qre(Kn,e.config),nr={...e,config:tr},Ur={...t,cards:t.cards.map(Rs=>Rs.id===e.id?nr:Rs)};c&&V(c,Ur)}})});if(Fe.type==="aggregateTable")return l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(Yj,{card:Fe,data:(Ne==null?void 0:Ne.records)||[],groupByColumns:Ne==null?void 0:Ne.groupByColumns,pivotSchema:Ne==null?void 0:Ne.pivotSchema,paginationMetadata:fe,onPaginationChange:We,onAggregationChange:Kn=>{const tr=ZM(Kn,e.config),nr={...e,config:tr},Ur={...t,cards:t.cards.map(Rs=>Rs.id===e.id?nr:Rs)};c&&V(c,Ur)},isLoading:Se||ie})});if(Fe.type==="text")return l.jsx(Fo,{className:"overflow-y-auto break-words pr-2",children:l.jsx($p,{isLoading:Se||ie,card:Fe,data:(Ne==null?void 0:Ne.records)||[]})});if(aN(Fe)&&((vt=Fe.customCardPreferences)!=null&&vt.url))return l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(Ra,{FallbackComponent:My,children:l.jsx(mS,{frame:t,card:Fe})})});if(n&&n.length>0){const Kn=n.find(tr=>tr.cardId===Fe.id);if(Kn&&Kn.content){const tr=Kn.content;return l.jsx(tr,{card:Fe})}}return $e?l.jsx(ev,{cfg:$e,onChartClick:Ue,onDatapointClick:de}):null}return j?l.jsx(aE,{card:N,records:ye,title:N.title,sql:N.sql,python:N.python,layoutMode:"fill",disablePointerEvents:u,fallback:Nt()}):Nt()}function dt(){if(n&&n.length>0){const Fe=n.find(Nt=>Nt.cardId===e.id);if(Fe&&Fe.footer){const Nt=Fe.footer;if(Nt)return l.jsx(Nt,{card:e})}}return null}function St(){var En;if(S&&y)return null;const Fe=t.cards.filter(tn=>{var vt;return!((vt=tn.tabTitle)!=null&&vt.endsWith("__Header"))&&(tn.displayTab===!0||tn.displayTab===void 0)}),Nt=i==null?void 0:i.controlInputRadius;return l.jsx(As,{value:t.activeCardId,className:"flex items-center justify-end gap-3",onValueChange:tn=>{const vt={...t,activeCardId:tn};V(c,vt)},children:l.jsx(ys,{style:{borderRadius:i==null?void 0:i.controlInputRadius},className:"flex-end flex h-9 flex-wrap items-center border border-border bg-background p-0",children:(En=t.cards.filter(tn=>{var vt;return!((vt=tn.tabTitle)!=null&&vt.endsWith("__Header"))&&(tn.displayTab===!0||tn.displayTab===void 0)}))==null?void 0:En.map((tn,vt)=>l.jsx(on,{className:Q("h-full items-center rounded-none data-[state=active]:bg-muted data-[state=active]:shadow-none",{"border-r":vt!==Fe.length-1}),style:{borderTopLeftRadius:vt===0?Nt:0,borderTopRightRadius:vt===Fe.length-1?Nt:0,borderBottomLeftRadius:vt===0?Nt:0,borderBottomRightRadius:vt===Fe.length-1?Nt:0},value:tn.id,children:tn.tabTitle||tn.title},tn.id))})})}function Ot(){var Nt,En,tn,vt,Kn,tr;let Fe=t.cards.find(nr=>nr.type==="kpi"&&nr.tabTitle===`${e.tabTitle}__Header`);return Fe||(Fe=t.cards.find(nr=>nr.type==="kpi"&&nr.tabTitle==="All__Header")),Fe?l.jsx("div",{className:"flex items-end gap-2",children:l.jsx(uWe,{renderFilterInfo:()=>{var nr,Ur,Rs,Zl;return o("showFilterInfo")&&((Ur=(nr=N.preferences)==null?void 0:nr.displayOptions)==null?void 0:Ur.showFilterInfo)!==!1?l.jsx(KM,{cardId:N.id,cardFilters:(Rs=N.config)==null?void 0:Rs.filters,cardFilterCount:wS(((Zl=N.config)==null?void 0:Zl.filters)||null),inlineFilters:N.inlineFilters,inlineFilterValues:_,sheetId:c||""}):null},card:Fe})}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{role:"card-title-container",className:"flex h-7 items-center gap-2",children:[o("showTitle")&&l.jsx(ja,{className:Q("text-base",{}),children:l.jsx(Ui,{value:N.title,onSave:()=>{},isEditable:!1,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),o("showTitle")&&((Nt=N.info)==null?void 0:Nt.trim())&&l.jsx(YO,{card:N}),o("showTitle")&&l.jsx(Xre,{cardId:N.id}),o("showRefreshIndicator")&&N.refreshInterval&&l.jsxs(wn,{children:[l.jsx(Cn,{className:"pr-1",children:l.jsx("div",{className:Q("h-2 w-2 rounded-full bg-green-500 transition-opacity",{"opacity-10":Se||ie})})}),l.jsx(Tn,{side:"right",align:"center",children:l.jsx("p",{className:"text-xs",children:`Realtime (${N==null?void 0:N.refreshInterval})`})})]}),o("showFilterInfo")&&((tn=(En=N.preferences)==null?void 0:En.displayOptions)==null?void 0:tn.showFilterInfo)!==!1&&l.jsx(KM,{cardId:N.id,cardFilters:(vt=N.config)==null?void 0:vt.filters,cardFilterCount:wS(((Kn=N.config)==null?void 0:Kn.filters)||null),inlineFilters:N.inlineFilters,inlineFilterValues:_,sheetId:c||""}),Oe&&N.type!=="table"&&l.jsx(wee,{metadata:Oe,variant:"compact"})]}),l.jsxs("div",{"data-content":"card-description-and-breadcrumb",className:"flex h-6 items-center overflow-y-auto",children:[!E&&o("showDescription")&&((tr=N.description)==null?void 0:tr.trim())&&l.jsx("div",{className:Q("text-sm text-muted-foreground",{}),children:l.jsx(Ui,{value:(N.description||"").trim(),onSave:()=>{},isEditable:!1,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})}),E&&o("showBreadcrumbs")&&l.jsx(CWe,{cardId:N.id})]})]})}if(!e.id)return null;const xt=((he=(xe=N.preferences)==null?void 0:xe.displayOptions)==null?void 0:he.showChrome)??!0,an=((ut=(Le=N.preferences)==null?void 0:Le.displayOptions)==null?void 0:ut.allowScroll)??!0,Tt=((zt=(It=N.preferences)==null?void 0:It.displayOptions)==null?void 0:zt.showInlineFilterBar)??!0,ve=MWe(N),nt=RO(N),ct=xt?"px-6 pb-3":"px-3 pb-3",pn=xt?l.jsxs(l.Fragment,{children:[se?l.jsx(Na,{className:N.inlineFilters&&N.inlineFilters.length>0?"pb-3":"",children:l.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[l.jsx("div",{className:"flex-1 basis-0 scroll-pb-2 overflow-x-auto",role:"header-container",children:Ot()}),l.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[l.jsx("div",{children:M&&o("showFilters")&&l.jsxs("div",{style:{borderRadius:(cr=(bn=i==null?void 0:i.chart)==null?void 0:bn.options)==null?void 0:cr.borderRadius},"data-content":"frame-filter-container",className:"flex shrink-0 items-center",children:[!Ca(M.dataType)&&l.jsx(ge,{className:"my-1 shrink-0 px-3",children:l.jsx(Ui,{value:M.title||M.column,onSave:Fe=>B({...M,title:Fe}),isEditable:u,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),l.jsx(Vg,{filter:M})]})}),t.cards.length>1&&o("showTabs")&&St()]})]})}):l.jsx("div",{className:"h-8"}),(ve||Tt&&N.inlineFilters&&N.inlineFilters.length>0)&&l.jsx("div",{className:"px-6 pb-2",children:l.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[Tt&&N.inlineFilters&&N.inlineFilters.length>0&&l.jsx(Kre,{card:N,sheetId:c||""}),ve&&l.jsx(FWe,{card:N})]})}),l.jsx(Ea,{"data-role":"card-content",className:"relative flex min-h-0 grow flex-col",children:bt()}),nt&&e.type!=="kpi"&&l.jsx("div",{className:ct,children:l.jsx(QM,{card:N,mode:"dashboard"})}),o("showFooter")&&l.jsx(EU,{children:dt()})]}):l.jsxs(l.Fragment,{children:[bt(),nt&&e.type!=="kpi"&&l.jsx("div",{className:ct,children:l.jsx(QM,{card:N,mode:"dashboard"})})]}),Qr=()=>xt&&an?"flex h-full flex-col":xt&&!an?"flex h-full flex-col overflow-hidden":!xt&&!an?"h-full":"h-full overflow-auto";return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"relative h-full",children:[l.jsx("div",{className:Q(Qr(),{"animate-pulse":Se||ie}),children:et()}),(Se||ie)&&(Ne==null?void 0:Ne.records)&&Ne.records.length>0&&l.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-background/50",children:l.jsx(ad,{size:"md",color:"muted","aria-label":"Loading data"})})]}),ze.context&&l.jsx(pWe,{open:ze.open,onOpenChange:Fe=>{Ge(Nt=>({...Nt,open:Fe}))},position:ze.position,interactions:ze.interactions,selectedConditions:ze.context.conditions,drillHierarchies:(bo=N.interactionConfig)==null?void 0:bo.drillHierarchies,cardId:N.id,card:N,onSelectInteraction:Fe=>{ze.context&&Ee(Fe,ze.context),Ge({open:!1,position:null,interactions:[],context:null})}})]})}function Qre({card:e,frame:t}){var a,c;const n=TO(t,e),{manifest:r}=$h(((a=n==null?void 0:n.customCardPreferences)==null?void 0:a.url)||""),s=w.useMemo(()=>{var u;return(u=r==null?void 0:r.visuals)==null?void 0:u.find(d=>{var f;return d.name===((f=n==null?void 0:n.customCardPreferences)==null?void 0:f.componentName)})},[r,(c=n==null?void 0:n.customCardPreferences)==null?void 0:c.componentName]),i=cv(n,s)==="multiple"&&n?n:e;return i.displayPreferences?l.jsx(GO,{displayPreferences:i.displayPreferences,children:l.jsx(e9,{card:e,frame:t})}):l.jsx(e9,{card:e,frame:t})}Qre.displayName="DashboardCard";const Jre=F.memo(Qre);function $We({card:e,frame:t,showTitle:n=!0}){const{isError:r,isLoading:s,isFetching:o,data:i,pagination:a,comparisonMetadata:c}=z0(e),u=ee(x=>x.themeStyle),d=fl(e)==="dynamic"?Wx(e):e,{data:f}=$0(d),h=w.useMemo(()=>{var x;return d.type!=="pivotTable"||!((x=i==null?void 0:i.records)!=null&&x.length)?null:{records:i.records,columnSubtotalMeta:i.columnSubtotalMeta,subtotalColumns:i.subtotalColumns||[],pivotSchema:i.pivotSchema||[],groupByColumns:i.groupByColumns}},[d.type,i==null?void 0:i.records,i==null?void 0:i.columnSubtotalMeta,i==null?void 0:i.subtotalColumns,i==null?void 0:i.pivotSchema,i==null?void 0:i.groupByColumns]),m=Ig(d,h),p=w.useMemo(()=>(i==null?void 0:i.records)||[],[i==null?void 0:i.records]),g=w.useMemo(()=>{var x;if(!(!((x=i==null?void 0:i.records)!=null&&x.length)||["kpi","text","table","detailTable","pivotTable","aggregateTable","custom"].includes(d.type)))return xg({card:d,data:i.records,cardType:d.type,queryConfig:d.queryConfig,customCfg:d.customCfg,preferences:d.preferences,topoJson:f})},[i==null?void 0:i.records,d,f,u]);if(s||o)return l.jsxs("div",{className:"flex h-full grow flex-col items-center justify-center gap-4 p-12",children:[l.jsx(Mn,{className:"h-8 w-8 animate-spin text-muted-foreground"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading visual..."})]});if(r)return l.jsx("div",{className:"flex flex-col items-center justify-center gap-2 p-12",children:l.jsx("p",{className:"text-sm font-medium text-destructive",children:"Failed to load visual"})});function b(){function x(){var y;return d.type==="kpi"?l.jsx(ph,{card:d,data:(i==null?void 0:i.records)||[],isPending:s||o,comparisonMetadata:c}):d.type==="table"||d.type==="detailTable"?l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(hh,{card:d,data:p,comparisonMetadata:c,isLoading:s||o,paginationMetadata:a})}):d.type==="pivotTable"&&m?l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(dv,{card:d,data:(i==null?void 0:i.records)||[],onAggregationChange:()=>{},onAggregationLabelChange:()=>{}})}):d.type==="aggregateTable"?l.jsx("div",{className:"relative flex h-full min-h-0 w-full flex-1 grow basis-0",children:l.jsx(Yj,{card:d,data:(i==null?void 0:i.records)||[],groupByColumns:i==null?void 0:i.groupByColumns,pivotSchema:i==null?void 0:i.pivotSchema,paginationMetadata:a,onAggregationChange:()=>{},isLoading:s||o})}):d.type==="text"?l.jsx(Fo,{className:"overflow-y-auto break-words pr-2",children:l.jsx($p,{isLoading:s||o,card:d,data:(i==null?void 0:i.records)||[]})}):aN(d)&&((y=d.customCardPreferences)!=null&&y.url)?l.jsx(Ra,{FallbackComponent:My,children:l.jsx(mS,{frame:t,card:d})}):g?l.jsx(ev,{cfg:g,onChartClick:()=>{},onDatapointClick:()=>{}}):null}return fl(e)==="dynamic"?l.jsx(aE,{card:e,records:p,title:e.title,sql:e.sql,python:e.python,layoutMode:"fill",fallback:x()}):x()}return l.jsxs("div",{className:"flex h-full w-full flex-col",children:[n&&e.title&&l.jsxs("div",{className:"border-b px-4 py-2",children:[l.jsx("h3",{className:"text-lg font-medium",children:e.title}),e.description&&l.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:e.description})]}),l.jsx("div",{className:"min-h-0 flex-1 p-4",children:b()})]})}function ese({insightId:e,filters:t,contextMode:n}){const{data:r,isLoading:s,isError:o,error:i}=AN(e,{enabled:!!e}),a=Vt(f=>f.setInteractionState),c=Vt(f=>f.resetInteractionState),u=w.useMemo(()=>{var f;return r?NZ((r==null?void 0:r.frameObject)??((f=r==null?void 0:r.visual)==null?void 0:f.frameObject)):null},[r]),d=w.useMemo(()=>lj(u),[u]);return w.useEffect(()=>{if(!d)return;if(n==="none"||!(t!=null&&t.length)){const p={...Oi(),contextMode:n};a(d.id,p);return}const h={sourceCardId:"drill-to-insight",interactionMode:"clickFilter",filterGroups:[{filters:t}],applyToCardIds:[d.id]},m={...Oi(),appliedClickFilters:[h],contextMode:n};return a(d.id,m),()=>{c(d.id)}},[d,t,n,a,c]),s?l.jsxs("div",{className:"flex h-full grow flex-col items-center justify-center gap-4 p-12",children:[l.jsx(Mn,{className:"h-8 w-8 animate-spin text-muted-foreground"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading visual..."})]}):o?l.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 p-12",children:[l.jsx("p",{className:"text-sm font-medium text-destructive",children:"Failed to load insight"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:i instanceof Error?i.message:"Unknown error"})]}):!u||!d?l.jsx("div",{className:"flex items-center justify-center p-12",children:l.jsx("p",{className:"text-sm text-muted-foreground",children:"This insight has no visual data to display"})}):l.jsx("div",{className:"h-full w-full",children:l.jsx($We,{card:d,frame:u,showTitle:!1})})}function zWe({filters:e,contextMode:t}){if(!e||e.length===0)return t==="none"?l.jsxs(Xe,{variant:"outline",className:"gap-1 whitespace-nowrap",children:[l.jsx(Ic,{className:"h-3 w-3"}),"No filters"]}):null;const n=e.reduce((s,o)=>{var a,c;const i=((a=o.field)==null?void 0:a.label)||((c=o.field)==null?void 0:c.name)||"Unknown";return s[i]||(s[i]=[]),s[i].push(o),s},{});e.length;const r=Object.keys(n).length;return l.jsx(gr,{children:l.jsxs(wn,{delayDuration:200,children:[l.jsx(Cn,{asChild:!0,children:l.jsxs(Xe,{variant:"secondary",className:"cursor-help gap-1 whitespace-nowrap border border-blue-500/20 bg-blue-500/10 text-blue-700 dark:text-blue-300",children:[l.jsx(Ic,{className:"h-3 w-3"}),r," ",r===1?"filter":"filters"]})}),l.jsx(Tn,{side:"bottom",align:"start",className:"max-w-md",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium",children:"Applied Filters"}),l.jsx("div",{className:"space-y-1.5",children:Object.entries(n).map(([s,o])=>l.jsxs("div",{className:"text-xs",children:[l.jsxs("span",{className:"font-medium",children:[s,":"]})," ",o.map((i,a)=>l.jsxs("span",{children:[VWe(i),a<o.length-1?", ":""]},a))]},s))}),t&&l.jsx("div",{className:"border-t pt-2 text-xs text-muted-foreground",children:BWe(t)})]})})]})})}function VWe(e){const{operator:t,value:n}=e;if(e.label){const r=e.label.split(/[=><]/);if(r.length>1)return r[1].trim()}switch(t){case"=":return String(n);case"!=":return`≠ ${n}`;case">":return`> ${n}`;case"<":return`< ${n}`;case">=":return`≥ ${n}`;case"<=":return`≤ ${n}`;case"in":return Array.isArray(n)?n.join(", "):String(n);case"not in":return`not ${Array.isArray(n)?n.join(", "):n}`;case"contains":return`contains ${n}`;case"startsWith":return`starts with ${n}`;case"endsWith":return`ends with ${n}`;case"between":return Array.isArray(n)?`${n[0]}-${n[1]}`:String(n);case"not between":return Array.isArray(n)?`not ${n[0]}-${n[1]}`:String(n);case"isNull":return"is null";case"isNotNull":return"is not null";default:return String(n)}}function BWe(e){switch(e){case"filters":case"interactionFilters":return"Showing data filtered by interaction only";case"full":return"Showing data with all dashboard filters + interaction filters";case"none":return"Showing all data (no filters applied)"}}function tse(e,t={}){const{enabled:n=!0}=t,{data:r}=AN(e,{enabled:n&&!!e});return w.useMemo(()=>{if(!r)return{title:"",description:void 0};const o=jZ(r);return o?{title:o.title,description:o.description}:{title:"",description:void 0}},[r])}function UWe({cardId:e,children:t}){const n=Vt(o=>o.replacedCards[e]),r=Vt(o=>o.restoreCard),s=tse((n==null?void 0:n.insightId)||"",{enabled:!!(n!=null&&n.insightId)});return n?l.jsxs("div",{className:"flex h-full w-full flex-col",children:[l.jsxs("div",{className:"border-b bg-muted/30",children:[l.jsx("div",{className:"flex items-baseline gap-2 px-5 pb-2 pt-4",children:s.title&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"truncate text-sm font-semibold",children:s.title}),s.description&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"text-muted-foreground",children:"-"}),l.jsx("span",{className:"truncate text-xs text-muted-foreground",children:s.description})]})]})}),l.jsxs("div",{className:"flex items-center gap-3 px-4 pb-2",children:[l.jsxs(re,{variant:"ghost",size:"sm",onClick:()=>r(e),className:"flex-shrink-0 gap-1",children:[l.jsx(TU,{className:"h-4 w-4"}),"Back"]}),l.jsx(zWe,{filters:n.filters,contextMode:n.contextMode})]})]}),l.jsx("div",{className:"min-h-0 flex-1",children:l.jsx(ese,{insightId:n.insightId,filters:n.filters,contextMode:n.contextMode})})]}):l.jsx(l.Fragment,{children:t})}function nse({frame:e,footer:t,className:n,...r}){var C,S;const s=w.useRef(null),[o,i]=w.useState(!1),a=ee(N=>N.themeStyle),c=ee(N=>N.isVisualEditing),u=ee(N=>N.selectedFrameId),d=ee(N=>N.isDashboardEditing),{setSelectedFrameId:f}=en(),{clearSelectedVisual:h}=Jp(),{setSelectedConnectionId:m,setSelectedDatabaseName:p,setSelectedSchemaName:g,setSelectedTableName:b,setCard:x}=lr();w.useEffect(()=>{if(u===e.id&&d&&!c){const N=s==null?void 0:s.current;N==null||N.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})}},[u,e.id,d,c,s]);const y=e.cards.find(N=>N.id===e.activeCardId);function v(N){N.stopPropagation(),f(e.id),h(),y&&x(y),y!=null&&y.connectionId&&m(y==null?void 0:y.connectionId),y!=null&&y.lastSelectedDatabase&&p(y==null?void 0:y.lastSelectedDatabase),y!=null&&y.lastSelectedSchema&&g(y==null?void 0:y.lastSelectedSchema),y!=null&&y.lastSelectedTable&&b(y==null?void 0:y.lastSelectedTable)}return l.jsx(Ra,{FallbackComponent:iE,children:l.jsxs("div",{tabIndex:-1,ref:s,role:"card-frame","data-frame-id":e.id,"data-active-card-id":y==null?void 0:y.id,onClick:v,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{borderRadius:a==null?void 0:a.cardBorderRadius},className:Q("relative flex h-full flex-col rounded-sm border bg-background shadow-sm",{"border-dashed border-foreground/50":u===e.id&&d},a==null?void 0:a.dashboardCard,n,"semaphor-card-frame"),...r,children:[(d||((S=(C=y==null?void 0:y.preferences)==null?void 0:C.displayOptions)==null?void 0:S.showCardToolbar)!==!1)&&l.jsx(Hre,{frame:e,isHovered:o}),y&&l.jsx(UWe,{cardId:y.id,children:l.jsx(Jre,{card:y,frame:e},y.id)})]})})}nse.displayName="DashboardFrame";const HWe=w.memo(nse);function WWe({filter:e,onUpdate:t}){const[n,r]=w.useState(""),s=ee(y=>y.dashboard.sheets)||[],o=ee(y=>y.selectedSheetId),i=w.useMemo(()=>{const y=[];return s==null||s.forEach(v=>{var C;(C=v.frames)==null||C.forEach(S=>{var N;(N=S.cards)==null||N.forEach(j=>{y.push({...j,sheetId:v.id,sheetTitle:v.title||v.id})})})}),y},[s]),a=()=>e.applyToSheetIds!==void 0?"specific-sheets":e.excludeSheetIds!==void 0?"all-except-specific":"all-sheets",c=()=>e.applyToCardIds!==void 0?"specific-cards":e.excludeCardIds!==void 0?"all-except-specific":"all-cards",u=y=>{const v={};switch(y){case"all-sheets":v.applyToSheetIds=void 0,v.excludeSheetIds=void 0;break;case"specific-sheets":v.applyToSheetIds=[],v.excludeSheetIds=void 0;break;case"all-except-specific":v.applyToSheetIds=void 0,v.excludeSheetIds=[];break}t(v)},d=y=>{const v={};switch(y){case"all-cards":v.applyToCardIds=void 0,v.excludeCardIds=void 0;break;case"specific-cards":v.applyToCardIds=[],v.excludeCardIds=void 0;break;case"all-except-specific":v.applyToCardIds=void 0,v.excludeCardIds=[];break}t(v)},f=(y,v)=>{if(v==="specific-sheets"){const C=e.applyToSheetIds||[],S=C.includes(y)?C.filter(N=>N!==y):[...C,y];t({applyToSheetIds:S})}else if(v==="all-except-specific"){const C=e.excludeSheetIds||[],S=C.includes(y)?C.filter(N=>N!==y):[...C,y];t({excludeSheetIds:S})}},h=(y,v)=>{if(v==="specific-cards"){const C=e.applyToCardIds||[],S=C.includes(y)?C.filter(N=>N!==y):[...C,y];t({applyToCardIds:S})}else if(v==="all-except-specific"){const C=e.excludeCardIds||[],S=C.includes(y)?C.filter(N=>N!==y):[...C,y];t({excludeCardIds:S})}},m=()=>{const y=a();return y==="specific-sheets"?e.applyToSheetIds||[]:y==="all-except-specific"?(s==null?void 0:s.filter(v=>{var C;return!((C=e.excludeSheetIds)!=null&&C.includes(v.id))}).map(v=>v.id))||[]:(s==null?void 0:s.map(v=>v.id))||[]},p=w.useMemo(()=>{const y=m();return i.filter(v=>y.includes(v.sheetId))},[i,e.applyToSheetIds,e.excludeSheetIds]),g=w.useMemo(()=>{if(!n.trim())return p;const y=n.toLowerCase();return p.filter(v=>{var C;return(C=v==null?void 0:v.title)==null?void 0:C.toLowerCase().includes(y)})},[n,p]),b=a(),x=c();return l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Sheet Scope"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Which sheets should display this filter?"})]}),l.jsxs(Do,{value:b,onValueChange:y=>u(y),className:"space-y-3",children:[l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"all-sheets",id:"all-sheets",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"all-sheets",className:"cursor-pointer text-sm font-medium",children:"All sheets"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Display filter on all sheets (",(s==null?void 0:s.length)||0," sheets)"]})]})]}),l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"specific-sheets",id:"specific-sheets",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"specific-sheets",className:"cursor-pointer text-sm font-medium",children:"Only specific sheets"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Display filter on selected sheets only"})]})]}),b==="specific-sheets"&&l.jsx("div",{className:"ml-7 space-y-2",children:l.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:s==null?void 0:s.map(y=>{const v=(e.applyToSheetIds||[]).includes(y.id);return l.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[l.jsx(Jt,{id:`sheet-${y.id}`,checked:v,onCheckedChange:()=>f(y.id,"specific-sheets")}),l.jsxs(ge,{htmlFor:`sheet-${y.id}`,className:"cursor-pointer text-sm font-medium",children:[y.title||y.id,y.id===o&&l.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:"(this sheet)"})]})]},y.id)})})}),l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"all-except-specific",id:"all-sheets-except",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"all-sheets-except",className:"cursor-pointer text-sm font-medium",children:"All sheets except specific ones"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Display filter on all sheets except selected ones"})]})]}),b==="all-except-specific"&&l.jsx("div",{className:"ml-7 space-y-2",children:l.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:s==null?void 0:s.map(y=>{const v=(e.excludeSheetIds||[]).includes(y.id);return l.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[l.jsx(Jt,{id:`sheet-exclude-${y.id}`,checked:v,onCheckedChange:()=>f(y.id,"all-except-specific")}),l.jsxs(ge,{htmlFor:`sheet-exclude-${y.id}`,className:"cursor-pointer text-sm font-medium",children:[y.title||y.id,y.id===o&&l.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:"(this sheet)"})]})]},y.id)})})})]})]}),l.jsxs("div",{className:"space-y-3 border-t pt-4",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Card Scope"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Which cards should receive this filter?"})]}),l.jsxs(Do,{value:x,onValueChange:y=>d(y),className:"space-y-3",children:[l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"all-cards",id:"all-cards",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"all-cards",className:"cursor-pointer text-sm font-medium",children:"All cards"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Apply filter to all cards in applicable sheets (",p.length," cards)"]})]})]}),l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"specific-cards",id:"specific-cards",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"specific-cards",className:"cursor-pointer text-sm font-medium",children:"Only specific cards"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to selected cards only"})]})]}),x==="specific-cards"&&l.jsxs("div",{className:"ml-7 space-y-2",children:[l.jsx(lt,{placeholder:"Search cards...",value:n,onChange:y=>r(y.target.value),className:"mb-2"}),l.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:g.length>0?g.map(y=>{const v=(e.applyToCardIds||[]).includes(y.id);return l.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[l.jsx(Jt,{id:`card-${y.id}`,checked:v,onCheckedChange:()=>h(y.id,"specific-cards")}),l.jsxs("div",{className:"flex-1",children:[l.jsx(ge,{htmlFor:`card-${y.id}`,className:"cursor-pointer text-sm font-medium",children:y.title}),l.jsx("p",{className:"text-xs text-muted-foreground",children:y.sheetTitle})]})]},y.id)}):l.jsxs("p",{className:"py-4 text-center text-sm text-muted-foreground",children:['No cards found matching "',n,'"']})})]}),l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"all-except-specific",id:"all-cards-except",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"all-cards-except",className:"cursor-pointer text-sm font-medium",children:"All cards except specific ones"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to all cards except selected ones"})]})]}),x==="all-except-specific"&&l.jsxs("div",{className:"ml-7 space-y-2",children:[l.jsx(lt,{placeholder:"Search cards...",value:n,onChange:y=>r(y.target.value),className:"mb-2"}),l.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:g.length>0?g.map(y=>{const v=(e.excludeCardIds||[]).includes(y.id);return l.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[l.jsx(Jt,{id:`card-exclude-${y.id}`,checked:v,onCheckedChange:()=>h(y.id,"all-except-specific")}),l.jsxs("div",{className:"flex-1",children:[l.jsx(ge,{htmlFor:`card-exclude-${y.id}`,className:"cursor-pointer text-sm font-medium",children:y.title}),l.jsx("p",{className:"text-xs text-muted-foreground",children:y.sheetTitle})]})]},y.id)}):l.jsxs("p",{className:"py-4 text-center text-sm text-muted-foreground",children:['No cards found matching "',n,'"']})})]})]})]}),l.jsx("div",{className:"rounded-md bg-blue-50 p-3 text-xs text-blue-900 dark:bg-blue-950 dark:text-blue-100",children:"ℹ️ Cards are filtered based on sheet scope selection. Only cards from applicable sheets are shown in card scope."})]})}function hv(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o<r.length;o++)s=r[o],!(t.indexOf(s)>=0)&&(n[s]=e[s]);return n}var qWe=["color"],YWe=w.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=hv(e,qWe);return w.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),w.createElement("path",{d:"M7.5 2C7.77614 2 8 2.22386 8 2.5L8 11.2929L11.1464 8.14645C11.3417 7.95118 11.6583 7.95118 11.8536 8.14645C12.0488 8.34171 12.0488 8.65829 11.8536 8.85355L7.85355 12.8536C7.75979 12.9473 7.63261 13 7.5 13C7.36739 13 7.24021 12.9473 7.14645 12.8536L3.14645 8.85355C2.95118 8.65829 2.95118 8.34171 3.14645 8.14645C3.34171 7.95118 3.65829 7.95118 3.85355 8.14645L7 11.2929L7 2.5C7 2.22386 7.22386 2 7.5 2Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),GWe=["color"],KWe=w.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=hv(e,GWe);return w.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),w.createElement("path",{d:"M7.14645 2.14645C7.34171 1.95118 7.65829 1.95118 7.85355 2.14645L11.8536 6.14645C12.0488 6.34171 12.0488 6.65829 11.8536 6.85355C11.6583 7.04882 11.3417 7.04882 11.1464 6.85355L8 3.70711L8 12.5C8 12.7761 7.77614 13 7.5 13C7.22386 13 7 12.7761 7 12.5L7 3.70711L3.85355 6.85355C3.65829 7.04882 3.34171 7.04882 3.14645 6.85355C2.95118 6.65829 2.95118 6.34171 3.14645 6.14645L7.14645 2.14645Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ZWe=["color"],XWe=w.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=hv(e,ZWe);return w.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),w.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),QWe=["color"],rse=w.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=hv(e,QWe);return w.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),w.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),JWe=["color"],sse=w.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,s=hv(e,JWe);return w.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s,{ref:t}),w.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Fc({text:e,className:t,ariaLabel:n,onCopy:r,disabled:s=!1}){const[o,i]=w.useState(!1);return l.jsx(re,{className:Q("h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",t),variant:"ghost",size:"icon","aria-label":n,disabled:s,onClick:async()=>{try{let a=!1;if(r)a=await r();else if(typeof e=="string"){if(typeof navigator>"u"||!navigator.clipboard)return;await navigator.clipboard.writeText(e),a=!0}if(!a)return;i(!0),setTimeout(()=>{i(!1)},1e3)}catch(a){console.error("Failed to copy text",a)}},children:o?l.jsx(rse,{className:"size-3.5"}):l.jsx(mp,{className:"size-3.5"})})}function ose(){const{authToken:e,tokenProps:t}=rt(),{data:n,isLoading:r,isFetching:s,isError:o}=Qt({queryKey:["plugins",e==null?void 0:e.accessToken],queryFn:()=>hme(t.apiServiceUrl,e==null?void 0:e.accessToken)});return{data:n,isLoading:r,isFetching:s,isError:o}}function fE(){const{data:e,isLoading:t,isError:n}=ose(),r=cN({queries:((e==null?void 0:e.plugins)||[]).map(c=>({queryKey:["manifest",c.value],queryFn:()=>xte(c.value),enabled:!!c.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:u=>Math.min(1e3*2**u,3e4)}))}),s=[],o=[];let i=t,a=n;return r.forEach((c,u)=>{var d;if(c.isLoading&&(i=!0),c.isError&&(a=!0),c.data&&((d=e==null?void 0:e.plugins)!=null&&d[u])){const f=e.plugins[u],h=c.data.visuals.map(m=>({name:m.name,pluginName:f.label,componentType:m.componentType,pluginType:f.type,icon:m.icon,chartType:m.chartType,visualType:m.visualType||(m.dataInputs&&m.dataInputs.length>1?"multiple":"single"),minInputs:m.minInputs,maxInputs:m.maxInputs,slots:m.slots,url:f.value}));if(s.push(...h),c.data.filters){const m=c.data.filters.map(p=>({name:p.name,component:p.component,pluginName:f.label,pluginType:f.type,icon:p.icon,filterType:p.filterType,supportedDataTypes:p.supportedDataTypes,url:f.value}));o.push(...m)}}}),{data:s,filters:o,isLoading:i,isError:a}}function eqe(e){const[t,n]=w.useState(null);return t}function tqe({pluginFilter:e}){const t=eqe(e.icon||""),n=e.name.charAt(0).toUpperCase();return l.jsxs("div",{className:"flex items-center gap-2",children:[t?l.jsx(t,{className:"h-4 w-4"}):l.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:n}),l.jsx("span",{children:e.name}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",e.pluginName,")"]})]})}function nqe({filter:e,onSelect:t,onClear:n}){const{filters:r,isLoading:s}=fE(),o=Sn(e.dataType),i=r==null?void 0:r.filter(u=>!u.supportedDataTypes||u.supportedDataTypes.length===0?!0:u.supportedDataTypes.some(d=>o.toLowerCase()===d.toLowerCase())),a=e.customFilterPreferences,c=a?`${a.url}::${a.componentName}`:"";return s?l.jsxs("div",{className:"flex h-9 items-center gap-2 text-sm text-muted-foreground",children:[l.jsx(Mn,{className:"h-4 w-4 animate-spin"}),"Loading custom filters..."]}):!i||i.length===0?l.jsx("div",{className:"text-sm text-muted-foreground",children:"No custom filters available"}):l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs(pt,{value:c,onValueChange:u=>{if(!u)return;const[d,f]=u.split("::"),h=i.find(m=>m.url===d&&m.component===f);h&&t({url:d,componentName:h.component,pluginFilterType:h.filterType,icon:h.icon})},children:[l.jsx(ft,{className:"h-9 flex-1",children:l.jsx(gt,{placeholder:"Use default UI"})}),l.jsx(ht,{children:i.map(u=>l.jsx(Ie,{value:`${u.url}::${u.component}`,children:l.jsx(tqe,{pluginFilter:u})},`${u.url}::${u.component}`))})]}),a&&l.jsx(re,{variant:"ghost",size:"sm",className:"h-9 w-9 p-0",onClick:n,title:"Clear custom filter selection",children:l.jsx(Mt,{className:"h-4 w-4"})})]})}function rqe(e){for(const[n,r]of Object.entries(k7))if(JSON.stringify(r)===JSON.stringify(e))return n;const t={day:"day",week:"week",month:"month",quarter:"quarter",year:"year"};switch(e.mode){case"last":{const n=e.complete?" (complete)":"",r=e.n>1?"s":"";return`Last ${e.n} ${t[e.unit]}${r}${n}`}case"this":{const n=e.toDate?" to date":"";return`This ${t[e.unit]}${n}`}case"previous":return`Previous ${t[e.unit]}`;case"between":return`Between ${e.from} and ${e.to} ${t[e.unit]}s`}}const sqe=["January","February","March","April","May","June","July","August","September","October","November","December"];function oqe(e){return fA(e)?`${sqe[e.month]} ${e.year}`:rqe(e)}function bT(e){return e&&Zp(e)?"relative":"fixed"}function iqe({filter:e,onUpdate:t,showFilterId:n=!0,filterOptionsData:r,timezone:s,variant:o="dashboard"}){var L;const[i,a]=w.useState(e.title===e.column?"":e.title||""),[c,u]=w.useState(e.column),[d,f]=w.useState(((L=e.defaultValues)==null?void 0:L.map($=>String($)))||[]),[h,m]=w.useState(e.defaultDateFilter),[p,g]=w.useState(bT(e.defaultDateFilter)),[b,x]=w.useState(e.targetColumns||[]),y=w.useMemo(()=>Sn(e.dataType)==="date",[e.dataType]),v=s||Intl.DateTimeFormat().resolvedOptions().timeZone,C=o==="inline"?"z-[80]":void 0,S=w.useMemo(()=>{if(!h)return;const $=sN(h,v);if(!$)return;const[B,V]=$;return{from:B,to:V}},[h,v]),N=w.useMemo(()=>{if(h&&fA(h))return{year:h.year,month:h.month}},[h]),j=w.useMemo(()=>{if(!(!h||!Zp(h)))return h},[h]);w.useEffect(()=>{var B;a(e.title===e.column?"":e.title||""),u(e.column),f(((B=e.defaultValues)==null?void 0:B.map(V=>String(V)))||[]);const $=e.defaultDateFilter;m($),g(bT($)),x(e.targetColumns||[])},[e]);function k(){const $=i.trim();t({title:$||e.column})}function T(){const $=c.trim();if($&&$!==e.column){const B=i.trim()!=="";t(B?{column:$}:{column:$,title:$})}}function E($){f($);const B=$.length>0?$.map(V=>{const R=Number(V);return!isNaN(R)&&wa(e.dataType)?R:V}):void 0;t({defaultValues:B})}function _($){m($),$&&g(bT($)),t({defaultDateFilter:$})}function M($){x($),t({targetColumns:$.length>0?$:void 0})}function P(){M([...b,{column:"",label:""}])}function D($){const B=b.filter((V,R)=>R!==$);M(B)}function A($,B,V){const R=b.map((U,O)=>O===$?{...U,[B]:V}:U);M(R)}return l.jsxs("div",{className:"space-y-5",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Label"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("p",{className:"text-xs",children:"Leave empty to use the column name. Provide a custom label to override it."}),n&&l.jsxs("div",{className:"space-y-1 border-t pt-2",children:[l.jsx("p",{className:"text-xs font-medium",children:"Filter ID"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("p",{className:"break-all font-mono text-xs text-muted-foreground",children:e.id}),l.jsx(Fc,{text:e.id})]})]})]})})]})})]}),l.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[l.jsx(Jt,{id:"hideLabel",checked:e.showLabel===!1,onCheckedChange:$=>{t({showLabel:!$})}}),l.jsx(ge,{htmlFor:"hideLabel",className:"cursor-pointer text-sm text-muted-foreground",children:"Hide label"})]})]}),l.jsx(lt,{value:i,onChange:$=>a($.target.value),onBlur:k,placeholder:e.column,className:"h-8 text-sm"})]}),y?l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Default Date Filter"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsx("p",{className:"text-xs",children:"Sets the initial date selection on load and previews it immediately while editing. Relative defaults recalculate on each load and scheduled execution, while fixed month defaults stay unchanged."})})]})})]}),e.dateSelectionMode==="months"?l.jsxs(As,{value:p,onValueChange:$=>g($),className:"space-y-2",children:[l.jsxs(ys,{className:"grid h-9 w-full grid-cols-2 overflow-hidden rounded-md p-1",children:[l.jsx(on,{value:"fixed",className:"h-7 text-xs leading-none",children:"Fixed"}),l.jsx(on,{value:"relative",className:"h-7 text-xs leading-none",children:"Relative"})]}),l.jsx(sr,{value:"fixed",className:"mt-0",children:l.jsx(Yte,{value:N,placeholder:"Select default month...",className:"w-full",onClear:()=>_(void 0),onChange:($,B)=>_({mode:"fixed",unit:"month",year:$,month:B})})}),l.jsx(sr,{value:"relative",className:"mt-0",children:l.jsxs(pt,{value:j?JSON.stringify(j):"__none__",onValueChange:$=>{if($==="__none__"){_(void 0);return}try{const B=JSON.parse($);_(B)}catch(B){console.error("Failed to parse relative date filter",B)}},children:[l.jsx(ft,{className:"h-8",children:l.jsx(gt,{placeholder:"Select default month range..."})}),l.jsxs(ht,{className:C,children:[l.jsx(Ie,{value:"__none__",children:"None"}),l.jsx(Ie,{value:JSON.stringify({mode:"this",unit:"month"}),children:"This month"}),l.jsx(Ie,{value:JSON.stringify({mode:"previous",unit:"month"}),children:"Last month"})]})]})})]}):l.jsx(iO,{value:S,onRelativeSelect:($,B)=>{_(B)},showRelativeTab:!0,hideCalendar:!0,timezone:v,placeholder:"Select default date range...",buttonClassName:"h-8",contentClassName:C,overlayContentClassName:C}),h&&l.jsx("div",{className:"flex items-center gap-2",children:l.jsxs(Xe,{variant:"secondary",className:"gap-1.5 text-xs",children:[oqe(h),l.jsx(Mt,{className:"h-3 w-3 cursor-pointer hover:text-destructive",onClick:()=>_(void 0)})]})})]}):l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Default Values"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsx("p",{className:"text-xs",children:"Sets the initial selection on load and previews it immediately while editing. Works like a filter selection."})})]})})]}),r!=null&&r.records&&r.records.length>0?l.jsxs(pt,{value:"",onValueChange:$=>{$&&!d.includes($)&&E([...d,$])},children:[l.jsx(ft,{className:"h-8",children:l.jsx(gt,{placeholder:"Select values to add..."})}),l.jsxs(ht,{className:C,children:[r.records.filter($=>{var R;const B=(R=e.column.split(".").pop())==null?void 0:R.replace(/"/g,""),V=B?$[B]:$.value;return V!=null&&!d.includes(String(V))}).map($=>{var R;const B=(R=e.column.split(".").pop())==null?void 0:R.replace(/"/g,""),V=B?$[B]:$.value;return l.jsx(Ie,{value:String(V),children:String(V)},String(V))}),r.records.every($=>{var R;const B=(R=e.column.split(".").pop())==null?void 0:R.replace(/"/g,""),V=B?$[B]:$.value;return V==null||d.includes(String(V))})&&l.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"All values selected"})]})]}):l.jsx("div",{className:"flex h-8 items-center rounded-md border bg-muted px-2 text-xs text-muted-foreground",children:"Loading filter options..."}),d.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"text-xs font-medium text-muted-foreground",children:["Selected (",d.length,"):"]}),l.jsx("div",{className:"flex flex-wrap gap-1.5",children:d.map($=>l.jsxs(Xe,{variant:"secondary",className:"gap-1.5 text-xs",children:[String($),l.jsx(Mt,{className:"h-3 w-3 cursor-pointer hover:text-destructive",onClick:()=>{E(d.filter(B=>B!==$))}})]},$))})]})]}),y&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Target Columns"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsx("p",{className:"text-xs",children:"Add multiple date columns to let users choose which field to filter at runtime. Leave empty to use only the primary column above."})})]})})]}),b.length>0&&l.jsx("div",{className:"space-y-2",children:b.map(($,B)=>l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(lt,{placeholder:"Column name",value:$.column,onChange:V=>A(B,"column",V.target.value),className:"h-8 flex-1 font-mono text-xs"}),l.jsx(lt,{placeholder:"Label",value:$.label,onChange:V=>A(B,"label",V.target.value),className:"h-8 flex-1 text-xs"}),l.jsx(re,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>D(B),children:l.jsx(Mt,{className:"h-4 w-4"})})]},B))}),l.jsxs(re,{variant:"outline",size:"sm",className:"h-8",onClick:P,children:[l.jsx($r,{className:"mr-1 h-4 w-4"}),"Add Column"]})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Column Name"}),l.jsx(lt,{value:c,onChange:$=>u($.target.value),onBlur:T,placeholder:"Enter column name",className:"h-8 font-mono text-xs"})]})]})}function aqe({filter:e,onUpdate:t,variant:n="dashboard"}){const{filters:r,isLoading:s}=fE(),o=w.useMemo(()=>Sn(e.dataType)==="date",[e.dataType]),i=n==="inline"?"z-[80]":void 0,a=w.useMemo(()=>{const p=Sn(e.dataType);return(r==null?void 0:r.filter(g=>!g.supportedDataTypes||g.supportedDataTypes.length===0?!0:g.supportedDataTypes.some(b=>p.toLowerCase()===b.toLowerCase())))??[]},[e.dataType,r]),c=s||!!e.customFilterPreferences||a.length>0;function u(p){t({type:p})}function d(p){t({dateSelectionMode:p})}function f(p){t({uiType:p})}function h(p){t({customFilterPreferences:p})}function m(){t({customFilterPreferences:void 0})}return l.jsxs("div",{className:"space-y-5",children:[o?l.jsxs("div",{className:"space-y-1",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Date Picker Type"}),l.jsxs(pt,{value:e.dateSelectionMode||"range",onValueChange:p=>d(p),children:[l.jsx(ft,{className:"h-8",children:l.jsx(gt,{})}),l.jsxs(ht,{className:i,children:[l.jsx(Ie,{value:"range",children:"Date Range Picker"}),l.jsx(Ie,{value:"months",children:"Month Picker"})]})]})]}):l.jsxs("div",{className:"space-y-1",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Selection Type"}),l.jsxs(pt,{value:e.type||"multiple",onValueChange:u,children:[l.jsx(ft,{className:"h-8",children:l.jsx(gt,{})}),l.jsxs(ht,{className:i,children:[l.jsx(Ie,{value:"multiple",children:"Multiple"}),l.jsx(Ie,{value:"single",children:"Single"})]})]})]}),!o&&e.type==="single"&&l.jsxs("div",{className:"space-y-1",children:[l.jsx(ge,{className:"text-sm font-medium",children:"UI Component"}),l.jsxs(pt,{value:e.uiType||"dropdown",onValueChange:f,children:[l.jsx(ft,{className:"h-8",children:l.jsx(gt,{})}),l.jsxs(ht,{className:i,children:[l.jsx(Ie,{value:"dropdown",children:"Dropdown"}),l.jsx(Ie,{value:"radio",children:"Radio"}),l.jsx(Ie,{value:"tabs",children:"Tabs"})]})]})]}),c&&l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Custom Filter Component"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsx("p",{className:"text-xs",children:"Select a custom filter component from an installed plugin to replace the default filter UI with a custom implementation."})})]})})]}),l.jsx(nqe,{filter:e,onSelect:h,onClear:m})]}),n==="dashboard"&&l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Display Mode"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsx("p",{className:"text-xs",children:`Choose how this filter is displayed. "Inherit" uses the dashboard's default setting. Override with "Canvas Card" or "Toolbar" to always display this filter in a specific mode.`})})]})})]}),l.jsxs(pt,{value:e.displayMode||"inherit",onValueChange:p=>t({displayMode:p}),children:[l.jsx(ft,{className:"h-8",children:l.jsx(gt,{})}),l.jsxs(ht,{children:[l.jsx(Ie,{value:"inherit",children:"Inherit (use dashboard default)"}),l.jsx(Ie,{value:"canvas",children:"Canvas Card"}),l.jsx(Ie,{value:"toolbar",children:"Toolbar"})]})]})]}),n==="inline"&&l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Width (px)"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsx("p",{className:"text-xs",children:"Set the width of this inline filter in pixels. Default is 250px."})})]})})]}),l.jsx(lt,{type:"number",min:100,max:500,value:e.width??250,onChange:p=>{const g=parseInt(p.target.value,10);isNaN(g)||t({width:g})},className:"h-8 w-24 text-sm"})]})]})}function lqe({filter:e,onUpdate:t,variant:n="dashboard"}){const[r,s]=w.useState(e.sql),[o,i]=w.useState(e.searchMode||"auto"),a=n==="inline"?"z-[80]":void 0;w.useEffect(()=>{s(e.sql),i(e.searchMode||"auto")},[e]);function c(){t({sql:r})}function u(d){i(d),t({searchMode:d})}return l.jsxs("div",{className:"space-y-5",children:[wa(e.dataType)&&l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Search Mode"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsxs("div",{className:"space-y-2 text-xs",children:[l.jsxs("p",{children:[l.jsx("strong",{children:"Text Search:"}),' Treats numbers as text (e.g., ZIP codes, IDs). Search for "90210".']}),l.jsxs("p",{children:[l.jsx("strong",{children:"Numeric Operators:"})," Supports comparison operators (e.g., >100, <=50, =100) for quantities, prices."]}),l.jsxs("p",{children:[l.jsx("strong",{children:"Auto-detect:"})," Tries numeric first, falls back to text search."]})]})})]})})]}),l.jsxs(pt,{value:o,onValueChange:u,children:[l.jsx(ft,{className:"h-8",children:l.jsx(gt,{})}),l.jsxs(ht,{className:a,children:[l.jsx(Ie,{value:"text",children:"Text Search"}),l.jsx(Ie,{value:"numeric",children:"Numeric Operators"}),l.jsx(Ie,{value:"auto",children:"Auto-detect"})]})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"SQL"}),l.jsx(gr,{children:l.jsxs(wn,{delayDuration:0,children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),l.jsx(Tn,{side:"right",className:"max-w-xs",children:l.jsx("p",{className:"text-xs",children:"This SQL will be used to fetch the filter values"})})]})})]}),l.jsx(yi,{onKeyDown:d=>{d.stopPropagation()},value:r,onChange:d=>s(d.target.value),onBlur:c,className:`h-32 w-full resize-none break-all font-mono text-xs ${pu}`,placeholder:"SELECT column FROM table..."})]})]})}const cqe=[{id:"basic",label:"Basic Settings",title:"Basic Settings",subtitle:"Configure the core filter properties"},{id:"scope",label:"Scope",title:"Scope",subtitle:"Configure which sheets and cards this filter applies to"},{id:"behavior",label:"Behavior",title:"Behavior",subtitle:"Control how this filter appears and behaves"},{id:"data",label:"Data",title:"Data",subtitle:"Control how this filter searches and fetches values"}];function KO({filter:e,variant:t="dashboard",onAccept:n,open:r,onOpenChange:s,trigger:o,isEditing:i=!1}){var P,D,A;function a(L){if(!L)return"Unknown";const $=Sn(L),B=$==="date"?"Datetime":$==="string"?"Text":$==="number"?"Number":$==="boolean"?"Boolean":$==="json"?"JSON":"Geo";return/nullable/i.test(L)?`${B} (nullable)`:B}const[c,u]=w.useState(!1),d=r??c,f=s??u,[h,m]=w.useState("basic"),[p,g]=w.useState({}),{updateFilter:b,addOrUpdateFilterValue:x,removeFilterValues:y}=en(),v=w.useMemo(()=>cqe.filter(L=>t==="dashboard"||L.id!=="scope"),[t]),{tokenProps:C}=rt(),S=((D=(P=C==null?void 0:C.params)==null?void 0:P.calendarContext)==null?void 0:D.tz)||((A=C==null?void 0:C.params)==null?void 0:A.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone,{data:N}=cO(e),j={...e,...p},k=v.find(L=>L.id===h)||v[0];function T(){let L={...p};const $=Object.prototype.hasOwnProperty.call(L,"defaultValues")||Object.prototype.hasOwnProperty.call(L,"defaultDateFilter");if(t==="inline"&&"width"in L){const B=L.width;L={...L,width:Math.min(500,Math.max(100,B))}}if(n)n(L);else{const B={...e,...L};if(b(B),$){const V=hA(B,S);V?x(V):y(e.id)}}g({}),f(!1)}function E(L){g($=>({...$,...L}))}w.useEffect(()=>{d&&(g({}),m("basic"))},[d]);const _=e.column.split(".").pop()||e.column,M=a(e.dataType);return l.jsxs(Gr,{open:d,onOpenChange:f,children:[l.jsx(Kr,{asChild:!0,children:o??l.jsx("button",{type:"button",className:Q("rounded p-0.5 hover:bg-muted focus:visible focus:outline-none focus:ring-1 focus:ring-ring",i?"visible":"invisible group-hover:visible"),"aria-label":"Filter settings",children:l.jsx(gl,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})}),l.jsx(Zr,{onMouseDown:L=>L.stopPropagation(),onDoubleClick:L=>L.stopPropagation(),className:Q("m-2 h-[400px] w-[600px] p-0",t==="inline"?"z-[70]":"z-50"),children:l.jsxs("div",{className:"flex h-full",children:[l.jsxs("div",{className:"flex w-[180px] min-w-0 flex-col border-r bg-muted/30 p-4",children:[l.jsxs("div",{className:"mb-6 min-w-0",children:[l.jsx("h4",{className:"truncate text-sm font-medium",title:e.column,children:_}),l.jsx(Xe,{variant:"secondary",className:"mt-1 inline-flex max-w-full truncate text-[10px] font-medium leading-tight",title:e.dataType,children:M})]}),l.jsx("nav",{className:"flex flex-1 flex-col gap-1",children:v.map(L=>l.jsx("button",{onClick:()=>m(L.id),className:Q("rounded-md px-3 py-2 text-left text-sm transition-colors",h===L.id?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:L.label},L.id))})]}),l.jsxs("div",{className:"flex min-w-0 flex-1 flex-col p-6",children:[l.jsxs("div",{className:"mb-6",children:[l.jsx("h3",{className:"text-lg font-semibold",children:k.title}),l.jsx("p",{className:"text-sm text-muted-foreground",children:k.subtitle})]}),l.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[h==="basic"&&l.jsx(iqe,{filter:j,onUpdate:E,showFilterId:!0,filterOptionsData:N,timezone:S,variant:t}),h==="behavior"&&l.jsx(aqe,{filter:j,onUpdate:E,variant:t}),h==="data"&&l.jsx(lqe,{filter:j,onUpdate:E,variant:t}),h==="scope"&&t==="dashboard"&&l.jsx(WWe,{filter:j,onUpdate:E})]}),l.jsx("div",{className:"mt-4 flex justify-end",children:l.jsx(re,{onClick:T,size:"sm",children:"Accept"})})]})]})})]})}function uqe(e=[]){const t=w.useRef(null),n=w.useRef(null),r=w.useRef(null),[s,o]=w.useState(),i=w.useCallback(()=>{var m,p,g;const a=((m=t.current)==null?void 0:m.clientWidth)??0,c=((p=r.current)==null?void 0:p.offsetWidth)??0,u=((g=n.current)==null?void 0:g.offsetWidth)??0,f=a-c-u-8,h=Math.max(f,0);o(b=>b===h?b:h)},[]);return w.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=new ResizeObserver(()=>i());return c.observe(a),i(),()=>c.disconnect()},[i,...e]),{headerRef:t,leftActionsRef:n,rightActionsRef:r,titleMaxWidth:s,updateAvailableWidth:i}}function ZO({filter:e}){var p;const t=ee(g=>g.isDashboardEditing),{preferences:n}=ag(),r=((p=n==null?void 0:n.cardDisplay)==null?void 0:p.mode)==="print",s=ee(g=>g.filterValues),o=s==null?void 0:s.some(g=>g.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:c}=en(),{headerRef:u,leftActionsRef:d,rightActionsRef:f,titleMaxWidth:h,updateAvailableWidth:m}=uqe([t,o,r]);return w.useEffect(()=>{m()},[e.title,m]),l.jsxs("div",{ref:u,className:"group mb-1 flex h-5 items-center justify-between",children:[l.jsxs("div",{className:"flex grow items-center gap-2 min-w-0",children:[l.jsx("div",{className:"min-w-0 flex-1",style:h!==void 0?{maxWidth:h}:void 0,children:l.jsx(ge,{className:"my-1 block w-full text-sm",children:l.jsx(Ui,{value:e.title||e.column,onSave:g=>c({...e,title:g}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm truncate",inputClassName:"text-sm"})})}),l.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",ref:d,children:[t&&l.jsx(KO,{filter:e,isEditing:t}),t&&l.jsx("button",{onClick:()=>{i(e.id),a(e.id)},className:"text-muted-foreground hover:text-foreground",children:l.jsx(Mt,{className:"size-3.5"})})]})]}),l.jsx("div",{className:"hidden",ref:f})]})}function dqe({sheetId:e}){const{handleAddNewFrame:t}=_Z(),n=ee(s=>s.themeStyle),r=()=>{t({openVisualEditor:!0,sheetId:e})};return l.jsx("div",{className:"flex h-full min-h-[400px] items-start justify-start p-4",children:l.jsxs("button",{onClick:r,style:{borderRadius:n==null?void 0:n.cardBorderRadius},className:"group flex h-96 w-[600px] flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed border-muted-foreground/25 bg-background transition-all hover:border-muted-foreground/50 hover:bg-muted/50",children:[l.jsx("div",{className:"rounded-full bg-primary/10 p-3 transition-colors group-hover:bg-primary/20",children:l.jsx($r,{className:"h-6 w-6 text-primary"})}),l.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Add new Visual"})]})})}function bh(e){const t=(e||"").toLowerCase(),n=Sn(t);return n==="string"?l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-blue-200/70 bg-gradient-to-r from-blue-100/60 to-blue-200/40 text-blue-900 shadow-sm dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100",children:l.jsx(eI,{className:"h-3 w-3"})}):n==="number"?l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-green-200/70 bg-gradient-to-r from-green-100/60 to-green-200/40 text-green-900 shadow-sm dark:border-green-800/50 dark:from-green-950/40 dark:to-green-900/30 dark:text-green-100",children:l.jsx($U,{className:"h-3 w-3"})}):n==="date"?l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-purple-200/70 bg-gradient-to-r from-purple-100/60 to-purple-200/40 text-purple-900 shadow-sm dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100",children:l.jsx(js,{className:"h-3 w-3"})}):n==="boolean"?l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-orange-200/70 bg-gradient-to-r from-orange-100/60 to-orange-200/40 text-orange-900 shadow-sm dark:border-orange-800/50 dark:from-orange-950/40 dark:to-orange-900/30 dark:text-orange-100",children:l.jsx(Fpe,{className:"h-3 w-3"})}):n==="json"?l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-gray-200/70 bg-gradient-to-r from-gray-100/60 to-gray-200/40 text-gray-900 shadow-sm dark:border-gray-800/50 dark:from-gray-950/40 dark:to-gray-900/30 dark:text-gray-100",children:l.jsx(FU,{className:"h-3 w-3"})}):n==="geo"?l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-amber-200/70 bg-gradient-to-r from-amber-100/60 to-amber-200/40 text-amber-900 shadow-sm dark:border-amber-800/50 dark:from-amber-950/40 dark:to-amber-900/30 dark:text-amber-100",children:l.jsx(vpe,{className:"h-3 w-3"})}):n==="calculated"?l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-indigo-200/70 bg-gradient-to-r from-indigo-100/60 to-indigo-200/40 text-indigo-900 shadow-sm dark:border-indigo-800/50 dark:from-indigo-950/40 dark:to-indigo-900/30 dark:text-indigo-100",children:l.jsx(AA,{className:"h-3 w-3"})}):l.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm border border-gray-200/70 bg-gradient-to-r from-gray-100/60 to-gray-200/40 text-gray-900 shadow-sm dark:border-gray-800/50 dark:from-gray-950/40 dark:to-gray-900/30 dark:text-gray-100",children:l.jsx(eI,{className:"h-3 w-3"})})}function fqe({value:e,onChange:t,metrics:n,attributes:r}){const s=(o,i)=>(e==null?void 0:e.field.id)===o.id&&(e==null?void 0:e.type)===i;return l.jsx(gr,{children:l.jsxs("div",{className:"space-y-4",children:[n.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Value of Metric"}),l.jsxs(wn,{children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 text-muted-foreground"})}),l.jsxs(Tn,{className:"max-w-xs",children:[l.jsx("p",{className:"text-xs font-medium mb-1",children:"Captures intersection of all dimensions"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:`Example: Clicking a bar segment in "Sales by Country, stacked by State" captures both Country='USA' AND State='California'`})]})]})]}),l.jsx("div",{className:"space-y-1",children:n.map(o=>{const i=s(o,"metric");return l.jsxs(re,{variant:i?"default":"outline",size:"sm",className:Q("w-full justify-start font-normal",i&&"bg-primary text-primary-foreground"),onClick:()=>t({type:"metric",field:o}),children:[i&&l.jsx(qr,{className:"mr-2 h-4 w-4"}),bh(o.dataType),l.jsx("span",{className:"ml-2",children:o.label})]},o.id)})})]}),r.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Value of Attribute"}),l.jsxs(wn,{children:[l.jsx(Cn,{asChild:!0,children:l.jsx(hr,{className:"h-3.5 w-3.5 text-muted-foreground"})}),l.jsxs(Tn,{className:"max-w-xs",children:[l.jsx("p",{className:"text-xs font-medium mb-1",children:"Captures only this dimension"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:`Example: If configured on "State", clicking a bar in "Sales by Country, stacked by State" captures only State='California' (Country is not included)`})]})]})]}),l.jsx("div",{className:"space-y-1",children:r.map(o=>{const i=s(o,"attribute");return l.jsxs(re,{variant:i?"default":"outline",size:"sm",className:Q("w-full justify-start font-normal",i&&"bg-primary text-primary-foreground"),onClick:()=>t({type:"attribute",field:o}),children:[i&&l.jsx(qr,{className:"mr-2 h-4 w-4"}),bh(o.dataType),l.jsx("span",{className:"ml-2",children:o.label})]},o.id)})})]}),n.length===0&&r.length===0&&l.jsx("div",{className:"text-sm text-muted-foreground text-center py-8",children:"No metrics or attributes available in this chart"})]})})}const t9=[{value:"clickFilter",label:"Cross filter",description:"Filter other cards on the dashboard"},{value:"drillDown",label:"Drill down",description:"Navigate through a hierarchy of dimensions"},{value:"dynamicDrill",label:"Explore dimensions",description:"Let users explore any dimension dynamically"},{value:"drillThrough",label:"Drill into dashboard",description:"Navigate to another dashboard"},{value:"drillToDetail",label:"Drill into insight",description:"Navigate to a saved insight"},{value:"drillToURL",label:"Drill into URL",description:"Navigate to a custom URL"}];function hqe({value:e,onChange:t}){const n=t9.find(r=>r.value===e);return l.jsx("div",{className:"space-y-2",children:l.jsxs(pt,{value:e,onValueChange:t,children:[l.jsx(ft,{className:"w-full",children:l.jsx(gt,{placeholder:"Choose action...",children:n&&l.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const r=CS(n.value);return l.jsx(r,{className:"h-4 w-4"})})(),l.jsx("span",{children:n.label})]})})}),l.jsx(ht,{children:t9.map(r=>{const s=CS(r.value);return l.jsx(Ie,{value:r.value,children:l.jsxs("div",{className:"flex items-start gap-2 py-1",children:[l.jsx(s,{className:"mt-0.5 h-4 w-4 shrink-0"}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{className:"font-medium",children:r.label}),l.jsx("span",{className:"text-xs text-muted-foreground",children:r.description})]})]})},r.value)})})]})})}function mqe({interaction:e,onUpdate:t}){const[n,r]=w.useState(""),s=X7(),o=()=>e.applyToCardIds!==void 0?"specific-cards":e.excludeCardIds!==void 0?"all-except-specific":"all-cards",i=d=>{const f={};switch(d){case"all-cards":f.applyToCardIds=void 0,f.excludeCardIds=void 0;break;case"specific-cards":f.applyToCardIds=[],f.excludeCardIds=void 0;break;case"all-except-specific":f.applyToCardIds=void 0,f.excludeCardIds=[];break}t({...e,...f})},a=(d,f)=>{if(f==="specific-cards"){const h=e.applyToCardIds||[],m=h.includes(d)?h.filter(p=>p!==d):[...h,d];t({...e,applyToCardIds:m})}else if(f==="all-except-specific"){const h=e.excludeCardIds||[],m=h.includes(d)?h.filter(p=>p!==d):[...h,d];t({...e,excludeCardIds:m})}},c=w.useMemo(()=>{if(!n.trim())return s;const d=n.toLowerCase();return s==null?void 0:s.filter(f=>{var h;return(h=f==null?void 0:f.title)==null?void 0:h.toLowerCase().includes(d)})},[n,s]),u=o();return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Filter scope"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose which cards should receive the filter"})]}),l.jsxs(Do,{value:u,onValueChange:d=>i(d),className:"space-y-2",children:[l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"all-cards",id:"all-cards",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"all-cards",className:"cursor-pointer text-sm font-medium",children:"All cards"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to all cards in the dashboard"})]})]}),l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"specific-cards",id:"specific-cards",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"specific-cards",className:"cursor-pointer text-sm font-medium",children:"Only specific cards"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to selected cards only"})]})]}),u==="specific-cards"&&l.jsxs("div",{className:"ml-7 space-y-2",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Cards to filter"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Select which cards should receive the filter"})]}),l.jsx(lt,{placeholder:"Search cards...",value:n,onChange:d=>r(d.target.value),className:"mb-2"}),l.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:c&&c.length>0?c.map(d=>{const f=(e.applyToCardIds||[]).includes(d.id);return l.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[l.jsx(Jt,{id:`card-${d.id}`,checked:f,onCheckedChange:()=>a(d.id,"specific-cards")}),l.jsxs("div",{className:"flex-1",children:[l.jsx(ge,{htmlFor:`card-${d.id}`,className:"cursor-pointer text-sm font-medium",children:d.title}),d.description&&l.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:d.description})]})]},d.id)}):l.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:n?`No cards found matching "${n}"`:"No cards available"})})]}),l.jsxs("div",{className:"flex items-start space-x-3 rounded-md border bg-background p-3",children:[l.jsx($n,{value:"all-except-specific",id:"all-except-specific",className:"mt-0.5"}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx(ge,{htmlFor:"all-except-specific",className:"cursor-pointer text-sm font-medium",children:"All cards except specific ones"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Apply filter to all cards, excluding selected ones"})]})]}),u==="all-except-specific"&&l.jsxs("div",{className:"ml-7 space-y-2",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Cards to exclude"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Select which cards should be excluded from filtering"})]}),l.jsx(lt,{placeholder:"Search cards...",value:n,onChange:d=>r(d.target.value),className:"mb-2"}),l.jsx("div",{className:"grid max-h-40 grid-cols-1 gap-2 overflow-y-auto rounded-md border bg-muted/20 p-3",children:c&&c.length>0?c.map(d=>{const f=(e.excludeCardIds||[]).includes(d.id);return l.jsxs("div",{className:"flex items-center space-x-3 rounded p-2 hover:bg-background/50",children:[l.jsx(Jt,{id:`card-exclude-${d.id}`,checked:f,onCheckedChange:()=>a(d.id,"all-except-specific")}),l.jsxs("div",{className:"flex-1",children:[l.jsx(ge,{htmlFor:`card-exclude-${d.id}`,className:"cursor-pointer text-sm font-medium",children:d.title}),d.description&&l.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:d.description})]})]},d.id)}):l.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:n?`No cards found matching "${n}"`:"No cards available"})})]})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Menu label"}),l.jsx(lt,{value:e.label||"",onChange:d=>t({...e,label:d.target.value}),placeholder:Uh(e.mode)}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}function pqe(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return w.useMemo(()=>r=>{t.forEach(s=>s(r))},t)}const hE=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Bg(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function XO(e){return"nodeType"in e}function $o(e){var t,n;return e?Bg(e)?e:XO(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function QO(e){const{Document:t}=$o(e);return e instanceof t}function mv(e){return Bg(e)?!1:e instanceof $o(e).HTMLElement}function ise(e){return e instanceof $o(e).SVGElement}function Ug(e){return e?Bg(e)?e.document:XO(e)?QO(e)?e:mv(e)||ise(e)?e.ownerDocument:document:document:document}const Fa=hE?w.useLayoutEffect:w.useEffect;function mE(e){const t=w.useRef(e);return Fa(()=>{t.current=e}),w.useCallback(function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];return t.current==null?void 0:t.current(...r)},[])}function gqe(){const e=w.useRef(null),t=w.useCallback((r,s)=>{e.current=setInterval(r,s)},[]),n=w.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function Ry(e,t){t===void 0&&(t=[e]);const n=w.useRef(e);return Fa(()=>{n.current!==e&&(n.current=e)},t),n}function pv(e,t){const n=w.useRef();return w.useMemo(()=>{const r=e(n.current);return n.current=r,r},[...t])}function SS(e){const t=mE(e),n=w.useRef(null),r=w.useCallback(s=>{s!==n.current&&(t==null||t(s,n.current)),n.current=s},[]);return[n,r]}function NS(e){const t=w.useRef();return w.useEffect(()=>{t.current=e},[e]),t.current}let xT={};function gv(e,t){return w.useMemo(()=>{if(t)return t;const n=xT[e]==null?0:xT[e]+1;return xT[e]=n,e+"-"+n},[e,t])}function ase(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];return r.reduce((o,i)=>{const a=Object.entries(i);for(const[c,u]of a){const d=o[c];d!=null&&(o[c]=d+e*u)}return o},{...t})}}const Gm=ase(1),Fy=ase(-1);function bqe(e){return"clientX"in e&&"clientY"in e}function pE(e){if(!e)return!1;const{KeyboardEvent:t}=$o(e.target);return t&&e instanceof t}function xqe(e){if(!e)return!1;const{TouchEvent:t}=$o(e.target);return t&&e instanceof t}function jS(e){if(xqe(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return bqe(e)?{x:e.clientX,y:e.clientY}:null}const Si=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[Si.Translate.toString(e),Si.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+" "+n+"ms "+r}}}),n9="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function yqe(e){return e.matches(n9)?e:e.querySelector(n9)}const vqe={display:"none"};function wqe(e){let{id:t,value:n}=e;return w.createElement("div",{id:t,style:vqe},n)}function Cqe(e){let{id:t,announcement:n,ariaLiveType:r="assertive"}=e;const s={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return w.createElement("div",{id:t,style:s,role:"status","aria-live":r,"aria-atomic":!0},n)}function Sqe(){const[e,t]=w.useState("");return{announce:w.useCallback(r=>{r!=null&&t(r)},[]),announcement:e}}const lse=w.createContext(null);function Nqe(e){const t=w.useContext(lse);w.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function jqe(){const[e]=w.useState(()=>new Set),t=w.useCallback(r=>(e.add(r),()=>e.delete(r)),[e]);return[w.useCallback(r=>{let{type:s,event:o}=r;e.forEach(i=>{var a;return(a=i[s])==null?void 0:a.call(i,o)})},[e]),t]}const Eqe={draggable:`
1303
1303
  To pick up a draggable item, press the space bar.
1304
1304
  While dragging, use the arrow keys to move the item.
1305
1305
  Press space again to drop the item in its new position, or press escape to cancel.
@@ -1390,7 +1390,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1390
1390
  `)},flush(e){e.enqueue(`data: [DONE]
1391
1391
 
1392
1392
  `)}})}});var Eut=yct(()=>Vae(qi([jr({type:sn("text-start"),id:kt(),providerMetadata:Hr.optional()}),jr({type:sn("text-delta"),id:kt(),delta:kt(),providerMetadata:Hr.optional()}),jr({type:sn("text-end"),id:kt(),providerMetadata:Hr.optional()}),jr({type:sn("error"),errorText:kt()}),jr({type:sn("tool-input-start"),toolCallId:kt(),toolName:kt(),providerExecuted:Uo().optional(),dynamic:Uo().optional()}),jr({type:sn("tool-input-delta"),toolCallId:kt(),inputTextDelta:kt()}),jr({type:sn("tool-input-available"),toolCallId:kt(),toolName:kt(),input:Ja(),providerExecuted:Uo().optional(),providerMetadata:Hr.optional(),dynamic:Uo().optional()}),jr({type:sn("tool-input-error"),toolCallId:kt(),toolName:kt(),input:Ja(),providerExecuted:Uo().optional(),providerMetadata:Hr.optional(),dynamic:Uo().optional(),errorText:kt()}),jr({type:sn("tool-output-available"),toolCallId:kt(),output:Ja(),providerExecuted:Uo().optional(),dynamic:Uo().optional(),preliminary:Uo().optional()}),jr({type:sn("tool-output-error"),toolCallId:kt(),errorText:kt(),providerExecuted:Uo().optional(),dynamic:Uo().optional()}),jr({type:sn("reasoning-start"),id:kt(),providerMetadata:Hr.optional()}),jr({type:sn("reasoning-delta"),id:kt(),delta:kt(),providerMetadata:Hr.optional()}),jr({type:sn("reasoning-end"),id:kt(),providerMetadata:Hr.optional()}),jr({type:sn("source-url"),sourceId:kt(),url:kt(),title:kt().optional(),providerMetadata:Hr.optional()}),jr({type:sn("source-document"),sourceId:kt(),mediaType:kt(),title:kt(),filename:kt().optional(),providerMetadata:Hr.optional()}),jr({type:sn("file"),url:kt(),mediaType:kt(),providerMetadata:Hr.optional()}),jr({type:Pae(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:kt().optional(),data:Ja(),transient:Uo().optional()}),jr({type:sn("start-step")}),jr({type:sn("finish-step")}),jr({type:sn("start"),messageId:kt().optional(),messageMetadata:Ja().optional()}),jr({type:sn("finish"),finishReason:Aae(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:Ja().optional()}),jr({type:sn("abort")}),jr({type:sn("message-metadata"),messageMetadata:Ja()})])));function kut(e){return e.type.startsWith("data-")}function Kae(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]=Kae(o,s):n[r]=s}return n}function Tut(e){const t=["ROOT"];let n=-1,r=null;function s(c,u,d){switch(c){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(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let c=0;c<e.length;c++){const u=e[c];switch(t[t.length-1]){case"ROOT":s(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=c,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,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=c;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=c,t.pop();break}default:{n=c,s(u,c,"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=c,t.pop();break}default:{n=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=c;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=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,c+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c)):n=c;break}}}let a=e.slice(0,n+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){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 Zae(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await US({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await US({text:Tut(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function U1(e){return e.type.startsWith("tool-")}function _ut(e){return e.type==="dynamic-tool"}function ED(e){return U1(e)||_ut(e)}function oB(e){return e.type.split("-").slice(1).join("-")}function Iut({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 Mut({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,c){await r(async({state:u,write:d})=>{var f,h,m,p;function g(C){const N=u.message.parts.filter(U1).find(j=>j.toolCallId===C);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function b(C){const N=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===C);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function x(C){var S;const N=u.message.parts.find(T=>U1(T)&&T.toolCallId===C.toolCallId),j=C,k=N;N!=null?(N.state=C.state,k.input=j.input,k.output=j.output,k.errorText=j.errorText,k.rawInput=j.rawInput,k.preliminary=j.preliminary,k.providerExecuted=(S=j.providerExecuted)!=null?S:N.providerExecuted,j.providerMetadata!=null&&N.state==="input-available"&&(N.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${C.toolName}`,toolCallId:C.toolCallId,state:C.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(C){var S,N;const j=u.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===C.toolCallId),k=C,T=j;j!=null?(j.state=C.state,T.toolName=C.toolName,T.input=k.input,T.output=k.output,T.errorText=k.errorText,T.rawInput=(S=k.rawInput)!=null?S:T.rawInput,T.preliminary=k.preliminary,T.providerExecuted=(N=k.providerExecuted)!=null?N:j.providerExecuted,k.providerMetadata!=null&&j.state==="input-available"&&(j.callProviderMetadata=k.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:C.toolName,toolCallId:C.toolCallId,state:C.state,input:k.input,output:k.output,errorText:k.errorText,preliminary:k.preliminary,providerExecuted:k.providerExecuted,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}async function v(C){if(C!=null){const S=u.message.metadata!=null?Kae(u.message.metadata,C):C;t!=null&&await eB({value:S,schema:t}),u.message.metadata=S}}switch(a.type){case"text-start":{const C={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=C,u.message.parts.push(C),d();break}case"text-delta":{const C=u.activeTextParts[a.id];C.text+=a.delta,C.providerMetadata=(f=a.providerMetadata)!=null?f:C.providerMetadata,d();break}case"text-end":{const C=u.activeTextParts[a.id];C.state="done",C.providerMetadata=(h=a.providerMetadata)!=null?h:C.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const C={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=C,u.message.parts.push(C),d();break}case"reasoning-delta":{const C=u.activeReasoningParts[a.id];C.text+=a.delta,C.providerMetadata=(m=a.providerMetadata)!=null?m:C.providerMetadata,d();break}case"reasoning-end":{const C=u.activeReasoningParts[a.id];C.providerMetadata=(p=a.providerMetadata)!=null?p:C.providerMetadata,C.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 C=u.message.parts.filter(U1);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:C.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const C=u.partialToolCalls[a.toolCallId];C.text+=a.inputTextDelta;const{value:S}=await Zae(C.text);C.dynamic?y({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:S}):x({toolCallId:a.toolCallId,toolName:C.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,providerExecuted:a.providerExecuted,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,providerExecuted:a.providerExecuted,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 C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-available",input:C.input,output:a.output,preliminary:a.preliminary})}else{const C=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:oB(C),state:"output-available",input:C.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-error",input:C.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const C=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:oB(C),state:"output-error",input:C.input,rawInput:C.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}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":{a.finishReason!=null&&(u.finishReason=a.finishReason),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(kut(a)){(n==null?void 0:n[a.type])!=null&&await eB({value:a.data,schema:n[a.type]});const C=a;if(C.transient){i==null||i(C);break}const S=C.id!=null?u.message.parts.find(N=>C.type===N.type&&C.id===N.id):void 0;S!=null?S.data=C.data:u.message.parts.push(C),i==null||i(C),d()}}c.enqueue(a)})}}))}async function Dut({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()}}Tv({prefix:"aitxt",size:24});Tv({prefix:"aiobj",size:24});var Aut=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()})}};Tv({prefix:"aiobj",size:24});var Rut={};gut(Rut,{object:()=>Put,text:()=>Fut});var Fut=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Put=({schema:e})=>{const t=mut(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await Zae(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 US({text:n});if(!s.success)throw new rB({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 U5({value:s.value,schema:t});if(!o.success)throw new rB({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}}};async function Out(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=c=>{var u;o((u=c.target)==null?void 0:u.result)},a.onerror=c=>i(c),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var Lut=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 cm(this.body),c=await cm(this.headers),u=await cm(this.credentials),d={...Kd(c),...Kd(t.headers)},f=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:d,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),h=(r=f==null?void 0:f.api)!=null?r:this.api,m=(f==null?void 0:f.headers)!==void 0?Kd(f.headers):d,p=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},g=(s=f==null?void 0:f.credentials)!=null?s:u,x=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:QV({"Content-Type":"application/json",...m},`ai-sdk/${sB}`,XV()),body:JSON.stringify(p),credentials:g,signal:e});if(!x.ok)throw new Error((i=await x.text())!=null?i:"Failed to fetch the chat response.");if(!x.body)throw new Error("The response body is empty.");return this.processResponseStream(x.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await cm(this.body),a=await cm(this.headers),c=await cm(this.credentials),u={...Kd(a),...Kd(e.headers)},d=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:u,credentials:c,requestMetadata:e.metadata})),f=(n=d==null?void 0:d.api)!=null?n:`${this.api}/${e.chatId}/stream`,h=(d==null?void 0:d.headers)!==void 0?Kd(d.headers):u,m=(r=d==null?void 0:d.credentials)!=null?r:c,g=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:QV(h,`ai-sdk/${sB}`,XV()),credentials:m});if(g.status===204)return null;if(!g.ok)throw new Error((o=await g.text())!=null?o:"Failed to fetch the chat response.");if(!g.body)throw new Error("The response body is empty.");return this.processResponseStream(g.body)}},W5=class extends Lut{constructor(e={}){super(e)}processResponseStream(e){return Cct({stream:e,schema:Eut}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},$ut=class{constructor({generateId:e=fct,id:t=e(),transport:n=new W5,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:c,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new Aut,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await Out(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(p=>p.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(C=>ED(C)&&C.toolCallId===m?{...C,state:f,output:p,errorText:g}:C)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(C=>ED(C)&&C.toolCallId===m?{...C,state:f,output:p,errorText:g}:C)),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.addToolResult=this.addToolOutput,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=c,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,c;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const m={state:Iut({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;let p;if(e==="resume-stream"){const b=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(b==null){this.setStatus({status:"ready"});return}p=b}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=b=>this.jobExecutor.run(()=>b({state:m.state,write:()=>{var x;this.setStatus({status:"streaming"}),m.state.message.id===((x=this.lastMessage)==null?void 0:x.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await Dut({stream:Mut({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:g,onError:b=>{throw b}}),onError:b=>{throw b}}),this.setStatus({status:"ready"})}catch(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(c=this.lastMessage)==null?void 0:c.id,metadata:t,headers:n,body:r})}};function Xae({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(ED).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function zut(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,c=t-a;c<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},c)}}var Vut=zut;const But=Ch(Vut);var Qae=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},dr=(e,t,n)=>(Qae(e,t,"read from private field"),n?n.call(e):t.get(e)),Ya=(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)},du=(e,t,n,r)=>(Qae(e,t,"write to private field"),t.set(e,n),n);function Uut(e,t){return t!=null?But(e,t):e}var Ti,H1,W1,ix,ax,lx,bm,kD,TD,Hut=class{constructor(e=[]){Ya(this,Ti,void 0),Ya(this,H1,"ready"),Ya(this,W1,void 0),Ya(this,ix,new Set),Ya(this,ax,new Set),Ya(this,lx,new Set),this.pushMessage=t=>{du(this,Ti,dr(this,Ti).concat(t)),dr(this,bm).call(this)},this.popMessage=()=>{du(this,Ti,dr(this,Ti).slice(0,-1)),dr(this,bm).call(this)},this.replaceMessage=(t,n)=>{du(this,Ti,[...dr(this,Ti).slice(0,t),this.snapshot(n),...dr(this,Ti).slice(t+1)]),dr(this,bm).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?Uut(t,n):t;return dr(this,ix).add(r),()=>{dr(this,ix).delete(r)}},this["~registerStatusCallback"]=t=>(dr(this,ax).add(t),()=>{dr(this,ax).delete(t)}),this["~registerErrorCallback"]=t=>(dr(this,lx).add(t),()=>{dr(this,lx).delete(t)}),Ya(this,bm,()=>{dr(this,ix).forEach(t=>t())}),Ya(this,kD,()=>{dr(this,ax).forEach(t=>t())}),Ya(this,TD,()=>{dr(this,lx).forEach(t=>t())}),du(this,Ti,e)}get status(){return dr(this,H1)}set status(e){du(this,H1,e),dr(this,kD).call(this)}get error(){return dr(this,W1)}set error(e){du(this,W1,e),dr(this,TD).call(this)}get messages(){return dr(this,Ti)}set messages(e){du(this,Ti,[...e]),dr(this,bm).call(this)}};Ti=new WeakMap;H1=new WeakMap;W1=new WeakMap;ix=new WeakMap;ax=new WeakMap;lx=new WeakMap;bm=new WeakMap;kD=new WeakMap;TD=new WeakMap;var xm,iB=class extends $ut{constructor({messages:e,...t}){const n=new Hut(e);super({...t,state:n}),Ya(this,xm,void 0),this["~registerMessagesCallback"]=(r,s)=>dr(this,xm)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>dr(this,xm)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>dr(this,xm)["~registerErrorCallback"](r),du(this,xm,n)}};xm=new WeakMap;function Jae({experimental_throttle:e,resume:t=!1,...n}={}){const r=w.useRef("chat"in n?n.chat:new iB(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new iB(n));const o="id"in n?n.id:null,i=w.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=w.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),c=w.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=w.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=w.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return w.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:c,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function Wut(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function qut(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function Yut(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function Gut(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function ele(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:Gut(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function tle(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 PE(e,t){var n;if((n=e.sheets)!=null&&n.length)return t&&e.sheets.find(r=>r.id===t)||e.sheets[0]}function nle(e,t,n){const r=PE(e,t);if(!r)return[];const s=o=>{var i;return{sourceCard:o,visibleCard:((i=n==null?void 0:n[o.id])==null?void 0:i.visibleCard)||o,...n!=null&&n[o.id]?{replacedCard:n[o.id]}:{}}};return(r.frames||[]).map(o=>lj(o)).filter(o=>o!==void 0).map(s)}function rle(e){var n;return(((n=e.dataSource)==null?void 0:n.selectedEntities)||[]).map(r=>({name:r.name,type:r.type,connectionId:r.connectionId,...r.label?{label:r.label}:{}}))}function Kut(e){return{id:(e==null?void 0:e.id)||"",name:(e==null?void 0:e.name)||"",label:(e==null?void 0:e.label)||(e==null?void 0:e.name)||"",...e!=null&&e.dataType?{dataType:e.dataType}:{},...e!=null&&e.aggregate?{aggregate:e.aggregate}:{},...e!=null&&e.granularity?{granularity:e.granularity}:{},...e!=null&&e.direction?{direction:e.direction}:{}}}function Dm(e){return(e||[]).map(Kut)}function sle(e){return Dm([...(e==null?void 0:e.groupByColumns)||[],...(e==null?void 0:e.pivotByColumns)||[],...(e==null?void 0:e.detailColumns)||[]])}function q5(e){const t={operation:e.operation};return"value"in e&&e.value!==void 0&&(t.value=e.value),"values"in e&&Array.isArray(e.values)&&(t.values=e.values),t}function Zut(e,t,n){const r=new Map((e||[]).map(s=>[s.id,s]));return(t||[]).map(s=>{const o=r.get(s.filterId);return{filterId:s.filterId,label:(o==null?void 0:o.title)||s.label||s.name||s.filterId,...o!=null&&o.type?{type:o.type}:{},...o!=null&&o.column||s.name?{column:(o==null?void 0:o.column)||s.name}:{},...o!=null&&o.dataType?{dataType:o.dataType}:{},origin:n,...q5(s)}})}function Xut(e){return(e||[]).map(t=>({filterId:t.filterId,label:t.label||t.name||t.filterId,...t.name?{column:t.name}:{},origin:"inline",...q5(t)}))}function ole(e,t){var n,r,s,o,i,a,c;return{filterId:t,label:((n=e.field)==null?void 0:n.label)||((r=e.field)==null?void 0:r.name)||t,...(s=e.field)!=null&&s.qualifiedFieldName||(o=e.field)!=null&&o.name?{column:((i=e.field)==null?void 0:i.qualifiedFieldName)||((a=e.field)==null?void 0:a.name)}:{},...(c=e.field)!=null&&c.dataType?{dataType:e.field.dataType}:{},origin:"interaction",operation:e.operator,...e.value!==void 0?{value:e.value}:{}}}function ZT(e,t){return(e||[]).flatMap((n,r)=>(n.filters||[]).map((s,o)=>ole(s,`${t}:${r}:${o}`)))}function Qut(e){return!!e&&typeof e=="object"&&"field"in e&&"operator"in e}function Jut(e){return!!e&&typeof e=="object"&&"filterId"in e&&"operation"in e}function edt(e){if(!e)return{dashboardFilterValues:[],interactionFilterValues:[]};const t=e.filter(Jut).map(r=>({filterId:r.filterId,label:r.label||r.name||r.filterId,...r.name?{column:r.name}:{},origin:"dashboard",...q5(r)})),n=e.filter(Qut).map((r,s)=>ole(r,`replaced-insight:${s}`));return{dashboardFilterValues:t,interactionFilterValues:n}}function tdt({card:e,interactionStates:t,currentDashboardId:n}){var c;if(!t)return[];const r=ZD(e.id,t),s=t[fa],i=(s==null?void 0:s.targetDashboardId)===n&&(s==null?void 0:s.contextMode)!=="none"?(s==null?void 0:s.appliedClickFilters)||[]:[],a=((c=t[e.id])==null?void 0:c.breadcrumbs)??[];return[...r.flatMap((u,d)=>ZT(u.filterGroups,`interaction:${u.sourceCardId||e.id}:${d}`)),...i.flatMap((u,d)=>ZT(u.filterGroups,`global-interaction:${u.sourceCardId||e.id}:${d}`)),...a.flatMap((u,d)=>ZT(u.sourceFilterGroups,`breadcrumb:${e.id}:${d}`))]}function ile(e){return e?{logicalOperator:e.logicalOperator,negate:e.negate,conditions:(e.conditions||[]).map(t=>{var n,r;return{field:((n=t.field)==null?void 0:n.label)||((r=t.field)==null?void 0:r.name)||"",operator:t.operator,value:t.value}}),groups:(e.groups||[]).map(t=>ile(t)).filter(Boolean)}:null}function ale(e){var n;const t=(n=e.python)==null?void 0:n.trim();return!!t&&t!==JD.trim()}function ndt(e){var t;return(t=e.sql)!=null&&t.trim()?"custom-sql":ale(e)?"custom-python":"config"}function lle({sourceCard:e,card:t,replacedCard:n,dashboard:r,viewState:s,runtimeFilterValues:o,interactionStates:i,inlineFilterValuesMap:a}){const c=PE(r,s.selectedSheetId),u=(c==null?void 0:c.id)||s.selectedSheetId,{finalConfig:d}=I0({card:t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u,inlineFilterValuesMap:a}),f=_0({card:e||t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u}),h=edt(n==null?void 0:n.filters),m=!!n&&n.filters!==void 0;return{selectedSheetId:u,finalConfig:d,dashboardFilterValues:m?h.dashboardFilterValues:Zut(f.cardFilters,f.cardFilterValues,"dashboard"),inlineFilterValues:Xut(a==null?void 0:a[t.id]),interactionFilterValues:m?h.interactionFilterValues:tdt({card:t,interactionStates:i,currentDashboardId:r.id})}}function rdt({sourceCard:e,visibleCard:t,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o,replacedCard:i,renderOrder:a}){const{finalConfig:c}=lle({sourceCard:e,card:t,replacedCard:i,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o});return{cardId:e.id,...e.id!==t.id?{visibleCardId:t.id}:{},...i!=null&&i.insightId?{replacementInsightId:i.insightId}:{},title:t.title||"Untitled Card",type:t.type,renderOrder:a,metrics:Dm(c.metricColumns),dimensions:sle(c),selectedEntities:rle(t)}}function sdt({activeFilters:e}){return Array.from(new Set((e||[]).map(t=>t.filterId)))}function aB({dashboard:e,selectedSheetId:t,activeFilters:n}){var s;const r=((s=PE(e,t??null))==null?void 0:s.id)||t||null;return{selectedSheetId:r,activeFilters:tS(e.filters,n,r)}}function odt({dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCards:s}){const o=PE(e,t.selectedSheetId),i=(o==null?void 0:o.id)||t.selectedSheetId,a=nle(e,t.selectedSheetId,s),c=Yl(e.filters,i);return{dashboardId:e.id,dashboardTitle:e.title||"Untitled Dashboard",selectedSheetId:i,sheetTitle:(o==null?void 0:o.title)||"Untitled Sheet",cards:a.map(({sourceCard:u,visibleCard:d,replacedCard:f},h)=>rdt({sourceCard:u,visibleCard:d,dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCard:f,renderOrder:h})),availableFilters:c.map(u=>{var d,f;return{filterId:u.id,label:u.title,...u.type?{type:u.type}:{},scope:(d=u.applyToCardIds)!=null&&d.length||(f=u.excludeCardIds)!=null&&f.length?"card":"sheet"}}),activeFilterIds:sdt({activeFilters:t.activeFilters})}}function idt({dashboard:e,viewState:t,cardId:n,runtimeFilterValues:r,interactionStates:s,inlineFilterValuesMap:o,replacedCards:i}){var v,C;const c=nle(e,t.selectedSheetId,i).find(({sourceCard:S,visibleCard:N})=>S.id===n||N.id===n);if(!c)return{found:!1,cardId:n,selectedEntities:[],metrics:[],dimensions:[],comparison:null,cardFilters:null,effectiveDashboardFilters:[],activeInlineFilters:[],activeInteractionFilters:[],sortingOrGroupingSummary:{groupBy:[],pivotBy:[],sortBy:[]},notes:["Card not found in the current selected sheet."]};const{sourceCard:u,visibleCard:d,replacedCard:f}=c,{finalConfig:h,dashboardFilterValues:m,inlineFilterValues:p,interactionFilterValues:g}=lle({sourceCard:u,card:d,replacedCard:f,interactionStates:s,dashboard:e,viewState:t,runtimeFilterValues:r,inlineFilterValuesMap:o}),{comparisonType:b,targetValue:x}=hre(h,d.type),y=ndt(d);return{found:!0,cardId:u.id,...u.id!==d.id?{visibleCardId:d.id}:{},...f!=null&&f.insightId?{replacementInsightId:f.insightId}:{},title:d.title,type:d.type,queryMode:y,...(v=d.sql)!=null&&v.trim()?{sql:d.sql.trim()}:{},...ale(d)?{python:(C=d.python)==null?void 0:C.trim()}:{},selectedEntities:rle(d),metrics:Dm(h.metricColumns),dimensions:sle(h),comparison:b!=="none"?{type:b,...x!==void 0?{targetValue:x}:{}}:null,cardFilters:ile(h.filters),effectiveDashboardFilters:m,activeInlineFilters:p,activeInteractionFilters:g,sortingOrGroupingSummary:{groupBy:Dm(h.groupByColumns),pivotBy:Dm(h.pivotByColumns),sortBy:Dm(h.sortByColumns)},notes:[...f?["This frame is currently showing a linked insight replacement."]:[],...y==="custom-sql"?["This card runs custom SQL."]:y==="custom-python"?["This card runs custom Python."]:[]]}}function ym(){return crypto.randomUUID()}function cle(){return crypto.randomUUID()}function _D(e){return typeof(e==null?void 0:e.then)=="function"}async function adt({replacedCards:e,apiServiceUrl:t,accessToken:n,queryClient:r}){const s=Object.entries(e);if(s.length===0||!n)return{};const o=await Promise.all(s.map(async([i,a])=>{const c=["resource-by-id",Xr.VISUAL,a.insightId];let u=r.getQueryData(c);if(!u)try{u=await r.fetchQuery({queryKey:c,queryFn:()=>or(`${t}/management/v1/visuals/${a.insightId}`,n)})}catch{return null}const d=jZ(u);return d?[i,{insightId:a.insightId,visibleCard:d,filters:a.filters,contextMode:a.contextMode}]:null}));return Object.fromEntries(o.filter(i=>i!==null))}function ldt({dynamicVisualMode:e="auto"}={}){var M;const{authToken:t,tokenProps:n}=rt(),r=cs(),s=ee(P=>P.dashboard.aiScopeTables),o=(M=uN().data)==null?void 0:M.assistantProfileId,i=w.useRef(null),a=w.useRef(ym()),c=w.useRef(!1),u=w.useRef(!1),d=w.useRef(e);d.current=e;function f(){const P=gs.getState(),D=ee.getState(),A=kZ({overrides:P.dashboardEntitySelectionOverrides,dashboardId:D.dashboard.id,draftScopeKey:D.dashboardAssistantDraftScopeKey});return mA(HIe({currentAIContext:P.currentAIContext,manualSelectedEntities:A.selectedEntities,hasManualOverride:A.hasManualOverride,dashboardAIContext:D.dashboard.aiContext,derivedSelectedSheetEntities:EZ(D.dashboard,D.selectedSheetId)}))}function h(){const P=ee.getState();return{aiContext:f(),dashboardViewState:aB({dashboard:P.dashboard,selectedSheetId:P.selectedSheetId,activeFilters:P.filterValues})}}const{sendMessage:m,messages:p,setMessages:g,regenerate:b,status:x,addToolResult:y,error:v,stop:C,clearError:S}=Jae({transport:new W5({api:`${n.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${t==null?void 0:t.accessToken}`}),body:()=>{const P=gs.getState();i.current||(i.current=h());const{aiContext:D,dashboardViewState:A}=i.current;return{assistantId:"dashboard-assistant",assistantProfileId:o,conversationId:a.current,assistantRequestId:cle(),aiContext:D,dashboardViewState:A,dynamicVisualMode:d.current,dynamicVisualTheme:LO(),reasoningEffort:P.reasoningEffort,showReasoning:P.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:P,body:D})=>({body:{...D,messages:A7(P)}})}),onToolCall:T,sendAutomaticallyWhen:Xae,onFinish({message:P,isAbort:D,isDisconnect:A,isError:L}){var $;u.current=!1,P!=null&&P.id&&(($=i.current)!=null&&$.aiContext)&&gs.getState().actions.setAssistantMessageContext(P.id,i.current.aiContext),console.log(D?"[Dashboard Assistant] Stream aborted by user":A?"[Dashboard Assistant] Stream disconnected (network error)":L?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully"),i.current=null,c.current&&(c.current=!1,a.current=ym(),g([]))},onError(P){var D;if(u.current=!1,P.name==="AbortError"||(D=P.message)!=null&&D.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)"),i.current=null,c.current&&(c.current=!1,a.current=ym(),g([]));return}console.error("[Dashboard Assistant] Stream error:",P),i.current=null,c.current&&(c.current=!1,a.current=ym(),g([]))}}),N=w.useCallback((...P)=>{u.current=!0;try{const D=m(...P);return _D(D)?D.catch(A=>{throw u.current=!1,A}):D}catch(D){throw u.current=!1,D}},[m]),j=w.useCallback((...P)=>{u.current=!0;try{const D=b(...P);return _D(D)?D.catch(A=>{throw u.current=!1,A}):D}catch(D){throw u.current=!1,D}},[b]),k=P=>{let D=!1;g(A=>{const L=typeof P=="function"?P(A):P;if(L.length===0){if(u.current)return c.current=!0,D=!0,A;c.current=!1,a.current=ym()}return L}),D&&C()};async function T({toolCall:P}){var R,U;if(P.toolName==="getCurrentTableScope"){y({tool:P.toolName,toolCallId:P.toolCallId,output:{tables:ele(s||[])}});return}const D=ee.getState().dashboard,A=ee.getState().inlineFilterValuesMap,L=Vt.getState(),$=L.interactionStates,B=await adt({replacedCards:L.replacedCards,apiServiceUrl:n.apiServiceUrl,accessToken:(t==null?void 0:t.accessToken)||"",queryClient:r}),V=aB({dashboard:D,selectedSheetId:ee.getState().selectedSheetId,activeFilters:ee.getState().filterValues});if(P.toolName==="getDashboardSynopsis"){y({tool:P.toolName,toolCallId:P.toolCallId,output:odt({dashboard:D,viewState:V,interactionStates:$,inlineFilterValuesMap:A,replacedCards:B})});return}if(P.toolName==="getCardContext"){const O=((R=P.input)==null?void 0:R.cardId)||((U=P.args)==null?void 0:U.cardId)||"";y({tool:P.toolName,toolCallId:P.toolCallId,output:idt({dashboard:D,viewState:V,cardId:O,runtimeFilterValues:ee.getState().filterValues,interactionStates:$,inlineFilterValuesMap:A,replacedCards:B})})}}const E=!["ready","error"].includes(x),_=tle(v);return{sendMessage:N,regenerate:j,isLoading:E,messages:p,setMessages:k,status:x,stop:C,errorMessage:_,clearError:S}}function ule(){var u;const{authToken:e,tokenProps:t}=rt(),n=(u=uN().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=Qt({queryKey:["assistant-profile",n],queryFn:()=>or(`${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 dle({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:l.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[l.jsxs("div",{className:"mb-3 flex items-center",children:[l.jsx(RU,{className:"mr-2 h-4 w-4 text-muted-foreground"}),l.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>l.jsx(re,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function cdt({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=w.useRef(null),o=async a=>{const c=Array.from(a.target.files||[]);if(c.length===0)return;const u=ac-n;if(c.length>u){qe.error(`You can only attach ${ac} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=Hie(c);if(f.forEach(({file:h,error:m})=>{qe.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>F5(m)));e(h)}catch(h){console.error("Failed to process files:",h),qe.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return l.jsxs(l.Fragment,{children:[l.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>=ac}),l.jsx(re,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=ac,title:n>=ac?`Maximum ${ac} files allowed`:"Attach files",children:l.jsx(qA,{className:"h-4 w-4 text-muted-foreground"})})]})}function udt({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=w.useState(!1),a=w.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),c=w.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=w.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=w.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const m=ac-r;if(h.length>m){qe.error(`You can only attach ${ac} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=Hie(h);if(g.forEach(({file:b,error:x})=>{qe.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>F5(x)));t(b),qe.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),qe.error("Failed to process one or more files")}},[n,r,t]);return l.jsxs("div",{className:Q("relative",s),onDragEnter:a,onDragLeave:c,onDragOver:u,onDrop:d,children:[e,o&&!n&&l.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:l.jsxs("div",{className:"flex flex-col items-center gap-2",children:[l.jsx(tR,{className:"h-8 w-8 text-primary"}),l.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:[ac-r," slot(s) available"]})]})})]})}function fle(e){return e.type==="dataset"&&e.label||e.name}function ddt(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 fdt({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:l.jsxs("div",{className:"mb-4 space-y-2",children:[l.jsxs(ge,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),l.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:l.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>l.jsxs(Xe,{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:[l.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),fle(n),l.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:l.jsx(Mt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function hdt(e){const{tokenProps:t}=rt(),n=ee(c=>c.authToken)||e;Ve(c=>c.selectedConnectionId),Ve(c=>{var u,d;return(d=(u=c==null?void 0:c.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=Qt({queryKey:["semantic-domains"],queryFn:()=>or(`${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 mdt(e,t){const{tokenProps:n}=rt(),r=ee(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:c}=Qt({queryKey:["datasets",e],queryFn:()=>or(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:c,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:c,refetchDatasets:s}}function pdt(e){var g,b;const{tokenProps:t}=rt(),n=ee(x=>x.authToken)||e,{connections:r}=Xi(e),s=Ve(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,c=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){var y;return!s||!x?!1:!!((y=o==null?void 0:o.capabilities)!=null&&y.path.includes("database"))}const{data:d,isPending:f,error:h,refetch:m}=Qt({queryKey:["databases",s],queryFn:()=>or(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:c}}function gdt(e){var g;const{tokenProps:t}=rt(),n=ee(b=>b.authToken)||e,{connections:r}=Xi(e),s=Ve(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Ve(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,c=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){var b;return!(!s||!((b=i==null?void 0:i.capabilities)!=null&&b.path.includes("schema"))||!o)}const{data:d,isPending:f,error:h,refetch:m}=Qt({queryKey:["schemas",s,o],queryFn:()=>or(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:c}}function hle(e){const{tokenProps:t}=rt(),n=ee(h=>h.authToken)||e,{connections:r}=Xi(e),s=Ve(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:c,error:u,refetch:d}=Qt({queryKey:["dataModels",s],queryFn:()=>or(`${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:c,error:u,dataModels:f||[],refetch:d}}function bdt(){var S,N,j;const e=Ve(k=>k.card.dataSource);Ve(k=>k.actions.updateDirectSource);const t=Ve(k=>k.actions.updateDataSource),[n,r]=w.useState(""),{selectedConnection:s,error:o}=Xi(),{databases:i,isPending:a,error:c,label:u}=pdt(),{schemas:d,isPending:f,error:h,label:m}=gdt(),{error:p}=hle(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=k=>{e&&t({...e,dbSelection:{database:k,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},C=k=>{var E;if(!((E=e==null?void 0:e.dbSelection)!=null&&E.database))return;const T=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...T,schema:k},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return l.jsxs(l.Fragment,{children:[(o||c||h||p)&&l.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[l.jsx("div",{className:"flex items-center",children:l.jsxs("div",{className:"text-sm text-red-800",children:[l.jsx("strong",{children:"Error loading data:"}),l.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&l.jsxs("li",{children:["Connections: ",o]}),c&&l.jsxs("li",{children:[u,": ",c.message]}),h&&l.jsxs("li",{children:[m,": ",h.message]}),p&&l.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),l.jsx(re,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),l.jsxs("div",{className:"space-y-4",children:[b&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{className:"text-sm font-medium",children:u}),l.jsxs(pt,{value:((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)||"",onValueChange:v,disabled:a,children:[l.jsx(ft,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[a&&l.jsx(Mn,{className:"h-4 w-4 animate-spin"}),l.jsx(gt,{placeholder:c?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),l.jsx(ht,{children:i.map(k=>l.jsx(Ie,{className:"hover:bg-muted",value:k.id,children:k.name},k.id))})]})]}),((N=e==null?void 0:e.dbSelection)==null?void 0:N.database)&&g&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{className:"text-sm font-medium",children:m}),l.jsxs(pt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:C,disabled:f,children:[l.jsx(ft,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[f&&l.jsx(Mn,{className:"h-4 w-4 animate-spin"}),l.jsx(gt,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),l.jsx(ht,{children:d.map(k=>l.jsx(Ie,{className:"hover:bg-muted",value:k.id,children:k.name},k.id))})]})]})]})]})}function xdt(){const e=Ve(c=>c.card.dataSource),t=Ve(c=>c.actions.updateDataSource),[n,r]=w.useState(!1),s=c=>{if(!c||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(c).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=c=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==c);t({...e,selectedEntities:u})},i=c=>{if(c===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(c)/Math.log(u));return Number.parseFloat((c/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Upload Files"}),l.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:c=>{c.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:c=>{c.preventDefault(),r(!1),s(c.dataTransfer.files)},children:[l.jsx(tR,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),l.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),l.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:c=>s(c.target.files),accept:".csv,.json,.xlsx,.xls"}),l.jsx(re,{variant:"outline",size:"sm",onClick:()=>{var c;return(c=document.getElementById("file-upload"))==null?void 0:c.click()},children:"Select Files"}),l.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs(ge,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(c=>l.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(ka,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("p",{className:"truncate text-sm text-gray-700",children:c.originalName}),l.jsx("p",{className:"text-xs text-gray-500",children:c.file?i(c.file.size):""})]})]}),l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(c.id),children:l.jsx(Mt,{className:"h-3 w-3"})})]},c.id))})]})]})}function ydt(){const e=Ve(f=>f.card.dataSource),t=Ve(f=>f.actions.updateDataSource),[n,r]=w.useState(""),[s,o]=w.useState(""),[i,a]=w.useState("api"),c=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(m=>m.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),l.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{className:"text-xs text-gray-600",children:"Source Name"}),l.jsx(lt,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{className:"text-xs text-gray-600",children:"URL"}),l.jsx(lt,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{className:"text-xs text-gray-600",children:"Type"}),l.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:[l.jsx("option",{value:"api",children:"API Endpoint"}),l.jsx("option",{value:"csv",children:"CSV File"}),l.jsx("option",{value:"json",children:"JSON File"})]})]}),l.jsxs(re,{onClick:c,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[l.jsx($r,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs(ge,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>l.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(pN,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),l.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:l.jsx(Mt,{className:"h-3 w-3"})})]},f.id))})]})]})}function vdt(e,t){var y,v;const{tokenProps:n}=rt(),r=ee(C=>C.authToken)||t,{connections:s}=Xi(t),o=Ve(C=>{var S,N;return(N=(S=C==null?void 0:C.card)==null?void 0:S.dataSource)==null?void 0:N.connectionId}),i=Ve(C=>{var S,N,j;return(j=(N=(S=C==null?void 0:C.card)==null?void 0:S.dataSource)==null?void 0:N.dbSelection)==null?void 0:j.database}),a=Ve(C=>{var S,N,j;return(j=(N=(S=C==null?void 0:C.card)==null?void 0:S.dataSource)==null?void 0:N.dbSelection)==null?void 0:j.schema}),c=s==null?void 0:s.find(C=>C.id===o),u=c==null?void 0:c.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){if(!o)return!1;const C=(u==null?void 0:u.path)||[];return!(C.includes("database")&&!i||C.includes("schema")&&!a)}const{data:h,isPending:m,isLoading:p,error:g,refetch:b}=Qt({queryKey:[e,o,i,a],queryFn:()=>or(`${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(C=>{var S;return{connectionId:c==null?void 0:c.id,connectionType:c==null?void 0:c.type,dialect:c==null?void 0:c.dialect,type:e,dbObjectType:(S=C==null?void 0:C.table_type)==null?void 0:S.toLowerCase(),id:C[`${e}_name`],database:i,schema:a,name:C[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function HS({title:e,message:t}){return l.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:l.jsxs("div",{className:"flex items-start gap-4",children:[l.jsx($c,{className:"h-6 w-6 flex-shrink-0"}),l.jsxs("div",{className:"flex-1",children:[l.jsx("h4",{className:"text-base font-semibold",children:e}),t&&l.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function wdt({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Xi(),[i,a]=w.useState(""),[c,u]=w.useState(""),[d,f]=w.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=lr(),{entities:p,isLoading:g,error:b}=vdt("table"),{dataModels:x,isPending:y,error:v}=hle(),C=E=>{const _=s.find(P=>P.id===E);if(!_)return;const M=_.type==="upload"?"upload":_.type==="url"?"url":"database";h({...e,connectionId:E,connectionType:_.type,mode:M,dbSelection:{database:"",schema:"",entityType:"table"}}),m(E)},S=E=>{var D,A;const _=n||[],M=_.some(L=>L.name===E.name&&L.type===E.type);let P;if(M)P=_.filter(L=>!(L.name===E.name&&L.type===E.type));else{const L={connectionId:e.connectionId,connectionType:e.connectionType,type:E.type,dbObjectType:E.dbObjectType,database:((D=e.dbSelection)==null?void 0:D.database)||"",schema:((A=e.dbSelection)==null?void 0:A.schema)||"",name:E.name,dialect:E.dialect};P=[..._,L]}t==null||t(P)},N=E=>{const _=n||[],M=_.some(D=>D.type==="model"&&D.name===E.name);let P;M?P=_.filter(D=>!(D.type==="model"&&D.name===E.name)):P=[..._,E],t==null||t(P)},j=p.filter(E=>E.name.toLowerCase().includes(i.toLowerCase())),k=x.filter(E=>E.name.toLowerCase().includes(c.toLowerCase())),T=w.useCallback(()=>{if(!t)return;const E=n||[];let _=[...E];if(d==="tables"){const P=j.filter(D=>!E.some(A=>A.name===D.name&&A.type==="table")).map(D=>{var A,L;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:D.dbObjectType,database:((A=e.dbSelection)==null?void 0:A.database)||"",schema:((L=e.dbSelection)==null?void 0:L.schema)||"",name:D.name,dialect:D.dialect}});_=[...E,...P]}else if(d==="datamodels"){const M=k.filter(P=>!E.some(D=>D.name===P.name&&D.type==="model"));_=[...E,...M]}t(_)},[d,j,k,n,e,t]);return w.useEffect(()=>{r&&r(T)},[r,T]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{className:"font-medium= text-sm",children:"Connection"}),l.jsxs(pt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:C,disabled:o,children:[l.jsx(ft,{className:"w-full",children:l.jsx(gt,{placeholder:o?"Loading connections...":"Select connection..."})}),l.jsx(ht,{children:s.map(E=>l.jsx(Ie,{className:"hover:bg-muted",value:E.id,children:l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(pl,{className:"h-4 w-4 flex-shrink-0"}),l.jsx("span",{className:"truncate",children:E.name}),l.jsx(Xe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:E.type})]})},E.id))})]})]}),(e==null?void 0:e.connectionId)&&l.jsxs(l.Fragment,{children:[e.connectionType==="upload"&&l.jsx(xdt,{}),e.connectionType==="url"&&l.jsx(ydt,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&l.jsxs(l.Fragment,{children:[l.jsx(bdt,{}),l.jsx("div",{className:"space-y-4",children:l.jsx("div",{className:"space-y-2",children:l.jsxs(As,{defaultValue:"tables",value:d,onValueChange:E=>f(E),className:"w-full",children:[l.jsxs(ys,{className:"grid w-full grid-cols-2",children:[l.jsxs(on,{value:"tables",children:["Tables & Views (",j.length,")"]}),l.jsxs(on,{value:"datamodels",children:["Data Models (",k.length,")"]})]}),l.jsxs(sr,{value:"tables",className:"space-y-2",children:[l.jsx(lt,{placeholder:"Search tables and views...",value:i,onChange:E=>a(E.target.value),className:"h-8 text-sm",disabled:g}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?l.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?l.jsx(HS,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?l.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(E=>{const _=n.some(M=>M.name===E.name&&M.type==="table");return l.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(E),children:[l.jsx(Jt,{id:`table-${E.name}`,checked:_,onCheckedChange:()=>S(E),onClick:M=>M.stopPropagation(),disabled:g}),l.jsxs(ge,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[E.name,E.dbObjectType==="view"&&l.jsx(Xe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),E.dbObjectType==="materialized view"&&l.jsx(Xe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},E.name)})})]}),l.jsxs(sr,{value:"datamodels",className:"space-y-2",children:[l.jsx(lt,{placeholder:"Search data models...",value:c,onChange:E=>u(E.target.value),className:"h-8 text-sm",disabled:y}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?l.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?l.jsx(HS,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):k.length===0?l.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):k.map(E=>{const _=n.some(M=>M.name===E.name&&M.type==="model");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>N(E),children:[l.jsx(Jt,{id:`dataModel-${E.name}`,checked:_,onCheckedChange:()=>N(E),onClick:M=>M.stopPropagation(),disabled:y}),l.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[l.jsx(ge,{className:"cursor-pointer",children:E.name}),l.jsx("span",{className:"text-xs text-muted-foreground",children:E.description})]})]},E.name)})})]})]})})})]})]})]})}function Cdt({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,domainAccess:s=Tc.DEFAULT_SEMANTIC_DOMAIN_ACCESS,autoSelectedDomainId:o,onRegisterSelectAll:i}){var C;const[a,c]=w.useState(""),u=w.useCallback(S=>{const N={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...N})},[e,t]);w.useEffect(()=>{o&&!(e!=null&&e.semanticDomainId)&&u(o)},[o,e==null?void 0:e.semanticDomainId,u]);const{semanticDomains:d,isPending:f,error:h}=hdt(),m=d.filter(S=>{var N,j;switch(s.mode){case"all":return!0;case"none":return!1;case"include":return((N=s.domainIds)==null?void 0:N.includes(S.id))??!1;case"exclude":return!(((j=s.domainIds)==null?void 0:j.includes(S.id))??!1);default:return!0}}),{datasets:p,isPending:g,error:b}=mdt(e==null?void 0:e.semanticDomainId),x=S=>{const N=r||[],j=N.some(T=>T.id===S.id&&T.type==="dataset");let k;if(j)k=N.filter(T=>!(T.id===S.id&&T.type==="dataset"));else{const T={id:S.id,datasetType:S.type,name:S.name||S.table,label:S.label,domainId:S.domainId,description:S.description,database:S.database,schema:S.schema,type:"dataset",connectionId:S.connectionId,connectionType:S.connectionType,dialect:S.dialect,datamodelId:S.datamodelId,sql:S.sql};k=[...N,T]}n==null||n(k)},y=p.filter(S=>S.name.toLowerCase().includes(a.toLowerCase())),v=w.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const S=r||[],j=y.filter(T=>!S.some(E=>E.id===T.id&&E.type==="dataset")).map(T=>({id:T.id,datasetType:T.type,name:T.name||T.table,label:T.label,domainId:T.domainId,description:T.description,database:T.database,schema:T.schema,type:"dataset",connectionId:T.connectionId,connectionType:T.connectionType,dialect:T.dialect,datamodelId:T.datamodelId,sql:T.sql})),k=[...S,...j];n(k)},[y,r,e==null?void 0:e.semanticDomainId,n]);return w.useEffect(()=>{i&&i(v)},[i,v]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{className:"text-sm font-medium",children:"Semantic Domain"}),l.jsxs(pt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:u,disabled:f||s.mode==="none"||s.mode==="include"&&!!o,children:[l.jsx(ft,{className:"w-full",children:l.jsx(gt,{placeholder:f?"Loading semantic domains...":s.mode==="none"?"No semantic domains available for this token":s.mode==="include"&&o?"Loading domain...":"Select semantic domain...",children:((C=m.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:C.label)||"Select semantic domain"})}),l.jsx(ht,{children:m.map(S=>l.jsx(Ie,{className:"hover:bg-muted",value:S.id,children:l.jsxs("div",{className:"flex flex-col items-start",children:[l.jsx("span",{className:"font-medium",children:S.label}),l.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),h&&l.jsx(HS,{title:"Error loading semantic models",message:h.message})]}),(e==null?void 0:e.semanticDomainId)&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(lt,{placeholder:"Search datasets...",value:a,onChange:S=>c(S.target.value),className:"h-8 text-sm",disabled:g}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):b?l.jsx(HS,{title:"Error loading datasets",message:b.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):y.length===0?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:a?"No datasets match your search":"No datasets available"}):y.map(S=>{const N=r.some(j=>j.id===S.id&&j.type==="dataset");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>x(S),children:[l.jsx(Jt,{id:`dataset-${S.id}`,checked:N,onCheckedChange:()=>x(S),onClick:j=>j.stopPropagation(),disabled:g}),l.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[l.jsx(ge,{className:"cursor-pointer font-medium",children:S.label||S.name}),l.jsx("span",{className:"text-xs text-gray-500",children:S.description})]})]},S.label||S.name)})})]})]})]})}function Sdt(e,t,n){switch(e){case"none":return!1;case"include":return n.includes(t);case"exclude":return!n.includes(t);case"all":default:return!0}}function Ndt({mode:e,currentDomainId:t,scopedDomainIds:n,hasSelectedEntities:r}){return e==="all"?!1:e==="none"?!!t||r:t?!Sdt(e,t,n):r}function jdt(e){const t=new Set;for(const n of e||[])"domainId"in n&&typeof n.domainId=="string"&&t.add(n.domainId);if(t.size===1)return[...t][0]}function Y5({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s,onSaveSelectedEntities:o,saveAsDashboardDefault:i=!1}){var U,O;const{tokenProps:a}=rt(),c=a.semanticDomainAccess||Tc.DEFAULT_SEMANTIC_DOMAIN_ACCESS,[u,d]=w.useState([]),[f,h]=w.useState(void 0),{updateDataSource:m}=lr(),p=ee(I=>I.isVisualEditing),g=ee(I=>I.dashboard.aiContext),{setAiContext:b}=en(),x=w.useRef(null),[y,v]=w.useState(!1),C=c.mode,S=C==="include"||C==="exclude",N=C!=="all",j=!S,k=r==="aiContext"&&S?"semanticDomain":n.mode,T=C==="include"&&(((U=c.domainIds)==null?void 0:U.length)||0)===1?(O=c.domainIds)==null?void 0:O[0]:void 0,E=w.useCallback(I=>{const W=I;m({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:W,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...W!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,m]),_=w.useCallback(I=>{m({...n,...I})},[n,m]),M=w.useCallback(I=>{if(r==="aiContext"){"semanticDomainId"in I&&h(I.semanticDomainId);return}_(I)},[r,_]),P=r==="aiContext"?f:n.semanticDomainId,D=r==="aiContext"?{...n,mode:k,semanticDomainId:f}:n;w.useEffect(()=>{if(!N||r==="aiContext"&&!e)return;if(S&&n.mode!=="semanticDomain"&&r==="dataSource"){E("semanticDomain");return}if(k!=="semanticDomain")return;const I=P,W=c.domainIds??[],X=r==="aiContext"?u:n.selectedEntities,Z=((X==null?void 0:X.length)??0)>0,H=((u==null?void 0:u.length)??0)>0;Ndt({mode:C,currentDomainId:I,scopedDomainIds:W,hasSelectedEntities:Z})&&(r==="dataSource"?_({semanticDomainId:void 0,selectedEntities:[]}):h(void 0),H&&d([]))},[S,N,k,n.mode,P,n.selectedEntities,r,f,u,e,c.domainIds,C,_,E]),w.useEffect(()=>{T&&!P&&M({semanticDomainId:T})},[T,P,M]),w.useEffect(()=>{if(e){d(s||[]);const I=r==="aiContext"?jdt(s):void 0;h(n.semanticDomainId||I)}else x.current=null,v(!1)},[e,n==null?void 0:n.selectedEntities,r,m,s,n]);const A=I=>{const W=u.filter(X=>!hi(X,I));d(W)},L=()=>{d([])},$=w.useCallback(I=>{d(I)},[]),B=w.useCallback(()=>{x.current&&x.current()},[]),V=w.useCallback(I=>{x.current=I,v(!0)},[]);function R(){var I,W;if(r==="aiContext"){if(p&&m(n),i){const X={...g,selectedEntities:u,mode:u.length>0?"fixed":"auto"};b(X)}o==null||o(u),t(!1)}else if(r==="dataSource"){if(n.mode==="semanticDomain"){const X=(I=u==null?void 0:u[0])==null?void 0:I.connectionId,Z=(W=u==null?void 0:u[0])==null?void 0:W.connectionType;m({...n,connectionId:X,connectionType:Z,selectedEntities:u})}else m({...n,selectedEntities:u});t(!1)}}return l.jsx(zr,{open:e,onOpenChange:t,children:l.jsx(Tr,{className:"flex max-w-2xl flex-col",children:l.jsxs("div",{children:[l.jsxs(_r,{className:"flex-shrink-0",children:[l.jsx(Ir,{children:r==="aiContext"?"Data Context":"Select Data Source"}),l.jsx(ss,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),l.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:l.jsxs("div",{className:"space-y-4",children:[j&&l.jsx("div",{className:"space-y-2",children:l.jsx(As,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:E,className:"w-full",children:l.jsxs(ys,{className:"grid w-full grid-cols-2",children:[l.jsx(on,{value:"database",children:"Direct Source"}),l.jsx(on,{value:"semanticDomain",children:"Semantic Domain"})]})})}),k==="semanticDomain"&&l.jsx(Cdt,{dataSource:D,onDataSourceUpdate:M,selectedEntities:u,onSelectionChange:$,domainAccess:c,autoSelectedDomainId:T,onRegisterSelectAll:V}),k==="database"&&j&&l.jsx(wdt,{dataSource:n,onDataSourceUpdate:_,selectedEntities:u,onSelectionChange:$,onRegisterSelectAll:V})]})}),l.jsx(fdt,{selectedEntities:u,onDeselectEntity:A}),l.jsx(Ds,{className:"flex-shrink-0",children:l.jsx("div",{className:"flex w-full justify-between",children:l.jsxs("div",{className:"flex grow justify-end gap-2",children:[l.jsx(re,{variant:"outline",onClick:B,disabled:!y,children:"Select All"}),l.jsx(re,{variant:"outline",onClick:L,disabled:u.length===0,children:"Clear All"}),l.jsxs(re,{variant:"outline",onClick:()=>t(!1),children:[l.jsx(Mt,{className:"mr-2 h-4 w-4"}),"Close"]}),l.jsxs(re,{onClick:R,children:[l.jsx(qr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function WS(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return l.jsx(XA,{className:r});case"view":return l.jsx(Gu,{className:r});case"materialized view":return l.jsx(mpe,{className:r});case"model":return l.jsx(bN,{className:r});case"file":return l.jsx(ka,{className:r});case"dataset":return l.jsx(pl,{className:r});case"upload":return l.jsx(tR,{className:r});case"url":return l.jsx(zU,{className:r});default:return l.jsx(pN,{className:r})}}const ID=e=>e.name||e.name,Edt=e=>{const t=ID(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"font-medium",children:t}),n&&l.jsx("div",{className:"text-sm text-muted-foreground",children:n}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function kdt({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r,className:s}){const[o,i]=w.useState(!1),a=e.length>0;e.length,t.length,e.length<t.length;const c=e.length>=3?e.slice(0,2):e,u=e.length>=3?e.slice(2):[],d=u.length>0;return l.jsx(gr,{children:l.jsx("div",{className:s,children:a&&l.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.map((f,h)=>{const m="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs(wn,{children:[l.jsx(Cn,{asChild:!0,children:l.jsxs(Xe,{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:[WS(f.type,{size:"h-3 w-3"}),l.jsx("span",{className:"max-w-24 truncate text-xs",children:ID(f)}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(f),children:l.jsx(Mt,{className:"h-3 w-3"})})]})}),l.jsx(Tn,{side:"top",className:"max-w-xs",children:Edt(f)})]},m)}),d&&l.jsxs(wn,{open:o,onOpenChange:i,children:[l.jsx(Cn,{asChild:!0,children:l.jsxs(Xe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>i(!0),children:[l.jsx(OU,{className:"h-3 w-3"}),l.jsxs("span",{className:"text-xs",children:[u.length," more"]}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(u),children:l.jsx(Mt,{className:"h-3 w-3"})})]})}),l.jsx(Tn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),l.jsx("div",{className:"space-y-2",children:u.map(f=>{const h="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:WS(f.type,{size:"h-3 w-3"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-sm font-medium",children:ID(f)}),l.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[f.type," ",f.database?`• ${f.database}`:""]})]})]}),l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(f),u.length===1&&i(!1)},children:l.jsx(Mt,{className:"h-3 w-3"})})]},h)})})]})})]})]})})})}const mle=F.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[l.jsx(Ws,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(mo.Input,{ref:n,className:Q("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})]}));mle.displayName=mo.Input.displayName;const c1=e=>e.label||(e==null?void 0:e.name),lB=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function Tdt({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:c,onAddContext:u}){const{tokenProps:d}=rt(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=w.useState(""),[p,g]=w.useState(""),b=s.filter(N=>{if(!h)return!0;const j=c1(N).toLowerCase(),k=lB(N).toLowerCase(),T=h.toLowerCase();return j.includes(T)||k.includes(T)});w.useEffect(()=>{e||(m(""),g(""))},[e]),w.useEffect(()=>{b.length>0&&!p&&g(c1(b[0]))},[b,p]);const x=()=>{if(!p)return;const N=b.find(j=>c1(j)===p);N&&(o.some(k=>"id"in N&&"id"in k?N.id===k.id:N.name===k.name&&N.connectionId===k.connectionId)||t(N),i(N),r())},y=N=>{(N.key==="Tab"||N.key==="Enter")&&(N.preventDefault(),x())};if(!e)return null;const v=N=>o.some(j=>"id"in N&&"id"in j?N.id===j.id:N.name===j.name&&N.connectionId===j.connectionId),C=o.length===s.length,S=o.length>0;return l.jsx(l.Fragment,{children:l.jsxs(Ng,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[l.jsx(mle,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&l.jsxs(re,{onClick:N=>{N.preventDefault(),N.stopPropagation(),u==null||u()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[l.jsx($r,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[l.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(re,{onClick:N=>{N.preventDefault(),N.stopPropagation(),a==null||a()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},disabled:C,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),S&&l.jsxs(re,{onClick:N=>{N.preventDefault(),N.stopPropagation(),c==null||c()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[l.jsx(Mt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),l.jsxs(jg,{className:"min-h-60",children:[l.jsx(Eg,{children:l.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[l.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&l.jsxs(re,{onClick:N=>{N.preventDefault(),N.stopPropagation(),u==null||u()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[l.jsx($r,{className:"h-4 w-4"}),"Add Datasets"]})]})}),l.jsx(kg,{children:b.map((N,j)=>{const k=v(N),T="id"in N?N.id:`${N.connectionId}-${N.name}`,E=c1(N);return l.jsxs(Tg,{value:E,onSelect:()=>{k?n==null||n(N):t(N)},onMouseDown:_=>{_.preventDefault(),_.stopPropagation()},className:Q("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[l.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:WS(N.type)}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-medium",children:E}),l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:lB(N)})]}),k&&l.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:l.jsx(qr,{className:"h-3 w-3 text-background"})})]},T)})})]})]})})}function MD({mode:e="full",compact:t=!1,inlineLayout:n=!1,inlineTriggerFirst:r=!1,syncOnOpen:s=!1,open:o,onOpenChange:i,onEntityMention:a,onEntityRemoved:c,onEntitiesRemoved:u,onSelectionChange:d,className:f,triggerClassName:h,triggerVariant:m="secondary",triggerLabel:p="Add entity",triggerIconOnly:g=!0,assistantType:b}){const[x,y]=w.useState(!1),[v,C]=w.useState(!1),S=o??x,N=o!==void 0,j=w.useRef(!1),T=Ve(z=>z.card.dataSource)??Hy,{selectedEntities:E,availableEntities:_,syncWithGlobalContext:M,setSelectedEntities:P,applyDashboardDefaultEntities:D,isEntitySelected:A}=cj(b),L=e==="full"||e==="display",$=e==="full"||e==="trigger",B=w.useMemo(()=>g&&E.length>0?`Add entity (${E.length})`:p,[E.length,g,p]);w.useEffect(()=>{S&&!j.current&&s&&M(),j.current=S},[S,s,M]);const V=w.useCallback(z=>{N||y(z),i==null||i(z)},[N,i]),R=w.useCallback(z=>{const q=E.filter(Y=>!hi(Y,z));P(q),c==null||c(z),d==null||d(q)},[c,d,E,P]),U=w.useCallback(z=>{if(z.length===0)return;const q=E.filter(Y=>!z.some(G=>hi(Y,G)));P(q),u==null||u(z),d==null||d(q)},[u,d,E,P]),O=w.useCallback(z=>{const q=A(z)?E.filter(Y=>!hi(Y,z)):[...E,z];P(q),d==null||d(q)},[A,d,E,P]),I=w.useCallback(()=>{P(_),d==null||d(_)},[_,d,P]),W=w.useCallback(()=>{P([]),d==null||d([])},[d,P]),X=w.useCallback(z=>{b==="dashboard"?D():P(z),d==null||d(z)},[D,b,d,P]),Z=w.useCallback(z=>{const q=E.some(Y=>hi(Y,z))?E:[...E,z];P(q),a==null||a(z),d==null||d(q),V(!1)},[a,d,E,V,P]),H=L?l.jsx(kdt,{className:Q(n?"contents":"space-y-2"),entities:E,availableEntities:_,onRemoveEntity:R,onRemoveEntities:U}):null,K=$?l.jsxs(l.Fragment,{children:[l.jsxs(Gr,{open:S,onOpenChange:V,children:[l.jsx(Kr,{asChild:!0,children:l.jsxs(re,{variant:m,size:"sm",className:Q(t?"h-7 gap-1.5 px-2 text-xs":"h-7 px-2",h),title:p,children:[l.jsx(cpe,{className:"h-4 w-4 text-muted-foreground"}),!g&&l.jsx("span",{children:B})]})}),l.jsx(Zr,{className:Q("w-80 p-0",t&&"w-72"),align:"start",side:"top",sideOffset:8,onOpenAutoFocus:z=>z.preventDefault(),children:l.jsx(Tdt,{isOpen:!0,onSelect:O,onDeselect:O,onClose:()=>V(!1),availableEntities:_,selectedEntities:E,onTabComplete:Z,onSelectAll:I,onRemoveAll:W,onAddContext:()=>{V(!1),C(!0)}})})]}),l.jsx(Y5,{incomingSelectedEntities:E,open:v,onOpenChange:C,dataSource:T,dialogMode:"aiContext",onSaveSelectedEntities:X,saveAsDashboardDefault:b==="dashboard"})]}):null;return l.jsx("div",{className:Q(n?"flex flex-wrap items-center gap-1":"",!n&&L?"space-y-2":"",f),children:n&&r?l.jsxs(l.Fragment,{children:[K,H]}):l.jsxs(l.Fragment,{children:[H,K]})})}const G5=w.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:c},u)=>{const[d,f]=w.useState(!1),h=w.useRef(null),{queueMessage:m}=Xp(),{addFileAttachment:p,removeFileAttachment:g,clearFileAttachments:b}=xA(),x=bA(c);w.useEffect(()=>{u&&"current"in u&&(u.current=h.current)},[u]);const y=w.useCallback(()=>{const E=h.current;if(E){if(!e||e.length===0){E.style.height="10px";return}E.style.height="auto";const _=Math.min(Math.max(E.scrollHeight,10),200);E.style.height=`${_}px`}},[e]);w.useEffect(()=>{y()},[y]),w.useEffect(()=>{const E=setTimeout(()=>{y()},0);return()=>clearTimeout(E)},[y]);const v=()=>{const E=e.trim();!E&&x.length===0||(a!=="ready"?(m(c,E,x),t(""),b(c)):r({preventDefault:()=>{}}))},C=E=>{E.key==="Enter"&&!E.shiftKey&&(E.preventDefault(),v()),E.key==="@"&&f(!0)},S=w.useCallback(E=>{const _=Fst(E.nativeEvent);_.length>0&&(E.preventDefault(),_.forEach(async M=>{const P=await F5(M);p(c,P)}))},[p,c]),N=w.useCallback(E=>{E.forEach(_=>{p(c,_)})},[p,c]),j=w.useCallback(E=>{E.forEach(_=>{p(c,_)})},[p,c]),k=w.useCallback(E=>{g(c,E)},[g,c]),T=w.useCallback(E=>{const _=`@${E}`;e.includes(_)&&t(e.replace(_,"").replace(/\s{2,}/g," ").trim())},[e,t]);return l.jsxs(udt,{onFilesDropped:N,currentFileCount:x.length,disabled:s,className:"space-y-4",children:[l.jsx(MD,{mode:"display",assistantType:c,onEntityRemoved:E=>{const _="label"in E?E.label:E.name;T(_)},onEntitiesRemoved:E=>{let _=e;E.forEach(M=>{const P="label"in M?M.label:M.name;_=_.replace(`@${P}`,"")}),_!==e&&t(_.replace(/\s{2,}/g," ").trim())}}),x.length>0&&l.jsx(Pst,{files:x,onRemove:k,showRemove:!s,className:"mb-2"}),l.jsxs("div",{className:"rounded-xl border border-border/60 bg-background shadow-sm transition-colors focus-within:border-border focus-within:ring-1 focus-within:ring-ring/20",children:[l.jsx("textarea",{ref:h,value:e,onChange:n,onKeyDown:C,onPaste:S,onFocus:()=>{y(),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 pt-3 pb-1 text-sm text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),l.jsxs("div",{className:"flex items-center justify-between px-2 pb-2",children:[l.jsxs("div",{className:"flex items-center gap-0.5",children:[l.jsx(MD,{mode:"trigger",assistantType:c,syncOnOpen:c==="dashboard",open:d,onOpenChange:f,onEntityMention:E=>{var M;const _="label"in E?E.label:E.name;t(`${e}@${_} `),(M=h.current)==null||M.focus()},triggerVariant:"secondary",triggerIconOnly:!0,triggerClassName:"h-7 px-2",triggerLabel:"Add entity"}),l.jsx(cdt,{onFilesSelected:j,disabled:s,currentFileCount:x.length})]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[s&&l.jsx(re,{className:"h-8 w-8 rounded-full p-0",size:"sm",onClick:o,children:l.jsx(Epe,{className:"size-3.5"})}),!s&&l.jsx(re,{disabled:!e.trim()&&x.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",className:"h-8 w-8 rounded-full p-0",onClick:v,title:a!=="ready"?"Message will be queued":void 0,children:l.jsx(KA,{className:"size-3.5"})})]})]})]})]})});G5.displayName="ChatInputWithContext";function ple({assistantType:e,className:t}){const n=R7(e),{removeFromQueue:r}=Xp();return n.length===0?null:l.jsxs("div",{className:Q("space-y-2",t),children:[l.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[l.jsx(Yu,{className:"h-3 w-3"}),l.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),l.jsx("div",{className:"space-y-2",children:n.map(s=>l.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:l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsx("div",{className:"flex-1 space-y-1",children:l.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),l.jsx(re,{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:l.jsx(Mt,{className:"h-3 w-3"})})]})},s.id))})]})}function gle({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=R7(e),{dequeueMessage:o}=Xp();w.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 _dt(e){return e?typeof e=="string"?e:typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:typeof e.value=="string"?e.value:"":""}function Idt(e){if(!e)return"none";const t=(e==null?void 0:e.id)??(e==null?void 0:e.messageId)??(e==null?void 0:e.createdAt)??(e==null?void 0:e.timestamp)??"unknown";if(!Array.isArray(e.parts)){const r=typeof(e==null?void 0:e.content)=="string"?e.content:typeof(e==null?void 0:e.text)=="string"?e.text:"";return`${t}|${(e==null?void 0:e.role)??"unknown"}|${r.length}|${r.slice(-24)}`}const n=e.parts.map(r=>{const s=typeof(r==null?void 0:r.type)=="string"?r.type:"unknown",o=typeof(r==null?void 0:r.state)=="string"?r.state:"na",i=_dt(r);return`${s}:${o}:${i.length}:${i.slice(-24)}`}).join("|");return`${t}|${(e==null?void 0:e.role)??"unknown"}|${e.parts.length}|${n}`}function ble(e,t={}){const{threshold:n=40,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=w.useRef(null),a=w.useRef(null),[c,u]=w.useState(!0),[d,f]=w.useState(!0),[h,m]=w.useState(!1),[p,g]=w.useState(0),b=w.useRef(!0),x=w.useRef(!0),y=w.useRef(!1),v=w.useRef(!1),C=w.useRef(0),S=w.useRef({count:0,signature:"none"}),N=w.useCallback(()=>{if(i.current)return i.current;const A=a.current;if(!A)return null;const L=A.closest("[data-radix-scroll-area-viewport]");if(L)return i.current=L,L;const $=A.parentElement;return $?(i.current=$,$):null},[]),j=w.useCallback(()=>{const A=N();return A?A.scrollHeight-A.scrollTop-A.clientHeight:0},[N]),k=w.useCallback(()=>j()<=n,[j,n]),T=w.useCallback(A=>{b.current!==A&&(b.current=A,u(A))},[]),E=w.useCallback(A=>{x.current!==A&&(x.current=A,f(A))},[]),_=w.useCallback(()=>{m(A=>A&&!1),g(A=>A===0?A:0)},[]),M=w.useCallback((A={})=>{const L=N();if(!L)return;const{force:$=!1,instant:B=!1}=A;if(!$&&y.current)return;const V=B||r==="auto"||r==="instant"?"auto":r;v.current=!0,V==="smooth"&&"scrollTo"in L?L.scrollTo({top:L.scrollHeight,behavior:"smooth"}):L.scrollTop=L.scrollHeight,C.current=L.scrollTop,y.current=!1,T(!0),E(!0),_(),requestAnimationFrame(()=>{v.current=!1})},[r,_,N,T,E]),P=w.useCallback(()=>{g(0),m(!1)},[]),D=w.useCallback(()=>{const A=N();if(!A)return;const L=C.current,$=A.scrollTop,B=$-L;C.current=$;const V=k();if(v.current){E(V),V&&(y.current=!1,T(!0));return}if(B<-1&&!V){y.current=!0,T(!1),E(!1);return}if(V){y.current=!1,T(!0),E(!0),_();return}E(!1),y.current&&T(!1)},[_,N,k,T,E]);return w.useEffect(()=>{const A=N();if(!e||e.length===0){S.current={count:0,signature:"none"},A&&(C.current=A.scrollTop),_();return}const L=e[e.length-1],$=Idt(L),B=S.current,V=e.length>B.count,R=$!==B.signature;S.current={count:e.length,signature:$};const U=o||s&&(L==null?void 0:L.role)==="assistant"&&R;if(!y.current){T(!0),A&&k()&&E(!0),(V||R||U)&&M({force:!1,instant:U});return}if(V){const O=e.length-B.count;O>0&&(m(!0),g(I=>I+O))}else R&&(m(!0),g(O=>O>0?O:1))},[_,o,s,N,k,e,M,T,E]),w.useEffect(()=>{M({force:!0,instant:!0})},[M]),w.useEffect(()=>{if(typeof ResizeObserver>"u")return;const A=a.current;if(!A)return;const L=new ResizeObserver(()=>{y.current||M({force:!1,instant:!0})});return L.observe(A),()=>{L.disconnect()}},[M]),w.useEffect(()=>()=>{v.current=!1},[]),{scrollRef:i,contentRef:a,isAutoScrollEnabled:c,isAtBottom:d,hasNewMessages:h,newMessageCount:p,scrollToBottom:M,handleScroll:D,resetNewMessageCount:P}}function xle(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=w.useState(r),a=w.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),c=e.length>o,u=o>=e.length,d=w.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=w.useCallback(()=>{i(r)},[r]);return w.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:c,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}const cB={"tool-getTableColumns":{"input-streaming":"Fetching table columns...","input-available":"Reading column definitions..."},"tool-getChartDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartDataFromCardConfig":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getForecastDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartSQLSyntax":{"input-streaming":"Generating SQL syntax...","input-available":"SQL syntax generated"},"tool-validateCardConfigFormat":{"input-streaming":"Validating card config format...","input-available":"Card config format validated"},"tool-generateQueryConfig":{"input-streaming":"Generating query config...","input-available":"Sending query config..."},"tool-generateDynamicVisual":{"input-streaming":"Planning dynamic visual...","input-available":"Generating dynamic visual..."},"tool-generateDynamicVisualFromData":{"input-streaming":"Planning dynamic visual...","input-available":"Building visual..."},"tool-askForMoreInfo":{"input-streaming":"Asking for more information...","input-available":"More information requested"},"tool-createChartFromSql":{"input-streaming":"Creating chart...","input-available":"Chart created"},"tool-getUserSql":{"input-streaming":"Getting SQL...","input-available":"SQL retrieved"},"tool-inspectTableData":{"input-streaming":"Inspecting table data...","input-available":"Analyzing data..."},"tool-getDomainRelationships":{"input-streaming":"Getting domain relationships...","input-available":"Analyzing data..."}};function Mdt(e,t){var r;if((r=cB[e])!=null&&r[t])return cB[e][t];const n=e.replace("tool-","").replace(/([A-Z])/g," $1").toLowerCase().trim();return t==="input-streaming"?`Processing ${n}...`:`Preparing ${n} response...`}function yle(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:"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:Mdt(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const Ddt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Adt({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=w.useState(!1),[a,c]=w.useState(eA),[u,d]=w.useState(!1),[f,h]=w.useState("auto"),[m,p]=w.useState(!1),[g,b]=w.useState(!1),x=n??g,{isLocalDev:y,isConsoleMode:v}=ag(),C=w.useRef(null);ee(ae=>ae.dashboard.aiScopeTables),ee(ae=>ae.isDashboardEditing);const S=ee(ae=>ae.selectedSheetId),{setDataSource:N}=lr(),{addFrame:j,setSelectedFrameId:k,setIsDashboardEditing:T}=en(),{setReasoningEffort:E,setShowReasoning:_,clearAssistantMessageContexts:M}=iN(),{clearQueue:P}=Xp(),{clearFileAttachments:D,getFileAttachments:A}=xA(),L=bA("dashboard"),$=Ve(ae=>ae.card.dataSource),{assistantProfile:B}=ule(),V=ee(ae=>ae.handleOpenAssistantProfile),{selectedEntities:R,applyDashboardDefaultEntities:U}=cj("dashboard"),{sendMessage:O,isLoading:I,messages:W,setMessages:X,status:Z,stop:H,errorMessage:K,clearError:z}=ldt({dynamicVisualMode:f}),q=w.useCallback(ae=>{r==null||r(ae),n===void 0&&b(ae)},[n,r]),Y=w.useCallback(()=>{q(!x)},[x,q]);w.useEffect(()=>{if(!x)return;function ae(Pe){Pe.key==="Escape"&&q(!1)}return window.addEventListener("keydown",ae),()=>{window.removeEventListener("keydown",ae)}},[x,q]);const[G,J]=w.useState(""),ne=ae=>{J(ae.target.value)};function be({sql:ae,cardTitle:Pe,connectionId:Ee,cardType:_e,python:We,cardConfig:Te,dataSource:Ue,customVisualPreferences:et,visualizationMode:bt,dynamicCardPreferences:dt}){if(!S)return;const St=bt==="dynamic",Ot=Sa(Te),xt=Ee||(Ue==null?void 0:Ue.connectionId)||"",an=Ue?{...Ue,connectionId:xt||Ue.connectionId,connectionType:Ue.connectionType||"",mode:Ue.mode||"database",selectedEntities:Ue.selectedEntities||[]}:xt?{connectionId:xt,connectionType:"",mode:"database",selectedEntities:[]}:Hy,Tt=!Ot||!St||(dt==null?void 0:dt.provenance)!=="card-config",ve=Tt?ae:"",nt=Tt?We:"",ct={id:wr(),title:Pe||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:_e==="horizontalBar"?"y":"x"},...St&&{displayOptions:{showChrome:!1,allowScroll:!1}}},type:_e,sql:ve,python:nt,dataSource:an,config:Te,connectionId:xt,visualizationMode:bt,dynamicCardPreferences:dt,customCardPreferences:et?{url:et.url,componentName:et.componentName,pluginChartType:et.pluginChartType,settings:et.settings,type:"component"}:void 0},pn={id:wr(),cards:[ct],activeCardId:ct.id};T(!0),j(S,pn,"end"),k(pn.id)}const te=ae=>{ae.preventDefault();const Pe=G.trim();if(!Pe&&L.length===0)return;const Ee=[];Pe&&Ee.push({type:"text",text:Pe}),L.forEach(_e=>{_e.data&&Ee.push({type:"file",mediaType:_e.type,filename:_e.name,url:`data:${_e.type};base64,${_e.data}`})}),O({role:"user",parts:Ee}),J(""),D("dashboard"),de({force:!0})};w.useEffect(()=>{var ae;e&&((ae=C.current)==null||ae.focus())},[e]),gle({assistantType:"dashboard",status:Z,isLoading:I,sendMessage:O});const{hasActiveTools:ce,activeToolText:se}=yle(W),{visibleMessages:ue,hasMoreMessages:Re,totalMessageCount:je,loadMoreMessages:ke,resetMessageWindow:me}=xle(W,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Me,contentRef:Se,isAtBottom:ie,hasNewMessages:pe,newMessageCount:Ne,scrollToBottom:de,handleScroll:fe,resetNewMessageCount:Oe}=ble(ue,{threshold:40,behavior:"smooth",isStreaming:I});function ye(ae){const Pe={role:"user",parts:[{type:"text",text:ae.title+" "+ae.subtitle}]};O(Pe)}function Ce(ae){O({role:"user",parts:[{type:"text",text:ae}]})}function $e(ae){O({role:"user",parts:[{type:"text",text:ae}]}),de({force:!0})}const ze=w.useCallback(async()=>{const ae=JSON.stringify(W??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ae),qe.success("Conversation copied")}catch(Pe){console.error("Failed to copy conversation",Pe),qe.error("Unable to copy conversation")}},[W]),Ge=(G==null?void 0:G.length)===0&&(W==null?void 0:W.filter(ae=>ae.role==="user").length)===0;function Ke(){return l.jsx("div",{"data-role":"header",children:l.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Ze(){return l.jsxs(pd,{children:[l.jsx(gd,{asChild:!0,children:l.jsx(Ou,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(_h,{className:"size-3.5"})})}),l.jsxs(Hc,{align:"end",children:[l.jsx(Df,{children:"Options"}),l.jsx(Zu,{}),l.jsx(fu,{checked:o,onCheckedChange:i,children:"Token Usage"}),l.jsx(fu,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(fu,{checked:u,onCheckedChange:d,children:"System Message"}),(y||v)&&l.jsxs(l.Fragment,{children:[l.jsx(Zu,{}),l.jsx(Df,{children:"Dynamic Visuals"}),l.jsx(fu,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),l.jsx(fu,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),l.jsx(fu,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const st=l.jsxs("div",{"data-role":"dashboard-assistant",className:Q("flex h-full grow flex-col justify-between break-words px-6 py-4",x&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[l.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ke(),V&&l.jsx(re,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:V,children:(B==null?void 0:B.name)||"Default Profile"}),l.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[v&&Ze(),a&&l.jsx(re,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:ze,children:"Copy Conversation"}),l.jsx(Ou,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:x?"Exit Fullscreen":"Expand",onClick:Y,children:x?l.jsx(WA,{className:"size-4"}):l.jsx(xN,{className:"size-4"})}),l.jsx(Ou,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{const ae=W.filter(Pe=>Pe.role==="assistant").map(Pe=>Pe.id).filter(Pe=>!!Pe);X([]),P("dashboard"),z(),M(ae),me()},children:l.jsx(vN,{className:"size-4"})}),l.jsx(Ou,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:l.jsx(Mt,{className:"size-4"})})]})]}),l.jsxs(za,{"data-role":"dashboard-assistant-scroll-area",ref:Me,className:"mt-4 flex min-w-0 flex-1 basis-0 flex-col justify-end pr-2",onScroll:fe,children:[l.jsxs("div",{ref:Se,className:"min-w-0 space-y-3 pb-4",children:[Re&&l.jsx("div",{className:"flex justify-center py-2",children:l.jsxs(re,{variant:"outline",size:"sm",onClick:ke,className:"text-xs",children:["Load ",Math.min(5,je-ue.length)," ","more messages (",je-ue.length," ","hidden)"]})}),l.jsx(qie,{showTools:a,showSystemMessage:u,messages:ue,onAddToDashboard:be,onQuickReply:$e,disableQuickReplies:I}),l.jsx(Wie,{status:Z,errorMessage:K,activeToolText:I&&ce?se:void 0})]}),l.jsx(Da,{orientation:"horizontal"})]}),e&&!ie&&l.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:l.jsxs(re,{onClick:()=>{de({force:!0}),Oe()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[l.jsx(pr,{className:"h-4 w-4"}),pe&&Ne>0&&l.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:Ne>9?"9+":Ne})]})}),l.jsxs("div",{className:"space-y-3",children:[!B&&Ge&&l.jsx(Yie,{onClick:ye,placeholders:Ddt}),l.jsx("div",{children:Ge&&B&&l.jsx(dle,{seedQuestions:B.seedQuestions||[],handleSeedQuestionClick:Ce})}),l.jsx(ple,{assistantType:"dashboard",className:"mb-3"}),l.jsx(G5,{ref:C,setInput:J,stop:H,input:G,handleInputChange:ne,handleSubmit:ae=>{te(ae),de({force:!0})},isLoading:I,status:Z,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(Y5,{incomingSelectedEntities:R,open:m,onOpenChange:p,dataSource:$||Hy,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:ae=>U()})]});return x&&s?mr.createPortal(l.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:l.jsx("div",{className:"flex h-full w-full",children:st})}),s):st}function Rdt(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=en(),o=ee(d=>d.dashboard.sheets),a=ee(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),c=ee(d=>d.isDashboardEditing),u=ee(d=>d.isVisualEditing);w.useEffect(()=>{if(!c||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),qe.success("Card copied to clipboard"),m.preventDefault()):p&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=yre(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),qe.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,c,u,t])}function Fdt(e,t){switch(e.interactionMode){case"drillToDetail":Pdt(e,t);break;case"drillThrough":Odt(e,t);break;case"drillToURL":Ldt(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 Pdt(e,t){var c;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=((c=t.getCurrentFilters)==null?void 0:c.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 Odt(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))||"",c=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:c,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:c,filters:i,contextMode:r})}function Ldt(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 $dt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return l.jsx(zr,{open:e,onOpenChange:t,children:l.jsxs(Tr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[l.jsxs(_r,{children:[l.jsx(Ir,{children:i||"Insight Detail"}),l.jsx(ss,{children:a||"View detailed insight data with applied filters"})]}),l.jsx(Yre,{filters:r,filterDefinitions:s,contextMode:o}),l.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?l.jsx(ese,{insightId:n,filters:r,contextMode:o}):l.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function zdt(){const e=Vt(C=>C.interactionStates),t=Vt(C=>C.setInteractionState),n=Vt(C=>C.clearLastInteractionEvent),r=Vt(C=>C.replaceCardWithInsight),s=Vt(C=>C.setPendingDrillThrough),o=Vt(C=>C.pendingDrillThrough),i=Vt(C=>C.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=en(),{selectDashboard:u}=Jp(),d=ee(C=>C.dashboard),f=ee(C=>C.filterValues),{data:h,isLoading:m}=iq((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=w.useState({open:!1,insightId:""}),b=tse(p.insightId,{enabled:p.open&&!!p.insightId}),x=w.useRef(new Set),y=w.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:C,filters:S,contextMode:N})=>{g({open:!0,insightId:C,filters:S,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:N})},replaceCardContent:({cardId:C,insightId:S,filters:N,contextMode:j})=>{r(C,S,N,j)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:C,contextMode:S,sourceDashboardId:N,sourceDashboardTitle:j,targetDashboardId:k})=>{const E={sourceCardId:fa,interactionMode:"clickFilter",filterGroups:[{filters:C}]},_={...Oi(),appliedClickFilters:[E],contextMode:S,sourceDashboardId:N,sourceDashboardTitle:j,targetDashboardId:k};t(fa,_)}}),[a,r,f,c,d,s,t]);w.useEffect(()=>{Object.entries(e).forEach(([C,S])=>{if(S!=null&&S.lastInteractionEvent){const N=S.lastInteractionEvent,j=`${C}-${N.interactionMode}-${N.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{Fdt(N,y)}catch(k){console.error("Error executing interaction event:",k)}finally{n(C),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),w.useEffect(()=>{if(!(!o||!h||m))try{u(h),c(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(C){console.error("[DrillThrough] Error during automatic navigation:",C),i()}},[o,h,m,u,c,i]);const v=()=>{g({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx($dt,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&m&&l.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[l.jsx(Mn,{className:"h-8 w-8 animate-spin text-primary"}),l.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function Vdt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=Bdt(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function Bdt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function Udt(e){return e?`Back to ${e}`:"Back"}function Hdt(){var x,y,v,C,S;const e=Vt(N=>N.interactionStates[fa]),t=ee(N=>N.actions.goBackFromDrill),n=ee(N=>N.actions.clearDrillContext),{selectDashboard:r}=Jp(),[s,o]=w.useState({x:16,y:16}),[i,a]=w.useState(!1),c=w.useRef({x:0,y:0});w.useEffect(()=>{if(!i)return;const N=k=>{o({x:k.clientX-c.current.x,y:k.clientY-c.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",N),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",N),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((C=(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:C.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((S=e.appliedClickFilters)!=null&&S.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(N){console.error("[DrillBack] Error during back navigation:",N)}},p=()=>{n()},g=N=>{N.target.closest("button")||(a(!0),c.current={x:N.clientX-s.x,y:N.clientY-s.y})};Vdt(f);const b=Udt(d);return l.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:l.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:[l.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((N,j)=>{const k=N.field.label||N.field.name,T=String(N.value);return l.jsxs(Xe,{variant:"secondary",className:"pointer-events-none text-xs",children:[k," = ",T]},j)})})]}),l.jsx(re,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(Mt,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(re,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(TU,{className:"mr-2 h-4 w-4"}),b]})})]})})}function Wdt(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function vle(){var je,ke;const{showAssistant:e,tokenProps:t}=rt(),n=Wdt((je=t.config)==null?void 0:je.showDashboardAssistant,e),{preferences:r,isConsoleMode:s}=ag(),o=((ke=r==null?void 0:r.cardDisplay)==null?void 0:ke.mode)==="print",i=w.useRef(null),a=w.useRef(null),[c,u]=w.useState(!1),{handleDragStart:d,isDraggingRef:f,getStyle:h,getPositionClasses:m}=EZe({initialPosition:"bottom-right"}),p=Lf(me=>me.setFullscreen),g=Lf(me=>me.setPanelOpen),b=Lf(me=>me.setContainer),x=YQ("dashboard"),y=GQ(),v=KQ("dashboard"),C=x.isOpen,S=y==="dashboard",N=ee(me=>me.isVisualEditing),j=ee(me=>me.themeStyle),k=ee(me=>{var Me;return(Me=me.dashboard)==null?void 0:Me.sheets}),T=ee(me=>me.showFilters),E=ee(me=>me.isDashboardEditing),_=ee(me=>me.selectedSheetId),M=ee(me=>{var Me,Se;return((Se=(Me=me.dashboard)==null?void 0:Me.summary)==null?void 0:Se.position)||"top"}),P=ee(me=>{var Me;return(Me=me.dashboard)==null?void 0:Me.id}),D=ee(me=>me.isDashboardPanelOpen),A=ee(me=>me.actions.setIsDashboardPanelOpen),L=j==null?void 0:j.controlInputRadius,{getDefaultSheetId:$,setDefaultSheetId:B,clearDefaultSheetId:V}=SU(P),[R,U]=w.useState(null);RN(Xr.DASHBOARD);const{setSelectedSheetId:O,setSheetTitle:I,addSheet:W,setSheets:X}=en();Rdt(a);const{setActiveAssistantType:Z}=iN();w.useEffect(()=>{if(P){const me=$();U(me)}},[P,$]),w.useEffect(()=>{C?Z("dashboard"):y==="dashboard"&&p(null)},[C,Z,y,p]),w.useEffect(()=>{var me;C||(me=i.current)==null||me.resize(0)},[C]);function H(me){var Me,Se;me?((Me=i.current)==null||Me.resize(40),g("dashboard",!0),p("dashboard"),Z("dashboard")):(g("dashboard",!1),p(null),(Se=i.current)==null||Se.resize(0),Z(null))}function K(){const me={id:wr(),title:"New Sheet"};W(me),O(me.id)}function z(me,Me){if(!P)return;R===me?(V(),U(null),qe.success("Default sheet cleared")):(B(me),U(me),qe.success(`"${Me}" set as default sheet`))}function q(me){var Me;me<1?(g("dashboard",!1),p(null),Z(null),(Me=i.current)==null||Me.resize(0)):(C||g("dashboard",!0),Z("dashboard"))}function Y(){return(j==null?void 0:j.canvasTheme)==="muted"||!(j!=null&&j.canvasTheme)?"hsl(var(--semaphor-muted))":(j==null?void 0:j.canvasTheme)==="clear"?"":j==null?void 0:j.canvasTheme}const G=(me,Me)=>{me.dataTransfer.setData("tabIndex",Me.toString())},J=me=>{me.preventDefault()},ne=(me,Me)=>{const Se=me.dataTransfer.getData("tabIndex");if(Se===Me.toString())return;const ie=Array.from(k||[]),[pe]=ie.splice(parseInt(Se),1);ie.splice(Me,0,pe),X(ie)},be=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,te=n===!0&&!o&&!C&&!N&&!T;function ce(){if(k&&k.length>1||E)return l.jsxs(ys,{role:"tab-list",className:"flex h-12 w-0 min-w-full items-center justify-start gap-2 overflow-x-auto rounded-none bg-transparent px-3",children:[s&&be&&!D&&l.jsx(re,{style:{borderRadius:L},variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{A(!D)},className:"h-9 shrink-0 px-3",children:l.jsx(UU,{className:"h-4 w-4"})}),k==null?void 0:k.map((me,Me)=>{const Se=_===me.id,ie=R===me.id;return l.jsxs(on,{draggable:!0,onDragStart:pe=>G(pe,Me),onDragOver:J,onDrop:pe=>ne(pe,Me),style:{borderRadius:L},onClick:()=>O(me.id),className:"flex h-9 shrink-0 items-center gap-1 bg-transparent px-3 py-1 text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground data-[state=active]:bg-muted data-[state=active]:font-medium data-[state=active]:text-foreground",value:me.id,children:[l.jsx(pS,{enabled:E&&Se,text:me.title,onSave:pe=>I(me.id,pe),children:me.title},me.id),!E&&Se&&l.jsx("div",{title:ie?"Clear default sheet":"Set as default sheet",children:l.jsx(ZA,{className:Q("ml-1 size-3 cursor-pointer transition-all",ie?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:pe=>{pe.stopPropagation(),z(me.id,me.title||"Sheet")}})}),E&&Se&&k.length>1&&l.jsx(Mt,{className:"ml-1 size-3",onClick:()=>u(!0)})]},me.id)}),E&&l.jsx(re,{style:{borderRadius:L},variant:"outline","aria-label":"Add sheet",className:"h-9 shrink-0 border-transparent bg-transparent px-3 text-muted-foreground hover:bg-muted/50 hover:text-foreground",onClick:K,children:l.jsx($r,{className:"size-4"})})]})}function se(){return l.jsx("div",{ref:a,style:{},className:"grow",children:k==null?void 0:k.map(me=>l.jsx(sr,{style:{backgroundColor:Y()},className:Q("mt-0",{}),value:me.id,children:l.jsx(ZKe,{sheet:me})},me.id))})}function ue(){var me;return l.jsxs(As,{"data-role":"dashboard-tabs-container",className:Q("relative flex h-full flex-col",j==null?void 0:j.dashboardTabsContainer),onValueChange:Me=>{O(Me)},value:_||((me=k==null?void 0:k[0])==null?void 0:me.id),children:[ce(),M==="top"&&l.jsx(VM,{}),l.jsx(za,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:se()}),M==="bottom"&&l.jsx(VM,{}),l.jsx(kZe,{open:c,setOpen:u})]})}const Re=w.useCallback(me=>{b("dashboard",me)},[b]);return k?l.jsxs(l.Fragment,{children:[l.jsx(zdt,{}),l.jsx(Hdt,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(Toe,{className:Q("flex-1 basis-0 overflow-y-auto transition-opacity",S&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx(oD,{children:ue()}),n===!0&&l.jsxs(l.Fragment,{children:[l.jsx(jZe,{open:C,onTabClick:H,withHandle:!0,disabled:!C}),l.jsx(oD,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:q,defaultSize:C?40:0,ref:i,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(Adt,{open:C,setOpen:H,isFullscreen:S,onFullscreenChange:me=>p(me?"dashboard":null),fullscreenContainer:v})})})]})]}),l.jsx("div",{ref:Re,className:Q("absolute inset-0",!S&&"pointer-events-none")}),te&&l.jsx("div",{className:Q("absolute z-50 transition-all duration-300 ease-in-out",m().horizontal,m().vertical),style:h(),children:l.jsx(re,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{f.current||H(!0)},onMouseDown:d,onTouchStart:d,title:"Open Assistant (drag to move)",children:l.jsx(wpe,{className:"h-5 w-5"})})})]})]}):null}const wle=w.forwardRef(({children:e,className:t,...n},r)=>l.jsx("div",{className:Q("semaphor-scope",t),ref:r,...n,children:e}));function K5({children:e}){return l.jsx(wle,{style:{height:"100%",width:"100%"},children:l.jsx(gme,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(gr,{delayDuration:0,children:e})})})}function Cle({children:e,preferences:t}){const{currentUser:n}=Lo(),r=w.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 l.jsx($W.Provider,{value:r,children:l.jsx(GO,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function qdt(e=2e3,t=500){const n=Wme(),[r,s]=w.useState(!1),[o,i]=w.useState(!1),a=w.useRef(null);return w.useEffect(()=>{const c=setTimeout(()=>s(!0),e);return()=>clearTimeout(c)},[e]),w.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function Z5({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=qdt(e,t);return w.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),l.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function Sle(e){if(typeof window>"u")return null;const{preferences:t}=e;return l.jsx(Ra,{FallbackComponent:iE,children:l.jsxs(MA,{dashboardProps:e,children:[l.jsx(Z5,{componentType:"dashboard",componentId:e.id}),l.jsx(K5,{children:l.jsx(Cle,{preferences:t,children:l.jsx("main",{className:"flex h-full flex-col",children:l.jsx(JF,{...e,type:"dashboard",children:l.jsx(vle,{})})})})})]})})}function Ydt(e){return!!e.expression}function Gdt(e){if(e)return e.startsWith("card-source-")?e.replace("card-source-",""):e}function Kdt(e){const t=Gdt(e);return t?t.startsWith("calc_")||t.startsWith("calc_dim_"):!1}function Nle(e){return e.fieldScope==="domain"&&e.entityName===uo||e.entityName===Io||e.qualifiedEntityName===Io}function Zdt(e){return Nle(e)}function Xdt(e){return e.entityName===uo||(e.fieldScope==="dashboard"||e.fieldScope==="card")&&Kdt(e.id)&&!e.entityName}function fd(e){return Ydt(e)?Zdt(e)?"domain_calculated":Xdt(e)?"user_calculated":"inline_expression":"none"}function Qg(e){return fd(e)!=="none"}function va(e){if(!Qg(e))return!1;const t=fd(e);return t==="domain_calculated"||t==="user_calculated"?!0:e.fieldScope==="domain"||e.fieldScope==="dashboard"||e.fieldScope==="card"}function jle(e){return va(e)&&e.fieldScope!=="card"}function Ele(e,t,n){return Qg(e)?t==="editor"?!0:t==="filter"?va(e)&&e.fieldScope!=="card":va(e)&&(n==null?void 0:n.isValuePickSafe)!==!1:!1}function uB(e,t){return e.map(n=>({...n,fieldScope:t}))}function kle(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=o5(),i=Ve(S=>S.frame.calculatedFields),a=Ve(S=>S.card.calculatedFields),c=Ve(S=>S.card.config),u=ee(S=>S.dashboard),d=ee(S=>S.selectedSheetId),f=ee(S=>S.selectedFrameId),h=ee(S=>S.isVisualEditing),m=w.useMemo(()=>e.filter(S=>fd(S)==="domain_calculated"),[e]),p=w.useMemo(()=>e.filter(S=>fd(S)!=="domain_calculated"),[e]),g=w.useMemo(()=>{var N;const S=(N=u==null?void 0:u.sheets)==null?void 0:N.find(j=>j.id===d);return Xhe(S,f)},[u==null?void 0:u.sheets,f,d]),b=w.useMemo(()=>{const S=h?i||[]:g;return S.length?uB(S,"dashboard"):[]},[i,h,g]),x=w.useMemo(()=>Zhe(b),[b]),y=w.useMemo(()=>{const S=(a||[]).filter(E=>va(E)&&E.fieldScope!=="domain"),N=((c==null?void 0:c.metricColumns)||[]).filter(E=>va(E)&&E.fieldScope!=="domain"),j=((c==null?void 0:c.groupByColumns)||[]).filter(E=>va(E)&&E.fieldScope!=="domain"),T=G7([...S,...N,...j]).filter(E=>!x.has(cf(E)));return uB(T,"card").map(E=>({...E,id:`card-source-${E.id}`}))},[a,c==null?void 0:c.groupByColumns,c==null?void 0:c.metricColumns,x]),v=w.useMemo(()=>[...m,...b,...y,...p],[y,p,b,m]),C=w.useMemo(()=>t.filter(S=>S.entityId!==v7),[t]);return{columns:e,columnGroups:C,rawColumnGroups:t,columnFields:p,domainCalculatedFields:m,dashboardCalculatedFields:b,cardCalculatedFields:y,scopedFields:v,isLoading:n,hasError:r,error:s,refetch:o}}function vm(e){const t=new Map;return e.forEach(n=>{const r=Qg(n)?(()=>{const s="expression"in n&&n.expression||"",o=n.qualifiedEntityName||n.entityName||"";return s?["calculated",n.fieldScope||"physical",n.role||"field",o,n.qualifiedFieldName||n.name,s].join("::"):["calculated",n.fieldScope||"physical",n.role||"field",o,nC(n.id)||n.qualifiedFieldName||n.name].join("::")})():["physical",n.fieldScope||"physical",n.role||"field",n.qualifiedEntityName||"",n.qualifiedFieldName||n.name,n.name].join("::");t.has(r)||t.set(r,n)}),Array.from(t.values())}function X5(e){return!d0(e)}function XT(e,t){return vm(e.filter(n=>Ele(n,t,{isValuePickSafe:X5(n)})))}function Qdt(e){return!Qg(e)||Ele(e,"inline-filter",{isValuePickSafe:X5(e)})}function Jdt(e){return!Qg(e)||jle(e)}function Tle(){const e=kle(),t=w.useMemo(()=>vm(e.scopedFields),[e.scopedFields]),n=w.useMemo(()=>vm([...e.columns,...e.dashboardCalculatedFields]),[e.columns,e.dashboardCalculatedFields]),r=w.useMemo(()=>vm(n.filter(Jdt)),[n]),s=w.useMemo(()=>XT(t,"editor"),[t]),o=w.useMemo(()=>XT(n.filter(jle),"filter"),[n]),i=w.useMemo(()=>vm(t.filter(X5)),[t]),a=w.useMemo(()=>vm(i.filter(Qdt)),[i]),c=w.useMemo(()=>XT(a,"inline-filter"),[a]);return{...e,filterableFields:t,sharedFilterableFields:n,dashboardFilterableFields:r,inlineFilterableFields:a,scopedCalculatedFields:s,sharedCalculatedFields:o,inlineCalculatedFields:c,valuePickFilterableFields:i}}function Q5(e){const{tokenProps:t,authToken:n}=rt(),r=t==null?void 0:t.apiServiceUrl;return Qt({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return or(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 _le(e,t,n){if(t==="source")return{isValid:!0};const r=Sn(e.dataType);if(n==="detailTable"&&t!=="detailColumns"&&t!=="sortBy")return{isValid:!1,reason:"Detail tables only accept columns"};if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function Ile(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=s.some(a=>a.comparisonType&&a.comparisonType!=="none");!o&&!i||n(r,{groupByColumns:[],metricColumns:s.map(a=>({...a,comparisonType:"none",targetValue:void 0}))})}function eft(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const tft=new Set(["COUNT","DISTINCT"]),nft=new Set(["running_total","moving_average","previous_period_delta"]);function rft(e){return Sn(e.dataType||"")==="number"?!0:e.aggregate?tft.has(e.aggregate.toUpperCase()):!1}function sft(e,t){var r,s;return!!((s=(r=e.parameters)==null?void 0:r.windowTransform)==null?void 0:s.function)}function J5(e,t){var n,r;return e==="aggregateTable"&&((((n=t.rowAggregates)==null?void 0:n.length)??0)>0||(((r=t.columnAggregates)==null?void 0:r.length)??0)>0)}function Mle({cardType:e,cardConfig:t,metric:n,transformMode:r}){var i,a,c;if(e==="detailTable"||e==="kpi")return{supported:!1,reason:"Metric transforms are not supported for this card type."};if((((i=t.groupByColumns)==null?void 0:i.length)??0)===0)return{supported:!1,reason:"Metric transforms require at least one grouped dimension."};if(!rft(n))return{supported:!1,reason:"Metric transforms are only available for numeric metrics."};const s=(((a=t.pivotByColumns)==null?void 0:a.length)??0)>0,o=e==="pivotTable"||J5(e,t);return s&&!o?{supported:!1,reason:"Metric transforms with pivot dimensions are only supported for pivotTable and subtotal-enabled aggregateTable in V1."}:nft.has(r)&&(((c=t.groupByColumns)==null?void 0:c.length)??0)===0?{supported:!1,reason:"This transform requires grouped dimensions for ordering."}:{supported:!0}}function oft(e){return e.find(t=>Sn(t.dataType||"")==="date")}function ift(e){return e}function Px({cardType:e,cardConfig:t,orderByFieldId:n}){const r=(t.groupByColumns||[]).filter(o=>o.id&&o.id!==n).map(o=>o.id),s=[];if(e==="pivotTable"||J5(e,t))for(const o of t.pivotByColumns||[])o.id&&s.push(o.id);return Array.from(new Set([...r,...s]))}function aft({transformMode:e,cardType:t,cardConfig:n,fallbackOrderByFieldId:r}){var i;const s=r||((i=oft(n.groupByColumns||[]))==null?void 0:i.id),o=Px({cardType:t,cardConfig:n,orderByFieldId:s});return e==="moving_average"?{function:"moving_average",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,movingAverage:{windowSize:7,minPeriods:1}}:e==="previous_period_delta"?{function:"previous_period_delta",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,previousPeriodDelta:{mode:"absolute"}}:e==="percent_of_total"?{function:"percent_of_total",percentOfTotal:{scope:"grand_total",output:"percent"},partitionByFieldIds:[]}:{function:"running_total",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,frame:"unbounded_preceding"}}const lft=new Set(["table","aggregateTable","pivotTable","detailTable"]);function cft(e){return e.alias||e.label||e.name}function Dle(e,t,n){var a,c,u;if(!e)return null;const r=ji(t.format);if(!r)return null;const s=n||{};let o=s,i=!1;if(lft.has(e.type)){const d=H7(r),f=cft(t);if(d&&!((c=(a=s.tablePrefs)==null?void 0:a.columnSettingsMap)==null?void 0:c[f])){const m=Bs();o={...o,tablePrefs:{...o.tablePrefs||{},columnSettingsMap:{...((u=o.tablePrefs)==null?void 0:u.columnSettingsMap)||{},[f]:{...m,type:"number",textAlign:"right",numberFormat:{...m.numberFormat,...d}}}}},i=!0}if(!s.formatNumber){const h=Bhe(r);h&&(o={...o,formatNumber:{decimalPlaces:h.decimalPlaces,minimumFractionDigits:h.minimumFractionDigits,maximumFractionDigits:h.maximumFractionDigits,currency:h.currency,locale:h.locale,prefix:h.prefix,suffix:h.suffix,useGrouping:h.useGrouping,percentValueMode:h.percentValueMode,enabled:!0}},i=!0)}}return i?o:null}const Ale=e=>{var X;const t=(X=e==null?void 0:e.dataSource)==null?void 0:X.semanticDomainId,{data:n}=Q5(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:c,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f,setCardPreferences:h}=lr(),m=Ve(Z=>Z.card.type),p=e==null?void 0:e.id,g=(Z,H)=>{if(Z.id)return Z.id;const K=Z.qualifiedEntityName||Z.entityName||H;return`${H}-${K}-${Z.name}`},b=w.useCallback(Z=>{if(!(e!=null&&e.config))return[];switch(Z){case"groupBy":return(e.config.groupByColumns||[]).map(H=>({...H,id:g(H,"groupBy"),label:H.label!==void 0?H.label:H.name}));case"metrics":return(e.config.metricColumns||[]).map(H=>({...H,id:g(H,"metrics"),label:H.label!==void 0?H.label:H.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map(H=>({id:g(H,"pivotBy"),name:H.name,dataType:H.dataType,label:H.label!==void 0?H.label:H.name,qualifiedEntityName:H.qualifiedEntityName,entityId:H.entityId,entityName:H.entityName,entityType:H.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(H=>({id:g(H,"sortBy"),name:H.name,dataType:H.dataType,label:H.label!==void 0?H.label:H.name,qualifiedEntityName:H.qualifiedEntityName,entityId:H.entityId,entityName:H.entityName,entityType:H.entityType,direction:H.direction}));case"detailColumns":return eft(e.config.detailColumns,H=>g(H,"detailColumns"));case"source":return[];default:return[]}},[e]),x=w.useCallback((Z,H)=>{if(p)switch(Z){case"groupBy":{r(p,{groupByColumns:H});break}case"metrics":{r(p,{metricColumns:H});break}case"pivotBy":{r(p,{pivotByColumns:H});break}case"sortBy":{r(p,{sortByColumns:H});break}case"detailColumns":{r(p,{detailColumns:H});break}}},[p,r]),y=w.useCallback((Z,H,K)=>{if(!p)return;const z=b(Z),q=z[H];if(q)switch(Z){case"groupBy":s(p,q.id,{label:K});break;case"metrics":o(p,q.id,{label:K});break;case"pivotBy":i(p,q.id,{label:K});break;case"sortBy":a(p,q.id,{label:K});break;case"detailColumns":{const Y=z.map((G,J)=>J===H?{...G,label:K}:G);r(p,{detailColumns:Y});break}}},[p,b,s,o,i,a,r]),v=w.useCallback((Z,H)=>{if(!p)return;const z=b("metrics")[Z];z&&o(p,z.id,{aggregate:H,label:yZ(z.name,H)})},[p,b,o]),C=w.useCallback((Z,H,K,z="groupBy")=>{if(!p)return;const q=b(z),Y=q[Z];if(!Y)return;const G={dateFormat:H,customFormat:H==="custom"&&K?K:void 0};if(z==="detailColumns"){const J=q.map((ne,be)=>be===Z?{...ne,...G}:ne);r(p,{detailColumns:J});return}s(p,Y.id,G)},[p,b,r,s]),S=w.useCallback((Z,H)=>{if(!p)return;const z=b("groupBy")[Z];z&&s(p,z.id,{granularity:H})},[p,b,s]),N=w.useCallback((Z,H)=>{if(!p)return;const z=b("metrics")[Z];z&&o(p,z.id,{aliasTemplate:H})},[p,b,o]),j=w.useCallback((Z,H)=>{if(console.log("handleValueAliasesChange",Z,H),!p)return;console.log("handleValueAliasesChange",Z,H);const z=b("metrics")[Z];z&&(console.log("handleValueAliasesChange",H),o(p,z.id,{valueAliases:H}))},[p,b,o]),k=w.useCallback((Z,H)=>{var q,Y;if(!p)return;const z=b("metrics")[Z];z&&(o(p,z.id,{format:H}),m==="kpi"&&((Y=(q=e==null?void 0:e.preferences)==null?void 0:q.kpiVisualOptions)!=null&&Y.formatOptions)&&h({...e.preferences,kpiVisualOptions:{...e.preferences.kpiVisualOptions,formatOptions:void 0}}))},[e,p,m,b,h,o]),T=w.useCallback((Z,H)=>{var Y;if(!p)return;const z=b("metrics")[Z];if(!z)return;const q=H!=="none"&&((Y=z.parameters)==null?void 0:Y.windowTransform);o(p,z.id,{comparisonType:H,...H!=="target"?{targetValue:void 0}:{},...q?{parameters:{...z.parameters||{},windowTransform:void 0}}:{}})},[p,b,o]),E=w.useCallback((Z,H)=>{var be,te,ce;if(!p||!(e!=null&&e.config))return;const z=b("metrics")[Z];if(!z)return;if(H==="none"){o(p,z.id,{parameters:{...z.parameters||{},windowTransform:void 0}});return}const q=Mle({cardType:m,cardConfig:e.config,metric:z,transformMode:H});if(!q.supported){qe.error(q.reason||"Metric transform is not supported here.");return}const Y=new Set((e.config.groupByColumns||[]).map(se=>se.id)),G=(ce=(te=(be=z.parameters)==null?void 0:be.windowTransform)==null?void 0:te.orderBy)==null?void 0:ce.fieldId,J=G&&Y.has(G)?G:void 0,ne=aft({transformMode:H,cardType:m,cardConfig:e.config,fallbackOrderByFieldId:J});o(p,z.id,{comparisonType:"none",targetValue:void 0,parameters:{...z.parameters||{},windowTransform:ne}})},[e,p,m,b,o]),_=w.useCallback((Z,H)=>{var ne,be;if(!p||!(e!=null&&e.config))return;const z=b("metrics")[Z];if(!z)return;const q=(ne=z.parameters)==null?void 0:ne.windowTransform;if(!q||!["running_total","moving_average","previous_period_delta"].includes(q.function))return;const Y=Px({cardType:m,cardConfig:e.config,orderByFieldId:H}),J=(q.partitionByFieldIds||Y).filter(te=>te!==H);o(p,z.id,{parameters:{...z.parameters||{},windowTransform:{...q,orderBy:{fieldId:H,direction:((be=q.orderBy)==null?void 0:be.direction)||"asc"},partitionByFieldIds:J}}})},[e,p,m,b,o]),M=w.useCallback((Z,H)=>{var Y;if(!p)return;const z=b("metrics")[Z];if(!z)return;const q=(Y=z.parameters)==null?void 0:Y.windowTransform;!q||!["running_total","moving_average","previous_period_delta"].includes(q.function)||o(p,z.id,{parameters:{...z.parameters||{},windowTransform:{...q,orderBy:q.orderBy?{...q.orderBy,direction:H}:q.orderBy}}})},[p,b,o]),P=w.useCallback((Z,H)=>{var J,ne;if(!p||!(e!=null&&e.config))return;const z=b("metrics")[Z];if(!z)return;const q=(J=z.parameters)==null?void 0:J.windowTransform;if(!q)return;const Y=Px({cardType:m,cardConfig:e.config,orderByFieldId:(ne=q.orderBy)==null?void 0:ne.fieldId}),G=new Set(q.partitionByFieldIds||Y);G.has(H)?G.delete(H):G.add(H),o(p,z.id,{parameters:{...z.parameters||{},windowTransform:{...q,partitionByFieldIds:Array.from(G)}}})},[e,p,m,b,o]),D=w.useCallback((Z,H)=>{var ne,be;if(!p)return;const z=b("metrics")[Z];if(!z)return;const q=(ne=z.parameters)==null?void 0:ne.windowTransform;if(!q||q.function!=="moving_average")return;const Y=Math.max(1,Math.floor(H||1)),G=((be=q.movingAverage)==null?void 0:be.minPeriods)||1,J=Math.min(G,Y);o(p,z.id,{parameters:{...z.parameters||{},windowTransform:{...q,movingAverage:{windowSize:Y,minPeriods:J}}}})},[p,b,o]),A=w.useCallback((Z,H)=>{var J,ne;if(!p)return;const z=b("metrics")[Z];if(!z)return;const q=(J=z.parameters)==null?void 0:J.windowTransform;if(!q||q.function!=="moving_average")return;const Y=((ne=q.movingAverage)==null?void 0:ne.windowSize)||7,G=Math.max(1,Math.min(Math.floor(H||1),Y));o(p,z.id,{parameters:{...z.parameters||{},windowTransform:{...q,movingAverage:{windowSize:Y,minPeriods:G}}}})},[p,b,o]),L=w.useCallback((Z,H)=>{var Y;if(!p)return;const z=b("metrics")[Z];if(!z)return;const q=(Y=z.parameters)==null?void 0:Y.windowTransform;!q||q.function!=="previous_period_delta"||o(p,z.id,{parameters:{...z.parameters||{},windowTransform:{...q,previousPeriodDelta:{mode:H}}}})},[p,b,o]),$=w.useCallback((Z,H)=>{var G;if(!p||!(e!=null&&e.config))return;const z=b("metrics")[Z];if(!z)return;const q=(G=z.parameters)==null?void 0:G.windowTransform;if(!q||q.function!=="percent_of_total")return;const Y=H==="grand_total"?[]:(q.partitionByFieldIds||[]).length>0?q.partitionByFieldIds||[]:Px({cardType:m,cardConfig:e.config,orderByFieldId:void 0});o(p,z.id,{parameters:{...z.parameters||{},windowTransform:{...q,partitionByFieldIds:Y,percentOfTotal:{...q.percentOfTotal||{},scope:H}}}})},[e,p,m,b,o]),B=w.useCallback((Z,H)=>{var Y;if(!p)return;const z=b("metrics")[Z];if(!z)return;const q=(Y=z.parameters)==null?void 0:Y.windowTransform;!q||q.function!=="percent_of_total"||o(p,z.id,{parameters:{...z.parameters||{},windowTransform:{...q,percentOfTotal:{...q.percentOfTotal||{},output:H}}}})},[p,b,o]),V=w.useCallback(Z=>{p&&r(p,{showTrendline:Z})},[p,r]),R=w.useCallback(Z=>{p&&r(p,{trendlineWindow:Z})},[p,r]),U=w.useCallback(Z=>{p&&r(p,{trendlineGranularity:Z})},[p,r]),O=w.useCallback((Z,H)=>{if(!p)return;const z=b("metrics")[Z];z&&o(p,z.id,{targetValue:H})},[p,b,o]),I=w.useCallback(async Z=>{var ne;if(!p)return;const H=[...b("groupBy"),...b("pivotBy"),...b("metrics"),...b("sortBy"),...b("detailColumns")],K=Z,z=EIe(K,H,{joinPlan:(ne=e==null?void 0:e.config)==null?void 0:ne.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!z.isValid){z.showError&&hZ();return}const q=OIe(K,H,m);if(!q){qe.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const Y=_le(K,q,m);if(!Y.isValid){qe.error("Invalid Field Type",{description:Y.reason,position:"top-center",duration:3e3});return}const G=b(q);if(mZ(K,G))return;const J=vZ(K,q,G);if(J){const be=[...G,J];if(x(q,be),q==="metrics"){const te=Dle(e,J,e==null?void 0:e.preferences);te&&h(te),Ile(m,e==null?void 0:e.config,r,p,be)}}},[p,e,b,x,t,n,m,r,h]),W=w.useCallback((Z,H)=>{if(!p)return;const z=b(Z)[H];if(z){if(Z!=="sortBy"){const q=b("sortBy"),Y=q.filter(G=>!(G.name===z.name&&G.qualifiedEntityName===z.qualifiedEntityName));Y.length!==q.length&&r(p,{sortByColumns:Y})}switch(Z){case"groupBy":c(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;case"detailColumns":{r(p,{detailColumns:(b("detailColumns")||[]).filter((q,Y)=>Y!==H)});break}}}},[p,b,c,u,d,f,r]);return{getFieldsForContainer:b,setFieldsForContainer:x,updateLabel:y,handleAggregationChange:v,handleDateFormatChange:C,handleGranularityChange:S,handleAliasTemplateChange:N,handleValueAliasesChange:j,handleMetricFormatChange:k,removeField:W,handleFieldClick:I,handleMetricComparisonChange:T,handleMetricWindowTransformChange:E,handleMetricWindowOrderByChange:_,handleMetricWindowDirectionChange:M,handleMetricWindowPartitionToggle:P,handleMetricMovingAverageWindowSizeChange:D,handleMetricMovingAverageMinPeriodsChange:A,handleMetricPreviousPeriodDeltaModeChange:L,handleMetricPercentOfTotalScopeChange:$,handleMetricPercentOfTotalOutputChange:B,handleKpiShowTrendlineChange:V,handleKpiTrendlineWindowChange:R,handleKpiTrendlineGranularityChange:U,handleMetricTargetValueChange:O,cardType:m}};function OE(e,t){var ye,Ce,$e,ze,Ge,Ke,Ze,st;const{tokenProps:n}=rt(),r=cs(),s=rt().authToken||e,o=Ve(ae=>ae.selectedConnectionId),i=Ve(ae=>ae.card),{queryKey:a}=Ywe(i),c=Ve(ae=>ae.selectedDatamodelId),u=Ve(ae=>ae.isDevMode),d=Ve(ae=>ae.selectedDatabaseName),f=Ve(ae=>ae.selectedSchemaName),h=Ve(ae=>ae.selectedTableName),m=Ve(ae=>ae.actions.setSelectedConnectionId),p=Ve(ae=>ae.actions.setSelectedDatamodelId),g=Ve(ae=>ae.actions.setSelectedDatabaseName),b=Ve(ae=>ae.actions.setSelectedSchemaName),x=Ve(ae=>ae.actions.setSelectedTableName);Ve(ae=>ae.actions.setCardSql);const{setQueryConfig:y}=lr();function v(ae){var Te;if(!o||!ae)return!1;const Pe=((Te=T==null?void 0:T.capabilities)==null?void 0:Te.path)||[],Ee=Pe.includes("database"),_e=Pe.includes("schema");return!(!Pe.includes("table")||Ee&&(!d||d==="NA")||_e&&!f)}function C(ae){var Pe;return!o||!ae?!1:!!((Pe=T==null?void 0:T.capabilities)!=null&&Pe.path.includes("database"))}const{refetchConnections:S,connectionsData:N,isConnectionsLoading:j,isConnectionsError:k,selectedConnection:T}=Xi(e),{refetch:E,data:_,isLoading:M,isError:P}=Qt({queryKey:["models",o],queryFn:()=>or(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),D=T==null?void 0:T.type,A=((ye=T==null?void 0:T.capabilities)==null?void 0:ye.path.includes("schema"))??!1,L=((Ce=T==null?void 0:T.capabilities)==null?void 0:Ce.path.length)===1&&(($e=T==null?void 0:T.capabilities)==null?void 0:$e.path[0])==="table",$=L,{data:B,isLoading:V,isFetching:R,isError:U,refetch:O}=Qt({queryKey:["databases",o],queryFn:()=>or(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:C(D)}),{data:I,isLoading:W,isFetching:X,isError:Z,refetch:H}=Qt({queryKey:["schemas",o,d],queryFn:()=>or(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&A&&d!=="NA"}),{data:K,isLoading:z,isFetching:q,isError:Y,refetch:G}=Qt({queryKey:["tables",o,d,f],queryFn:()=>or(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(D)}),{columns:J,isColumnsLoading:ne,isColumnsFetching:be,isColumnsError:te,refetchColumns:ce}=CZ(e);w.useEffect(()=>{L&&(g(""),b(""),p(""),D==="API"&&x("api"))},[D,x,g,b,p,L]);const se=(T==null?void 0:T.type)==="API"?(ze=T==null?void 0:T.type)==null?void 0:ze.toLowerCase():h||"",ue=A&&f||"";function Re(ae){x(ae),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function je(ae){b(ae),x("")}function ke(ae){g(ae==="none"?"":ae),b(""),x(""),ae!=="none"&&ae!==""&&p("")}function me(ae){m(ae)}function Me(ae){p(ae==="none"?"":ae),ae!=="none"&&ae!==""&&g("")}B&&((Ge=B==null?void 0:B.databases)==null?void 0:Ge.length)>0,I&&((Ke=I==null?void 0:I.schemas)==null?void 0:Ke.length)>0;const Se=N==null?void 0:N.connections.map(ae=>({id:ae.id,name:ae.name,type:ae.type})),ie=(Ze=_==null?void 0:_.datamodels)==null?void 0:Ze.map(ae=>({id:ae.id,name:ae.name})),pe=B==null?void 0:B.databases.map(ae=>({id:ae.database_name,name:ae.database_name})),Ne=I==null?void 0:I.schemas.map(ae=>({id:ae.schema_name,name:ae.schema_name})),de=K==null?void 0:K.tables.map(ae=>({id:ae.table_name,name:ae.table_name})),fe=(st=_==null?void 0:_.datamodels.find(ae=>ae.id===c))==null?void 0:st.name,Oe=T!=null&&T.capabilities?Q1({schemaName:ue,tableName:se,modelName:fe,databaseName:d||"",capabilities:T.capabilities}):se;return{connectionItems:Se,selectedConnectionId:o,selectedConnection:T,isConnectionsLoading:j,isConnectionsError:k,modelItems:ie,selectedDatamodelId:c,selectedDatamodelName:fe,isModelsLoading:M,isModelsError:P,selectedDatabaseName:d,databaseItems:pe,isDatabasesLoadingOrFetching:V||R,isDatabaseError:U,schemaItems:Ne,selectedSchemaName:f,isSchemaLoadingOrFetching:W||X,isSchemaError:Z,tableItems:de,selectedTableName:h,isTableLoadingOrFetching:z||q,isTableError:Y,columns:J,isColumnsLoadingOrFetching:ne||be,isColumnsError:te,isNonDbConnection:$,connectionType:D,tableName:se,formattedTableName:Oe,schemaName:ue,refetchConnections:S,refetchModels:E,refetchDatabases:O,refetchSchemas:H,refetchTables:G,refetchColumns:ce,handleConnectionChange:me,handleDatamodelChange:Me,handleDatabaseChange:ke,handleSchemaChange:je,handleTableChange:Re}}function u1(e){return`${e}-${wr()}`}function dB(e,t){const n=Dl(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 uft(e,t){const n=Dl(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"quarter":return`Quarter of ${n}`;case"year":return`Year of ${n}`;case"hour":return`Hour of ${n}`;case"minute":return`Minute of ${n}`;case"second":return`Second of ${n}`;default:return n}}function e4(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 Rle(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Fle(){const e=Ve(j=>j.sqlGen),t=Ve(j=>j.isDevMode),n=Ve(j=>j.card.dataSource),r=Ve(j=>{var k,T;return(T=(k=j.card)==null?void 0:k.queryConfig)==null?void 0:T.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=e4(n),a=Rle(n),c=Ve(j=>j.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=lr(),{modelItems:g,selectedDatamodelName:b}=OE(),{selectedConnection:x}=Xi(),y=x==null?void 0:x.capabilities,v=j=>({column_name:j.name,data_type:j.dataType,label:j.label,description:j.description});return{handleDevModeFieldClick:j=>{var T;if(!t)return;const k=v(j);if(t&&a&&s&&y){const E=oA(k,e);m(E);const _=(T=g==null?void 0:g.find(P=>P.id===c))==null?void 0:T.name,M=sA(E,o||"",s,_||"",i||"",y,j.qualifiedEntityName);M&&(f(M),h(!0))}else if(!t){if(a0(k.data_type))if(r&&r.length>0){const E={...k,role:"groupby",id:u1(k.column_name),name:k.column_name,type:k.data_type};d(E)}else{const E={...k,role:"metric",id:u1(k.column_name),name:k.column_name,label:dB(k.column_name,"COUNT"),type:k.data_type,aggregate:"COUNT"};u(E)}if(Ca(k.data_type)){const E={...k,role:"groupby",id:u1(k.column_name),name:k.column_name,type:k.data_type,label:uft(k.column_name,"month"),granularity:"month"};d(E)}if(wa(k.data_type)){const E={...k,role:"metric",id:u1(k.column_name),name:k.column_name,label:dB(k.column_name,"SUM"),type:k.data_type,aggregate:"SUM"};u(E)}}},handleShowSample:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=Q1({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});p(!1);const T=(x==null?void 0:x.type)==="MSSQL"?`SELECT top 10 * FROM ${j}`:`SELECT * FROM ${j} LIMIT 10`;f(T),h(!0)},handleShowCount:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=Q1({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});f(`SELECT COUNT(*) as count FROM ${j}`),h(!0)},isNumberField:j=>wa(j.dataType)}}function dft(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>Hx(o)).join("."),s=Hx(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function Ple(e){const t=e;return{id:e.id,name:e.name,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityName:e.entityName,entityId:e.entityId,entityType:e.entityType,dataType:e.dataType,role:e.role,fieldScope:e.fieldScope,expression:t.expression,calculatedFormula:t.calculatedFormula}}function Ole(e,t){if(!(!e&&!t))return{semanticDomainId:e==null?void 0:e.semanticDomainId,selectedEntities:(e==null?void 0:e.selectedEntities)||[],connectionId:(e==null?void 0:e.connectionId)||(t==null?void 0:t.connectionId),connectionType:(e==null?void 0:e.connectionType)||(t==null?void 0:t.connectionType)}}function qS(e){var t,n;return e?!!(e.entityName===uo||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function fB(e){return e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e}function Gy(e,t){var g,b,x,y,v,C,S;if(!e.fieldMeta)return e.column===t.qualifiedFieldName||e.column===t.name;const n=fB((g=e.fieldMeta)==null?void 0:g.id),r=fB(t.id),s=((b=e.fieldMeta)==null?void 0:b.qualifiedFieldName)||e.column,o=s===t.qualifiedFieldName||s===t.name,i=(x=e.fieldMeta)==null?void 0:x.qualifiedEntityName,a=!i||!t.qualifiedEntityName||i===t.qualifiedEntityName,c=(y=e.fieldMeta)==null?void 0:y.entityId,u=!c||!t.entityId||c===t.entityId,d=(v=e.fieldMeta)==null?void 0:v.fieldScope;if(d&&t.fieldScope&&d!==t.fieldScope)return!1;const f=(C=e.fieldMeta)==null?void 0:C.role;if(f&&t.role&&f!==t.role)return!1;const h=qS(e.fieldMeta)||qS(t);if(h&&n&&r&&n===r)return!0;if(!h&&(!a||!u))return!1;const m=(S=e.fieldMeta)==null?void 0:S.expression,p=t.expression;return m||p?o&&a&&u&&m===p:o&&a&&u}function Lle(){const e=ee(c=>c.dashboard.filters)||[],t=ee(c=>c.selectedSheetId),n=ee(c=>c.actions.addFilter),r=ee(c=>c.actions.removeFilter),{removeFilterValues:s}=en(),o=Ve(c=>c.card.dataSource),{selectedConnection:i}=Xi();function a(c,u="sheet"){const{qualifiedColumnName:d,qualifiedTableName:f,formattedColumnName:h}=dft(c);let m;if(u==="sheet"&&t){const p=Yl(e,t);m=p.find(g=>g.fieldMeta&&Gy(g,c))||vPe(p.filter(g=>!g.fieldMeta),d,f,t)}else m=e==null?void 0:e.find(p=>Gy(p,c)||!p.fieldMeta&&Op(p.column)===Op(d));if(m)s(m.id),r(m.id);else{const p=wr(),g=Ple(c),b=Ole(o,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),x=qS(g),y=u==="sheet"&&t?[t]:void 0,v=Sn(c.dataType)==="date"?"between":"in";return n({id:p,location:u,column:d,title:c.label||c.name,dataType:c.dataType,qualifiedTableName:f,connectionId:(i==null?void 0:i.id)||"",operation:v,applyToSheetIds:y,sql:x?"":Kte(c.dataType,f,h),fieldMeta:g,semanticContext:b}),p}}return{assignFilter:a}}function fft({column:e}){const[t,n]=w.useState(!1),r=Ve(v=>v.isDevMode),s=Ve(v=>v.card.dataSource),{tableName:o,schemaName:i,databaseName:a}=e4(s),c=Ve(v=>v.selectedDatamodelId),u=Ve(v=>v.sqlGen),{modelItems:d,selectedConnection:f}=OE(),h=f==null?void 0:f.capabilities,m=Ve(v=>v.actions.setSqlGen),p=Ve(v=>v.actions.setCardSql),g=Ve(v=>v.actions.setRunSql),b=Rle(s);function x(v,C){var T,E;if(!b||!o){console.warn("Cannot generate SQL: missing table metadata");return}const S=oA(v,u,C),N=(T=d==null?void 0:d.find(_=>_.id===c))==null?void 0:T.name;if(m(S),!h){console.warn("Cannot generate SQL: missing connection capabilities");return}const j=(E=v.qualifiedFieldName)==null?void 0:E.split(".").slice(0,-1).join("."),k=sA(S,i||"",o,N||"",a||"",h,j);k&&(p(k),g(!0)),n(!1)}function y(){return l.jsxs("ul",{className:"text-xs",children:[l.jsx("li",{onClick:()=>x(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),l.jsx("li",{onClick:()=>x(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),l.jsx("li",{onClick:()=>x(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),l.jsx("li",{onClick:()=>x(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),l.jsx("li",{onClick:()=>x(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return!r||!b?null:l.jsxs(Yc,{openDelay:0,open:t,onOpenChange:n,children:[l.jsx(Gc,{asChild:!0,children:l.jsx(_h,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),l.jsx(Ia,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:y()})]})}const $le="absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 font-mono text-[7px] font-semibold leading-none shadow-sm",hB="bg-emerald-500/90 text-white",hft="bg-blue-500/90 text-white";function zle(e){const t=fd(e);return t==="none"?null:t==="inline_expression"?{label:"{}",badgeClassName:hB}:{label:"fx",badgeClassName:e.role==="metric"?hB:hft}}function mft(e){if(!e)return[];const t=[{label:"Type",value:e.type}];if("locale"in e&&e.locale&&t.push({label:"Locale",value:e.locale}),e.prefix&&t.push({label:"Prefix",value:e.prefix}),e.suffix&&t.push({label:"Suffix",value:e.suffix}),e.type==="date")return e.pattern&&t.push({label:"Pattern",value:e.pattern}),e.timezone&&t.push({label:"Timezone",value:e.timezone}),e.sourceTimezone&&t.push({label:"Source TZ",value:e.sourceTimezone}),e.relative!==void 0&&t.push({label:"Relative",value:e.relative?"On":"Off"}),t;if("minimumFractionDigits"in e||"maximumFractionDigits"in e){const n=e.minimumFractionDigits,r=e.maximumFractionDigits;if(n!==void 0||r!==void 0){const s=n!==void 0&&r!==void 0?n===r?`${n}`:`${n}-${r}`:`${n??"auto"}-${r??"auto"}`;t.push({label:"Decimals",value:s})}}return"useGrouping"in e&&e.useGrouping!==void 0&&t.push({label:"Grouping",value:e.useGrouping?"On":"Off"}),"currency"in e&&e.currency&&t.push({label:"Currency",value:e.currency}),"percentValueMode"in e&&e.percentValueMode&&t.push({label:"Percent Input",value:e.percentValueMode}),"negativeStyle"in e&&e.negativeStyle&&t.push({label:"Negative Style",value:e.negativeStyle}),"compact"in e&&e.compact!==void 0&&t.push({label:"Compact",value:e.compact?"On":"Off"}),"scale"in e&&e.scale!==void 0&&t.push({label:"Scale",value:String(e.scale)}),t}function pft(e){var n;if(!e.expression)return null;const t=((n=e.calculatedFormula)==null?void 0:n.inputFields)||[];return t.length?e.expression.replace(/\{field_(\d+)\}/g,(r,s)=>{const o=t[Number(s)];return o?`{${o.name||o.label}}`:r}):e.expression}function gft({field:e,fieldState:t}){const n=pft(e),r=mft(e.format);return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[l.jsx("h3",{className:"text-[13px] font-medium text-foreground",children:e.label||e.name}),l.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-[11px] text-muted-foreground",children:e.dataType})]}),e.description&&l.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),n&&l.jsxs("div",{className:"mb-3 rounded bg-muted/50 p-2",children:[l.jsx("p",{className:"mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Expression"}),l.jsx("code",{className:"block whitespace-pre-wrap break-all font-mono text-xs text-foreground",children:n})]}),r.length>0&&l.jsxs("div",{className:"mb-3 rounded bg-muted/50 p-2",children:[l.jsx("p",{className:"mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Format"}),l.jsx("div",{className:"space-y-0.5",children:r.map(s=>l.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[l.jsx("span",{className:"text-muted-foreground",children:s.label}),l.jsx("span",{className:"font-mono text-foreground",children:s.value})]},`${s.label}-${s.value}`))})]}),t&&t.tooltip&&l.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:l.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),l.jsx("div",{className:"overflow-x-auto border-t border-border pt-2",children:l.jsx("span",{className:"font-mono text-[11px] text-muted-foreground",children:e.name})})]})}function mB({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o}){const i=Ve(Y=>Y.isDevMode),a=t==="filter"||t==="inline-filter",c=i||a||(n==null?void 0:n.state)==="unreachable"&&!a,u=ee(Y=>Y.dashboard.filters),d=ee(Y=>Y.selectedSheetId),f=ee(Y=>Y.actions.removeFilter),{removeFilterValues:h}=en(),{assignFilter:m}=Lle(),p=t==="filter"?Yl(u,d):u,g=t==="filter"?p==null?void 0:p.find(Y=>{if(Gy(Y,e))return!0;if(Y.fieldMeta)return!1;const G=Op(Y.column||""),J=Op(e.name);return G.endsWith(`.${J}`)||G===J}):void 0,b=!!g,x=t==="inline-filter"&&(s==null?void 0:s.some(Y=>Gy(Y,e))),y=b||x,v=g&&a?u==null?void 0:u.find(Y=>Y.id===g.id):void 0,C=v&&(v.applyToSheetIds&&v.applyToSheetIds.length>1||v.excludeSheetIds&&v.excludeSheetIds.length>0||!v.applyToSheetIds&&!v.excludeSheetIds&&!v.sheetId);a&&y&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:y,activeFilterOnSheet:g?{id:g.id,title:g.title,column:g.column,applyToSheetIds:g.applyToSheetIds,excludeSheetIds:g.excludeSheetIds}:null,activeFilterForField:v?{id:v.id,title:v.title,column:v.column,applyToSheetIds:v.applyToSheetIds,excludeSheetIds:v.excludeSheetIds}:null,isMultiSheetFilter:C,selectedSheetId:d});const[S,N]=w.useState(!1),[j,k]=w.useState(null),{attributes:T,listeners:E,setNodeRef:_,transform:M,transition:P,isDragging:D}=Yg({id:e.id,disabled:c}),[A,L]=w.useState(!1),$=Ve(Y=>Y.card),{handleFieldClick:B}=Ale($),{handleDevModeFieldClick:V,isNumberField:R}=Fle(),U=()=>{v&&(console.log("[SourceField] Removing multi-sheet filter:",v.id),h(v.id),f(v.id)),k(null),N(!1)},O=()=>{if(t==="inline-filter"&&r){r(e);return}t==="filter"?y&&C?(k(e),N(!0)):m(e,"sheet"):i?V(e):B(e)},I={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},W={transform:Si.Transform.toString(M),transition:P},X=()=>{if(!n||a)return{};const G={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",...G},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...G},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...G}}[n.state]||G};function Z(Y){return Y==="domain"?{label:"Semantic domain",Icon:jpe,className:"text-foreground/55 hover:text-foreground/85"}:Y==="dashboard"?{label:"Dashboard",Icon:BA,className:"text-foreground/55 hover:text-foreground/85"}:{label:"Card",Icon:YU,className:"text-foreground/55 hover:text-foreground/85"}}const H=X(),K=e.fieldScope,z=K?Z(K):null,q=zle(e);return l.jsxs("div",{ref:_,style:W,...c?{}:T,...c?{}:E,className:Q("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",D&&"scale-95 opacity-50",!D&&"border",H.borderColor||"border-transparent",H.bgColor||"",H.hoverBorderColor,H.hoverBgColor||"hover:bg-muted",H.opacity,H.cursor,b&&"border-accent-foreground/20 bg-accent",x&&"border-primary/20 bg-primary/10",{"cursor-pointer":i||a,"cursor-grab active:cursor-grabbing":!c&&!i&&!a}),title:n==null?void 0:n.tooltip,children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:O,children:[l.jsxs("div",{className:"relative shrink-0",children:[bh(e.dataType),q&&l.jsx("span",{className:Q($le,q.badgeClassName),children:q.label})]}),l.jsxs(Yc,{openDelay:200,closeDelay:100,children:[l.jsx(Gc,{asChild:!0,children:l.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:l.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${A?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),l.jsx(Ia,{side:"bottom",align:"start",className:"ml-5 w-72 p-3",children:l.jsx(gft,{field:e,fieldState:n})})]}),i&&!a&&R(e)&&l.jsx("div",{onClick:Y=>Y.stopPropagation(),children:l.jsx(fft,{column:I})}),t==="editor"&&z&&l.jsxs("div",{className:"ml-auto flex items-center",onClick:Y=>Y.stopPropagation(),onPointerDown:Y=>Y.stopPropagation(),children:[o&&l.jsx("div",{className:"mr-1 flex items-center opacity-0 transition-opacity pointer-events-none group-hover/container:opacity-100 group-hover/container:pointer-events-auto group-focus-within/container:opacity-100 group-focus-within/container:pointer-events-auto [@media(hover:none)]:opacity-100 [@media(hover:none)]:pointer-events-auto",children:o}),l.jsxs(wn,{children:[l.jsx(Cn,{asChild:!0,children:l.jsx("span",{"aria-label":`${z.label} calculated field`,title:"",className:Q("block p-0.5 transition-colors",z.className),children:l.jsx(z.Icon,{className:"h-3.5 w-3.5"})})}),l.jsxs(Tn,{side:"top",align:"end",children:[z.label," calculated field"]})]})]}),o&&(!z||t!=="editor")&&l.jsx("div",{className:"ml-auto flex items-center",onClick:Y=>Y.stopPropagation(),onPointerDown:Y=>Y.stopPropagation(),children:o})]}),A&&l.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:l.jsx(xi,{className:"",children:l.jsxs(Ea,{className:"space-y-2 p-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(GU,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"break-all",children:e.label||e.name})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Dpe,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"break-all",children:e.name})]}),l.jsx(Xe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),l.jsx(qc,{open:S,onOpenChange:N,children:l.jsxs(Pl,{children:[l.jsxs(Ol,{children:[l.jsx($l,{children:"Remove Filter from Multiple Sheets?"}),l.jsx(zl,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),l.jsxs(Ll,{children:[l.jsx(Bl,{children:"Cancel"}),l.jsx(Vl,{onClick:U,children:"Remove Filter"})]})]})})]})}var Ua="Accordion",bft=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[t4,xft,yft]=b0(Ua),[LE]=us(Ua,[yft,RX]),n4=RX(),Vle=w.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return l.jsx(t4.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?l.jsx(Sft,{...o,ref:t}):l.jsx(Cft,{...s,ref:t})})});Vle.displayName=Ua;var[Ble,vft]=LE(Ua),[Ule,wft]=LE(Ua,{collapsible:!1}),Cft=w.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,c]=Ms({prop:n,defaultProp:r??"",onChange:s,caller:Ua});return l.jsx(Ble,{scope:e.__scopeAccordion,value:w.useMemo(()=>a?[a]:[],[a]),onItemOpen:c,onItemClose:w.useCallback(()=>o&&c(""),[o,c]),children:l.jsx(Ule,{scope:e.__scopeAccordion,collapsible:o,children:l.jsx(Hle,{...i,ref:t})})})}),Sft=w.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=Ms({prop:n,defaultProp:r??[],onChange:s,caller:Ua}),c=w.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=w.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return l.jsx(Ble,{scope:e.__scopeAccordion,value:i,onItemOpen:c,onItemClose:u,children:l.jsx(Ule,{scope:e.__scopeAccordion,collapsible:!0,children:l.jsx(Hle,{...o,ref:t})})})}),[Nft,$E]=LE(Ua),Hle=w.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=w.useRef(null),c=Et(a,t),u=xft(n),f=hd(s)==="ltr",h=Ye(e.onKeyDown,m=>{var k;if(!bft.includes(m.key))return;const p=m.target,g=u().filter(T=>{var E;return!((E=T.ref.current)!=null&&E.disabled)}),b=g.findIndex(T=>T.ref.current===p),x=g.length;if(b===-1)return;m.preventDefault();let y=b;const v=0,C=x-1,S=()=>{y=b+1,y>C&&(y=v)},N=()=>{y=b-1,y<v&&(y=C)};switch(m.key){case"Home":y=v;break;case"End":y=C;break;case"ArrowRight":o==="horizontal"&&(f?S():N());break;case"ArrowDown":o==="vertical"&&S();break;case"ArrowLeft":o==="horizontal"&&(f?N():S());break;case"ArrowUp":o==="vertical"&&N();break}const j=y%x;(k=g[j].ref.current)==null||k.focus()});return l.jsx(Nft,{scope:n,disabled:r,direction:s,orientation:o,children:l.jsx(t4.Slot,{scope:n,children:l.jsx(at.div,{...i,"data-orientation":o,ref:c,onKeyDown:r?void 0:h})})})}),YS="AccordionItem",[jft,r4]=LE(YS),Wle=w.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=$E(YS,n),i=vft(YS,n),a=n4(n),c=Lr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return l.jsx(jft,{scope:n,open:u,disabled:d,triggerId:c,children:l.jsx(OX,{"data-orientation":o.orientation,"data-state":Xle(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Wle.displayName=YS;var qle="AccordionHeader",Yle=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=$E(Ua,n),o=r4(qle,n);return l.jsx(at.h3,{"data-orientation":s.orientation,"data-state":Xle(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Yle.displayName=qle;var DD="AccordionTrigger",Gle=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=$E(Ua,n),o=r4(DD,n),i=wft(DD,n),a=n4(n);return l.jsx(t4.ItemSlot,{scope:n,children:l.jsx(NDe,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Gle.displayName=DD;var Kle="AccordionContent",Zle=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=$E(Ua,n),o=r4(Kle,n),i=n4(n);return l.jsx(jDe,{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}})});Zle.displayName=Kle;function Xle(e){return e?"open":"closed"}var Eft=Vle,kft=Wle,Tft=Yle,Qle=Gle,Jle=Zle;const zE=Eft,Wp=F.forwardRef(({className:e,...t},n)=>l.jsx(kft,{ref:n,className:Q("border-b",e),...t}));Wp.displayName="AccordionItem";const qp=F.forwardRef(({className:e,children:t,...n},r)=>l.jsx(Tft,{className:"flex",children:l.jsxs(Qle,{ref:r,className:Q("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,l.jsx(pr,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));qp.displayName=Qle.displayName;const Yp=F.forwardRef(({className:e,children:t,...n},r)=>l.jsx(Jle,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:l.jsx("div",{className:Q("pb-4 pt-0",e),children:t})}));Yp.displayName=Jle.displayName;let ece=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");const Ky=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",requiresTwoInputs:!0},{id:"product",label:"Product (Multiplication)",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",requiresTwoInputs:!0},{id:"scale",label:"Scale (Multiply by Factor)",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}],s4=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),rf=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function tce(e,t){e.forEach(n=>{var i;const r=n.id||n.qualifiedFieldName||n.name;if(r&&t.visited.has(r))return;if(r&&t.visited.add(r),Nle(n)){t.disqualified=!0;return}const s=(i=n.calculatedFormula)==null?void 0:i.inputFields;if(s!=null&&s.length){tce(s,t);return}if(n.expression&&!(fd(n)==="inline_expression"&&va(n)&&n.fieldScope==="domain")){t.disqualified=!0;return}if(!n.entityName||!n.entityId){t.disqualified=!0;return}const o=n.qualifiedEntityName||n.entityId||n.entityName;t.entities.has(o)||t.entities.set(o,{entityName:n.entityName,entityId:n.entityId,qualifiedEntityName:n.qualifiedEntityName})})}function o4(e){const t={entities:new Map,disqualified:!1,visited:new Set};if(tce(e,t),t.disqualified||t.entities.size!==1)return{kind:"multi-entity"};const[n]=Array.from(t.entities.values());return!(n!=null&&n.entityName)||!n.entityId?{kind:"multi-entity"}:{kind:"inline",entityName:n.entityName,entityId:n.entityId,qualifiedEntityName:n.qualifiedEntityName}}const pB="calculated_fields";function _ft(e){return e?e.startsWith("calc_")||e.startsWith("calc_dim_"):!1}function Ift(e){return e.fieldScope==="domain"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===uo||e.entityName===pB||e.qualifiedEntityName===pB||_ft(e.id)}function Mft(e){return e.aggregate?e.aggregate:gZ(e.dataType)}function Dft(e,t){const n=Mft(t);return n==="DISTINCT"?`COUNT(DISTINCT ${e})`:`${n}(${e})`}function Aft(e,t){return e.replace(/\{field_(\d+)\}/g,(n,r)=>{const s=Number(r),o=t[s];return!o||Ift(o)||typeof o.expression=="string"&&pZ(o.expression)?n:Dft(n,o)})}function gB(e,t,n,r,s,o,i,a,c,u){const d=Ky.find(y=>y.id===t);if(!d)throw new Error(`Unknown operation: ${t}`);let f,h=[],m;if(t==="custom"){if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}else if(t==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(c===void 0||Number.isNaN(c))throw new Error("Constant factor is required for scale operation");f=d.template().replace("{constant}",String(c)),h=[n],m=c}else{if(!n||!r)throw new Error("Metrics A and B are required for standard operations");f=d.template(),h=[n,r]}t!=="custom"&&(f=Aft(f,h));const p={operation:t,inputFields:h,...m!==void 0&&{constant:m}},g=s4(e),b=o4(h);return{id:i||`calc_${ece(10)}`,name:g,label:e,alias:g,qualifiedFieldName:g,dataType:"number",role:"metric",expression:f,calculatedFormula:p,entityId:b.kind==="inline"?b.entityId:o,entityName:b.kind==="inline"?b.entityName:uo,qualifiedEntityName:b.kind==="inline"?b.qualifiedEntityName:void 0,entityType:b.kind==="inline"?"dataset":"table",description:`Calculated field: ${e}`}}function Rft(e){var r,s;const t=Ky.find(o=>o.id===e.operation);if(!t)return"Unknown operation";if(e.operation==="custom")return"Custom expression";if(e.operation==="scale"){const o=((r=e.inputFields[0])==null?void 0:r.label)||((s=e.inputFields[0])==null?void 0:s.name)||"A",i=e.constant??1;return`${o} × ${i}`}return e.inputFields.map(o=>o.label||o.name).join(` ${t.symbol} `)}function Fft(e,t,n,r,s,o){const i=s4(e),a=o4(n);return bZ({id:o||`calc_dim_${ece(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(c=>c.role==="metric"?{...c,role:"metric"}:{...c,role:"groupby"})},entityId:a.kind==="inline"?a.entityId:s,entityName:a.kind==="inline"?a.entityName:uo,qualifiedEntityName:a.kind==="inline"?a.qualifiedEntityName:void 0,entityType:a.kind==="inline"?"dataset":"table",description:`Calculated field: ${e.trim()}`})}function Pft({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const s=r.length>0?r:["dimension","metric"],o=["dimension","metric"].filter(c=>s.includes(c)),i=n||o.length<=1,a=o.includes(e)?e:o[0];return l.jsx(As,{value:a,onValueChange:c=>t(c),className:"w-full",children:l.jsx(ys,{className:"grid w-full",style:{gridTemplateColumns:`repeat(${o.length}, minmax(0, 1fr))`},children:o.map(c=>l.jsx(on,{value:c,disabled:i,children:c==="metric"?"Calculated Metric":"Calculated Dimension"},c))})})}function Oft({groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:r,selectedFieldIds:s,disabled:o}){const i=new Set(s||[]),a=e.length>0||t.length>0,c=e.map(f=>f.id),u=(f,h)=>{if(!h)return f;const m=f.toLowerCase(),p=h.toLowerCase();return m.startsWith(`${p}.`)?f.slice(h.length+1):f},d=(f,h)=>{const p=(f.name||f.baseLabel||f.label||f.tokenLabel||"").trim(),g=[h,f.qualifiedEntityName,f.entityName].filter(Boolean);for(const b of g){const x=u(p,b);if(x!==p)return x}return p.includes(".")&&p.split(".").pop()||p};return l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border pr-4",children:[a&&l.jsxs("div",{className:"relative",children:[l.jsx(Ws,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx(lt,{value:t,onChange:f=>n(f.target.value),placeholder:"Search fields...",className:"pl-10 pr-10"}),t&&l.jsx("button",{type:"button",onClick:()=>n(""),className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",children:l.jsx(Mt,{className:"size-3.5"})})]}),l.jsx(za,{className:"min-h-0 flex-1",children:e.length===0?l.jsx("div",{className:"rounded-md border border-dashed border-muted px-3 py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):l.jsx(zE,{type:"multiple",defaultValue:c,className:"space-y-2",children:e.map(f=>l.jsxs(Wp,{value:f.id,className:"border-none",children:[l.jsx(qp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:f.label}),l.jsx(Xe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:f.fields.length})]})}),l.jsx(Yp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:f.fields.map(h=>{const m=i.has(h.id),p=!h.isCompatible||o,g=h.isCalculated&&h.role==="metric",b=d(h,f.label);return l.jsxs("button",{type:"button",onClick:()=>h.isCompatible&&!o&&r(h),className:Q("group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all",p?"cursor-not-allowed opacity-50":"hover:bg-muted",m&&"border-border bg-muted"),disabled:p,children:[l.jsxs("div",{className:"relative shrink-0",children:[bh(h.dataType),h.isCalculated&&l.jsx("span",{className:Q("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",g?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:l.jsx("span",{className:Q("block truncate text-sm text-foreground/80",!p&&"group-hover/container:text-foreground"),children:b})}),m&&l.jsx(Xe,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Selected"})]},h.id)})})})]},f.id))})})]})}function Lft({value:e,onChange:t,allowCustom:n,disabled:r}){const s=Ky.filter(c=>n?!0:c.id!=="custom"),i=!s.some(c=>c.id==="custom")&&e==="custom"?[...s,Ky.find(c=>c.id==="custom")]:s,a=i.find(c=>c.id===e);return l.jsxs("div",{className:"space-y-2",children:[l.jsxs(pt,{value:e,onValueChange:c=>t(c),disabled:r,children:[l.jsx(ft,{children:l.jsx(gt,{})}),l.jsx(ht,{children:l.jsxs(GF,{children:[l.jsx(wj,{children:"OPERATIONS"}),i.map(c=>l.jsx(Ie,{value:c.id,children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"font-mono text-sm",children:c.symbol}),l.jsx("span",{children:c.label})]})},c.id))]})})]}),a&&l.jsx("p",{className:"text-xs text-muted-foreground",children:a.description})]})}const $ft={COUNT:"Count",DISTINCT:"Count Distinct",SUM:"Sum",AVG:"Average",MIN:"Minimum",MAX:"Maximum",MEDIAN:"Median"};function zft({value:e,onChange:t,disabled:n,fieldDataType:r,allowMedian:s}){const i=(r?Sn(r):"number")==="number",a=["SUM","AVG","COUNT","DISTINCT","MIN","MAX"],c=i?s?[...a,"MEDIAN"]:a:["COUNT","DISTINCT"];return l.jsxs(pt,{value:e,onValueChange:u=>t(u),disabled:n,children:[l.jsx(ft,{className:"h-9",children:l.jsx(gt,{})}),l.jsx(ht,{children:c.map(u=>l.jsx(Ie,{value:u,children:$ft[u]},u))})]})}const Vft=e=>{const n=(e.name||e.baseLabel||e.label||e.tokenLabel||"").trim();return n.includes(".")&&n.split(".").pop()||n};function bB({label:e,input:t,availableFields:n,excludeFieldIds:r,onFieldSelect:s,onAggregateChange:o,onRemove:i,onActivate:a,allowMedian:c,disabled:u}){const d=(t==null?void 0:t.field.id)||"",f=r!=null&&r.length?n.filter(h=>!r.includes(h.id)):n;return l.jsxs("div",{className:Q("flex items-center gap-2 rounded-md border border-border px-2 py-2",a&&!u&&"cursor-pointer",u&&"opacity-60"),onClick:u?void 0:a,children:[l.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded bg-muted font-mono text-xs font-semibold",children:e}),l.jsxs("div",{className:"flex flex-1 gap-2",children:[l.jsxs(pt,{value:d,onValueChange:h=>{const m=f.find(p=>p.id===h);m&&s(m)},disabled:u,children:[l.jsx(ft,{className:"h-9 flex-1",children:l.jsx(gt,{placeholder:"Select field"})}),l.jsx(ht,{children:f.map(h=>l.jsx(Ie,{value:h.id,children:Vft(h)},h.id))})]}),l.jsx("div",{className:"w-36",children:l.jsx(zft,{value:(t==null?void 0:t.aggregate)||"SUM",onChange:o,disabled:u||(t==null?void 0:t.isCalculatedField),fieldDataType:t==null?void 0:t.field.dataType,allowMedian:c})})]}),t&&l.jsx(re,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:h=>{h.stopPropagation(),i()},disabled:u,children:l.jsx(Mt,{className:"h-3.5 w-3.5"})})]})}const xB=w.forwardRef(function({value:t,onChange:n,onGenerate:r,showGenerate:s,docsUrl:o,placeholder:i,disabled:a},c){return l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx(ge,{children:"Expression"}),l.jsxs("div",{className:"flex items-center gap-2",children:[o&&l.jsxs("a",{href:o,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:["Docs",l.jsx(pp,{className:"h-3 w-3"})]}),s&&l.jsxs(re,{type:"button",size:"sm",variant:"outline",onClick:r,disabled:a,className:"h-7 text-xs",children:[l.jsx(uC,{className:"mr-1.5 h-3.5 w-3.5"}),"Generate with AI"]})]})]}),l.jsx(yi,{ref:c,value:t,onChange:u=>n(u.target.value),disabled:a,rows:3,placeholder:i||"CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",className:"min-h-0 resize-none overflow-y-auto font-mono text-xs leading-5"})]})}),i4=F.forwardRef(({className:e,sideOffset:t=8,...n},r)=>l.jsx(JW,{children:l.jsx(wle,{children:l.jsx(jR,{ref:r,sideOffset:t,className:Q("z-[60] overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})})}));i4.displayName="ValidationTooltipContent";const nce=eq;function QT(e,t){return`${e} ${t}${e===1?"":"s"}`}function Bft({result:e}){const t=e.errors.length>0,n=QT(e.tokens.length,"token"),r=e.errors.length>0?QT(e.errors.length,"error"):null,s=e.warnings.length>0?QT(e.warnings.length,"warning"):null,o=e.errors.map(i=>i.suggestion?`${i.message} (${i.suggestion})`:i.message).join(`
1393
- `);return l.jsxs(wn,{delayDuration:120,children:[l.jsx(Cn,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":t?"Validation failed. Hover to view details.":"Validation passed. Hover to view details.",className:Q("inline-flex h-5 w-5 items-center justify-center rounded-full transition-colors",t?"bg-destructive text-destructive-foreground hover:bg-destructive/90":"bg-emerald-600 text-white hover:bg-emerald-700"),children:t?l.jsx(Mt,{className:"h-3 w-3","aria-hidden":!0}):l.jsx(qr,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(i4,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(440px,calc(100vw-32px))] p-0",children:[l.jsxs("div",{className:"space-y-2.5 p-3 text-xs",children:[l.jsx("div",{className:Q("font-semibold",t?"text-destructive":"text-emerald-700"),children:t?"Validation failed":"Validation passed"}),l.jsxs("div",{className:"flex flex-wrap gap-x-2 gap-y-1 text-[11px] text-muted-foreground",children:[l.jsx("span",{children:n}),r&&l.jsx("span",{children:r}),s&&l.jsx("span",{children:s}),e.inferredDataType&&l.jsxs("span",{children:["type: ",e.inferredDataType]})]}),e.tokens.length>0&&l.jsxs("div",{className:"space-y-1.5 border-t pt-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Tokens"}),l.jsx("div",{className:"max-h-28 space-y-1 overflow-y-auto pr-1 select-text",children:e.tokens.map((i,a)=>l.jsxs("div",{className:"flex items-start gap-1.5",children:[l.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 font-mono leading-none",children:`{${i.token}}`}),l.jsx(DA,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}),i.field?l.jsx("span",{className:"break-all text-muted-foreground",children:i.field.qualifiedFieldName||i.field.name}):l.jsx("span",{className:"text-muted-foreground",children:"Unresolved"})]},`${i.token}-${a}`))})]}),e.errors.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-destructive",children:"Errors"}),l.jsx(Fc,{text:o,ariaLabel:"Copy validation errors",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-destructive select-text",children:e.errors.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.warnings.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-amber-700",children:"Warnings"}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-amber-700 select-text",children:e.warnings.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.inferredDataType&&l.jsxs("div",{className:"border-t pt-2 text-[11px] text-muted-foreground",children:["Inferred output type:"," ",l.jsx("span",{className:"font-medium text-foreground",children:e.inferredDataType})]})]}),l.jsx(nce,{className:"fill-popover"})]})]})}function yB({onValidate:e,isValidating:t,validationResult:n,error:r,disabled:s}){return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(re,{type:"button",variant:"outline",size:"sm",onClick:e,disabled:t||s,children:t?"Validating expression (may take a few seconds)...":"Validate Expression"}),n&&l.jsx(Bft,{result:n}),!n&&r&&l.jsxs(wn,{delayDuration:120,children:[l.jsx(Cn,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Validation failed. Hover to view details.",className:"inline-flex h-5 w-5 items-center justify-center rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90",children:l.jsx(Mt,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(i4,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(420px,calc(100vw-32px))] p-3",children:[l.jsxs("div",{className:"space-y-2 text-xs",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("span",{className:"font-semibold text-destructive",children:"Validation failed"}),l.jsx(Fc,{text:r,ariaLabel:"Copy validation error",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("p",{className:"max-h-40 overflow-y-auto break-words text-destructive select-text",children:r})]}),l.jsx(nce,{className:"fill-popover"})]})]})]})}function Uft({scope:e,onChange:t,showDashboardScope:n,error:r,disabled:s}){return l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(ge,{children:"Availability"}),l.jsxs(Do,{value:e,onValueChange:o=>t(o),className:"gap-0.5",disabled:s,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx($n,{id:"scope-card",value:"card"}),l.jsx(ge,{htmlFor:"scope-card",className:"text-sm font-normal",children:"This card only"})]}),n&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx($n,{id:"scope-dashboard",value:"dashboard"}),l.jsx(ge,{htmlFor:"scope-dashboard",className:"text-sm font-normal",children:"All cards on this sheet"})]})]}),r&&l.jsx("p",{className:"text-xs text-destructive",children:r})]})}function Hft(e){var r;const t=f0(e,"AI generation failed"),n=(r=ime(e))==null?void 0:r[0];return n?n.hint?`${n.message} Hint: ${n.hint}`:n.message||t:t}function Wft({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=rt(),[o,i]=w.useState(!1),[a,c]=w.useState(null);return{generateExpression:w.useCallback(async d=>{var f;if(!e)return c("AI generation is not available"),null;if(!d.trim())return c("Describe what you want to calculate"),null;i(!0),c(null);try{const h={type:"calculated-field-expression",context:{userQuery:d,availableFields:t.map(p=>({name:p.tokenLabel,dataType:p.dataType,...p.role==="metric"||p.role==="groupby"?{role:p.role}:{}})),fieldType:n},options:{dialect:r}},m=await Is(e,(s==null?void 0:s.accessToken)||"",h);if(!m.success||!((f=m.result)!=null&&f.generated))throw new Error(m.error||"No expression generated");return m.result.generated}catch(h){return c(Hft(h)),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),isGenerating:o,error:a}}function rce(e){return e.entityName===Io||e.qualifiedEntityName===Io||e.entityName===uo}function qft(e){return rce(e)?Io:e.qualifiedEntityName||e.entityName||"Other"}function Yft(e){return rce(e)?"Calculated Fields":e.qualifiedEntityName?Kf(e.entityName||e.qualifiedEntityName):Kf(e.entityName||"Other")}function Gft({open:e,onOpenChange:t,availableFields:n,fieldType:r,onExpressionGenerated:s,endpoint:o,dialect:i}){const[a,c]=w.useState(""),[u,d]=w.useState(""),[f,h]=w.useState(""),[m,p]=w.useState([]),g=w.useRef(null),{generateExpression:b,isGenerating:x,error:y}=Wft({endpoint:o,availableFields:n,fieldType:r,dialect:i}),v=w.useMemo(()=>{const M=f.trim().toLowerCase();return M?n.filter(P=>[P.label,P.baseLabel,P.name,P.tokenLabel,P.entityName,P.qualifiedEntityName].filter(Boolean).join(" ").toLowerCase().includes(M)):n},[n,f]),C=w.useMemo(()=>{const M=new Map;return v.forEach(P=>{var L;const D=qft(P),A=Yft(P);M.has(D)||M.set(D,{id:D,label:A,fields:[]}),(L=M.get(D))==null||L.fields.push(P)}),Array.from(M.values())},[v]),S=w.useMemo(()=>C.map(M=>M.id),[C]);w.useEffect(()=>{e&&p(S)},[e,S]),w.useEffect(()=>{if(e){if(f.trim()){p(S);return}p(M=>{const P=M.filter(D=>S.includes(D));return P.length>0?P:S})}},[e,f,S]);const N=M=>{const D=(M.name||M.baseLabel||M.label||M.tokenLabel||"").trim();return D.includes(".")&&D.split(".").pop()||D},j=M=>{const P=`{${M}}`,D=g.current;if(!D){c($=>$+P);return}const A=D.selectionStart||0,L=D.selectionEnd||0;c($=>`${$.slice(0,A)}${P}${$.slice(L)}`),requestAnimationFrame(()=>{D.focus();const $=A+P.length;D.setSelectionRange($,$)})},k=M=>{const P=M.tokenLabel||M.name||M.baseLabel||M.label||"";P.trim()&&j(P.trim())},T=async()=>{const M=await b(a.trim());M&&d(M)},E=()=>{u.trim()&&(s(u.trim()),c(""),d(""),t(!1))},_=()=>{c(""),d(""),h(""),p([]),t(!1)};return l.jsx(zr,{open:e,onOpenChange:M=>{M?t(!0):_()},children:l.jsxs(Tr,{className:"max-w-3xl",children:[l.jsxs(_r,{children:[l.jsx(Ir,{children:"Generate Expression with AI"}),l.jsx(ss,{children:"Describe what you want to calculate and we will draft a SQL expression."})]}),l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"ai-prompt",children:"Describe what you want to calculate"}),l.jsx(yi,{id:"ai-prompt",ref:g,value:a,onChange:M=>c(M.target.value),placeholder:"Create a bucket that categorizes orders as 'Large' when amount is greater than 1000",rows:2})]}),l.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[l.jsx("span",{children:"Be specific about conditions, buckets, or math you want to apply."}),l.jsx(re,{size:"sm",onClick:T,disabled:x||!a.trim(),children:x?"Generating...":u?"Regenerate":"Generate"})]}),y&&l.jsx("p",{className:"text-xs text-destructive whitespace-pre-wrap",children:y})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{children:"Available fields"}),l.jsxs("div",{className:"relative",children:[l.jsx(Ws,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),l.jsx(lt,{value:f,onChange:M=>h(M.target.value),placeholder:"Search fields...",className:"pl-9"})]}),l.jsx("div",{className:"overflow-hidden rounded-lg border border-border",children:l.jsx(za,{className:"h-64",children:C.length===0?l.jsx("div",{className:"py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):l.jsx(zE,{type:"multiple",value:m,onValueChange:p,className:"space-y-1 p-2",children:C.map(M=>l.jsxs(Wp,{value:M.id,className:"border-none",children:[l.jsx(qp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[360px] truncate text-sm font-medium text-primary",children:M.label}),l.jsx(Xe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:M.fields.length})]})}),l.jsx(Yp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:M.fields.map(P=>l.jsxs("button",{type:"button",onClick:()=>k(P),className:"group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all hover:bg-muted",children:[l.jsxs("div",{className:"relative shrink-0",children:[bh(P.dataType),P.isCalculated&&l.jsx("span",{className:Q("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",P.role==="metric"?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-mono text-xs text-foreground/90 group-hover/container:text-foreground",children:N(P)}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:P.tokenLabel})]}),l.jsx(Xe,{variant:"secondary",className:"shrink-0 px-1.5 py-0 text-[11px]",children:P.dataType})]},P.id))})})]},M.id))})})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{children:"Generated expression"}),l.jsx(yi,{value:u,onChange:M=>d(M.target.value),rows:2,className:"font-mono text-sm"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Review and edit the generated expression before using it."})]})]}),l.jsxs(Ds,{className:"gap-2",children:[l.jsx(re,{variant:"ghost",onClick:_,children:"Cancel"}),l.jsx(re,{onClick:E,disabled:!u.trim(),children:"Use Expression"})]})]})})}const Kft=/\{([^}]+)\}/g;function VE(e){return e.trim().toLowerCase()}function sce(e){return Array.from(e.matchAll(Kft)).map(t=>t[1]).filter(Boolean)}function Zft(e){const t=new Set,n=[];return e.forEach(r=>{const s=VE(r);t.has(s)||(t.add(s),n.push(r))}),n}function a4(e){const t=new Map,n=(r,s)=>{const o=VE(r),i=t.get(o)||[];i.some(a=>a.id===s.id)||t.set(o,[...i,s])};return e.forEach(r=>{n(r.tokenLabel,r),r.name&&r.name!==r.tokenLabel&&n(r.name,r),r.baseLabel&&r.baseLabel!==r.tokenLabel&&n(r.baseLabel,r)}),t}function wm(e,t){const n=sce(e),r=Zft(n),s=a4(t),o=r.map(a=>{const c=s.get(VE(a))||[];return c.length===1?c[0]:null}),i=r.filter((a,c)=>!o[c]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function AD(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${Xft(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function Xft(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Qft=e=>e.entityName===Io||e.qualifiedEntityName===Io||e.entityName===uo?"Calculated Fields":e.qualifiedEntityName?Kf(e.entityName||e.qualifiedEntityName):Kf(e.entityName||"Other");function Jft(e){return e.entityName===Io||e.qualifiedEntityName===Io||e.entityName===uo?Io:e.qualifiedEntityName||e.entityName||"Other"}const eht=e=>Sn(e.dataType||"")==="number";function tht(e,t,n){const r=new Set((n||[]).map(s=>rf(s)));return e.filter(s=>{const o=rf(s.id);return o&&r.has(o)?!1:t==="dimension"?s.role!=="metric":!0})}function nht(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==uo?`${r.entityName}.${r.name}`:r.name;const i=o.toLowerCase(),a=n.get(i)||0;a>0&&(o=`${o} ${a+1}`),n.set(i,a+1),t.set(r.id,o)}),t}function rht(e,t,n,r){if(t!=="metric")return e.map(o=>({...o,isCompatible:!0}));if(!n)return e.map(o=>({...o,isCompatible:!0}));const s=n==="COUNT"||n==="DISTINCT";return e.map(o=>{const i=s||eht(o);return{...o,isCompatible:i}}).filter(o=>r)}function sht(e,t){if(!t)return e;const n=t.toLowerCase();return e.filter(r=>r.name.toLowerCase().includes(n)||r.baseLabel.toLowerCase().includes(n)||r.tokenLabel.toLowerCase().includes(n)||r.dataType.toLowerCase().includes(n)||(r.qualifiedEntityName||r.entityName||"").toLowerCase().includes(n))}function oht(e){const t=new Map;return e.forEach(n=>{var s;const r=Jft(n);t.has(r)||t.set(r,{id:r,label:Qft(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function iht({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=w.useMemo(()=>tht(e,t,r),[e,t,r]),a=w.useMemo(()=>nht(i),[i]),c=w.useMemo(()=>i.map(m=>{const p=m.label||m.name,g=m.role==="metric"&&d0(m)||m.role==="groupby"&&W7(m);return{...m,baseLabel:p,tokenLabel:a.get(m.id)||p,isCalculated:g,isCompatible:!0}}),[i,a]),u=w.useMemo(()=>a4(c),[c]),d=w.useMemo(()=>rht(c,t,s,o),[c,t,s,o]),f=w.useMemo(()=>sht(d,n),[d,n]),h=w.useMemo(()=>oht(f),[f]);return{allFields:c,filteredFields:f,groups:h,tokenCandidates:u}}const aht=e=>Sn(e.dataType||"")==="number",vB=e=>aht(e)?"SUM":"COUNT",lht=e=>{if(e.role==="metric"){const n=e;return{...n,aggregate:n.aggregate||vB(e)}}const t=vB(e);return{...e,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`}},cht=(e,t)=>{var r;const n=e.trim();if(n){if(/\bDATE_TRUNC\b/i.test(n))return"date";if(/\bTIMESTAMP\b/i.test(n))return"datetime";if(/\bDATE\b/i.test(n)&&!/\bUPDATE\b/i.test(n))return"date";if(/['"]/.test(n))return"string";if(/[+\-*/]/.test(n))return"number";if(t.length===1){const s=((r=t[0])==null?void 0:r.dataType)||"";if(/date|timestamp/i.test(s))return"date";if(/int|decimal|float|double|num|real/i.test(s))return"number";if(/boolean/i.test(s))return"boolean"}}};function uht({expression:e,availableFields:t,validationEndpoint:n,connectionId:r,dialect:s,fieldType:o,outputType:i,validationContext:a}){const{authToken:c}=rt(),[u,d]=w.useState(null),[f,h]=w.useState(!1),[m,p]=w.useState(null),g=w.useMemo(()=>a4(t),[t]),b=w.useMemo(()=>sce(e).map(S=>{const N=g.get(VE(S))||[];return{token:S,field:N.length===1?N[0]:null}}),[e,g]),x=w.useCallback((C,S)=>{const N=[{code:"SQL_VALIDATION_ERROR",message:C,suggestion:(S==null?void 0:S.suggestion)||(S==null?void 0:S.errorCode)}];return{isValid:!1,tokens:b,errors:N,warnings:[]}},[b]),y=w.useCallback(async()=>{var D;p(null);const C=n==null?void 0:n.trim();if(!C){const A=x("Validation endpoint is not configured");return d(A),A}if(!!!(a!=null&&a.cardConfig&&(a!=null&&a.cardDataSource)&&(a!=null&&a.cardId)&&(a!=null&&a.connectionId||r))){const A=x("Validation context is incomplete for server-side validation");return d(A),A}const{orderedTokens:N,orderedFields:j}=wm(e,t),k=[],T=[];N.forEach((A,L)=>{const $=j[L];$&&(k.push(A),T.push($))});const E=o==="metric"?T.map(lht):T,_=cht(e,T),M=AD(e,k),P={type:"calculated-field-expression",fieldType:o,expression:M,inputFields:E,outputType:i,options:{validateWithExplain:!0},context:{connectionId:(a==null?void 0:a.connectionId)||r,cardId:a==null?void 0:a.cardId,cardConfig:a==null?void 0:a.cardConfig,cardDataSource:a==null?void 0:a.cardDataSource,activeFilters:(a==null?void 0:a.activeFilters)||[],cardType:(a==null?void 0:a.cardType)||"table",dialect:s}};h(!0);try{const A=await Is(C,(c==null?void 0:c.accessToken)||"",P),L=A==null?void 0:A.status,$=A==null?void 0:A.error,B=A==null?void 0:A.errorCode,V=[],R=[];L==="invalid"?V.push({code:"SQL_VALIDATION_ERROR",message:$||"Expression failed SQL validation",suggestion:B?`Validation code: ${B}`:void 0}):L==="unverified"?R.push({code:"EXECUTION_UNVERIFIED",message:$||"Execution could not be fully verified in this environment.",suggestion:"Syntax checks passed. This expression may still run successfully."}):L!=="valid"&&V.push({code:"SQL_VALIDATION_ERROR",message:$||"Unexpected SQL validation response from server",suggestion:B?`Validation code: ${B}`:void 0});const U={isValid:(L==="valid"||L==="unverified")&&V.length===0,tokens:b,errors:V,warnings:R,inferredDataType:(A==null?void 0:A.inferredDataType)??((D=A==null?void 0:A.metadata)==null?void 0:D.inferredDataType)??_??i??void 0};return d(U),U}catch(A){const L=(A==null?void 0:A.error)||(A==null?void 0:A.message)||"Expression validation failed";p(L);const $=x(L);return d($),$}finally{h(!1)}},[n,a,r,e,t,o,i,s,c==null?void 0:c.accessToken,x,b]),v=w.useCallback(()=>{d(null),p(null)},[]);return{validationResult:u,isValidating:f,serverError:m,validateExpression:y,resetValidation:v}}function wB(e,t){const{aggregate:n,...r}=e;return{...r,...t}}function dht({fields:e,normalizedName:t,existingFieldId:n,targetKind:r,targetEntityName:s,targetQualifiedEntityName:o}){return e.some(i=>{if(n&&i.id===n||i.name!==t)return!1;const a=fd(i);if(r==="inline"){const c=wA(i),u=o||s;return a==="inline_expression"&&!!u&&c===u}return a==="domain_calculated"})}const CB=[{value:"string",label:"String"},{value:"number",label:"Number"},{value:"boolean",label:"Boolean"},{value:"date",label:"Date"},{value:"datetime",label:"Datetime"},{value:"json",label:"JSON"},{value:"geo",label:"Geo"}],fht=[],hht="https://docs.semaphor.cloud/docs/concepts/calculated-fields/metrics",mht="https://docs.semaphor.cloud/docs/concepts/calculated-fields/dimensions",pht="SUM({amount} - {discount_amount}) / NULLIF(SUM({quantity}), 0)",ght="CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",JT=e=>{if(!e)return"";const t=e.field.tokenLabel||e.field.label||e.field.name,n=e.aggregate;return n==="DISTINCT"?`COUNT(DISTINCT ${t})`:n==="COUNT"?`COUNT(${t})`:`${n}(${t})`},oce=e=>Sn(e.dataType||"")==="number",Cm=e=>oce(e)?"SUM":"COUNT",e_=(e,t)=>oce(e)||t==="COUNT"||t==="DISTINCT"?t:Cm(e);function t_(e,t){if(e.role==="metric"){const n=e;return d0(n)?n:{...n,aggregate:t}}return{...e,id:`${e.id}_${t.toLowerCase()}`,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`,entityName:e.entityName,entityId:e.entityId,qualifiedEntityName:e.qualifiedEntityName}}function um(e,t){const n=e.role==="metric"&&d0(e);return{field:e,aggregate:n&&e.aggregate||t,isCalculatedField:n}}function ice({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToDashboard:i,cardId:a,initialFieldType:c="metric",allowedFieldTypes:u}){var xe;const{tokenProps:d}=rt(),{selectedConnection:f}=wZ(),h=Ve(he=>{var Le;return(Le=he.card)==null?void 0:Le.config}),m=Ve(he=>{var Le;return(Le=he.card)==null?void 0:Le.dataSource}),p=Ve(he=>{var Le;return(Le=he.card)==null?void 0:Le.type}),b=Ve(he=>he.filterValues)??fht,x=(f==null?void 0:f.dialect)==="bigquery"||(f==null?void 0:f.dialect)==="snowflake",[y,v]=w.useState(c),[C,S]=w.useState(""),[N,j]=w.useState("ratio"),[k,T]=w.useState(null),[E,_]=w.useState(null),[M,P]=w.useState(1),[D,A]=w.useState(""),[L,$]=w.useState(null),[B,V]=w.useState("card"),[R,U]=w.useState({}),[O,I]=w.useState("A"),[W,X]=w.useState(""),[Z,H]=w.useState(!1),[K,z]=w.useState(null),[q,Y]=w.useState(!1),[G,J]=w.useState(!1),ne=w.useRef(null),be=w.useRef(!1),te=w.useRef(null),{userContext:ce}=Lo(),se=w.useMemo(()=>n.filter(he=>he.fieldScope==="domain"&&!!he.expression),[n]),ue=w.useMemo(()=>se.filter(he=>he.role==="metric"),[se]),Re=w.useMemo(()=>se.filter(he=>he.role==="groupby"),[se]),ke=!((ce==null?void 0:ce.type)==="organization"),me=!!i,Me=!!i,Se=(xe=d==null?void 0:d.apiServiceUrl)==null?void 0:xe.replace(/\/$/,""),ie=Se?`${Se}/v1/calculated-fields/validate`:"/v1/calculated-fields/validate",pe=Se?`${Se}/v1/ai/generate`:"/v1/ai/generate",Ne=w.useMemo(()=>{var ut;const he=[...n];return(((ut=r==null?void 0:r.calculatedFormula)==null?void 0:ut.inputFields)||[]).forEach(It=>{he.some(bn=>bn.id===It.id||bn.qualifiedFieldName===It.qualifiedFieldName||bn.name===It.name)||he.push(It)}),he},[n,r]),de=O==="A"?k:E,fe=y==="metric"&&N!=="custom"?de==null?void 0:de.aggregate:void 0,{allFields:Oe,groups:ye}=iht({fields:Ne,mode:y,searchTerm:W,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:fe,showIncompatible:!0}),Ce=Oe,{validationResult:$e,validateExpression:ze,isValidating:Ge,serverError:Ke,resetValidation:Ze}=uht({expression:D,availableFields:Ce,validationEndpoint:ie,connectionId:f==null?void 0:f.id,dialect:f==null?void 0:f.dialect,fieldType:y,outputType:L||void 0,validationContext:{connectionId:(f==null?void 0:f.id)||(m==null?void 0:m.connectionId),cardId:a,cardConfig:h||{},cardDataSource:m||null,activeFilters:b,cardType:p}}),st=$e==null?void 0:$e.inferredDataType,ae=L||st||"string",Pe=Ky.find(he=>he.id===N),Ee=w.useMemo(()=>{if(y==="dimension"){const{orderedFields:he}=wm(D,Ce);return he.filter(Le=>!!Le)}if(N==="custom"){const{orderedFields:he}=wm(D,Ce);return he.filter(Le=>!!Le)}return[k==null?void 0:k.field,E==null?void 0:E.field].filter(he=>!!he)},[Ce,D,y,k==null?void 0:k.field,E==null?void 0:E.field,N]),_e=w.useMemo(()=>o4(Ee),[Ee]),We=w.useMemo(()=>{if(!C.trim())return!1;const he=s4(C);return dht({fields:y==="metric"?ue:Re,normalizedName:he,existingFieldId:s==="domain"?r==null?void 0:r.id:void 0,targetKind:_e.kind==="inline"?"inline":"root",targetEntityName:_e.kind==="inline"?_e.entityName:void 0,targetQualifiedEntityName:_e.kind==="inline"?_e.qualifiedEntityName:void 0})},[_e,Re,ue,r,s,y,C]),Te=w.useMemo(()=>{if(y==="metric"&&N==="custom"){const{orderedFields:Le}=wm(D,Ce);return Le.filter(ut=>!!ut).map(ut=>ut.id)}const he=[];return k!=null&&k.field.id&&he.push(k.field.id),E!=null&&E.field.id&&he.push(E.field.id),he},[Ce,D,y,k,E,N]),Ue=he=>{ke||v(he)},et=he=>{ke||(j(he),he==="scale"&&_(null),he==="custom"&&(T(null),_(null)))},bt=()=>{S(""),j("ratio"),T(null),_(null),P(1),A(""),$(null),V("card"),U({}),X(""),H(!1),z(null),Y(!1),Ze(),t(!1)},dt=w.useCallback(he=>Ne.find(Le=>Le.qualifiedFieldName===he.qualifiedFieldName||Le.name===he.name)||he,[Ne]),St=w.useCallback(he=>{if(!he.calculatedFormula)return;const Le=he.calculatedFormula;if(j(Le.operation),A(""),Le.operation==="scale"){const zt=Le.inputFields[0];zt&&T(um(dt(zt),zt.aggregate||"SUM")),P(Le.constant===void 0?1:Le.constant);return}if(Le.operation==="custom"){A(Ot(he.expression||"",Le.inputFields||[])),T(null),_(null);return}const[ut,It]=Le.inputFields;ut&&T(um(dt(ut),ut.aggregate||"SUM")),It&&_(um(dt(It),It.aggregate||"SUM"))},[dt]),Ot=w.useCallback((he,Le)=>he.replace(/\{field_(\d+)\}/g,(ut,It)=>{var cr;const zt=Le[Number(It)];return zt?`{${((cr=Ce.find(bo=>bo.id===zt.id))==null?void 0:cr.tokenLabel)||zt.label||zt.name}}`:ut}),[Ce]);w.useEffect(()=>{var ut;if(!e){be.current=!1,te.current=null;return}const he=r?`${r.role}-${r.id||r.name}`:"new";if(be.current&&te.current===he)return;if(be.current=!0,te.current=he,U({}),X(""),Ze(),r){if(r.role==="metric"){v("metric"),S(r.label||r.name),V(s||"card"),St(r);return}v("dimension");const It=r;S(It.label||It.name),V(s||"card"),A(Ot(It.expression||"",((ut=It.calculatedFormula)==null?void 0:ut.inputFields)||[]));const zt=CB.some(bn=>bn.value===It.dataType)?It.dataType:"string";$(zt);return}const Le=u&&u.length>0?u.includes(c)?c:u[0]:c;v(Le),S(""),j("ratio"),T(null),_(null),P(1),A(""),$(null),V("card")},[e,r,s,c,u,St,Ot,Ze]);const xt=he=>{const Le=`{${he}}`,ut=ne.current;if(!ut){A(cr=>cr+Le);return}const It=ut.selectionStart||0,zt=ut.selectionEnd||0,bn=`${D.slice(0,It)}${Le}${D.slice(zt)}`;A(bn),requestAnimationFrame(()=>{ut.focus();const cr=It+Le.length;ut.setSelectionRange(cr,cr)})},an=he=>{if(ke)return;if(y==="dimension"||N==="custom"){xt(he.tokenLabel||he.label||he.name);return}const Le=e_(he,O==="A"?(k==null?void 0:k.aggregate)||Cm(he):(E==null?void 0:E.aggregate)||Cm(he)),ut=um(he,Le);if(O==="A"){T(ut),E||I("B");return}_(ut),k||I("A")},Tt=(he,Le)=>{if(!ke){if(he==="A"&&k){T({...k,aggregate:Le});return}he==="B"&&E&&_({...E,aggregate:Le})}},ve=async()=>{const he={};if(C.trim()||(he.name="Name is required"),N==="custom")D.trim()||(he.expression="Expression is required"),he.expression||(await ze()).isValid||(he.expression="Fix validation errors before saving");else if(N==="scale")k||(he.inputA="Please select a metric for input A"),Number.isNaN(M)&&(he.constant="Please enter a valid multiplication factor");else{if(k||(he.inputA="Please select a metric for input A"),E||(he.inputB="Please select a metric for input B"),k&&E){const Le=k.field.id===E.field.id,ut=k.aggregate===E.aggregate;Le&&ut&&(he.inputs="Inputs A and B must be different metrics")}if(r&&r.role==="metric"){const Le=rf(r.id);(rf(k==null?void 0:k.field.id)===Le||rf(E==null?void 0:E.field.id)===Le)&&(he.inputs="Cannot reference the field being edited")}}return U(he),Object.keys(he).length===0},nt=async()=>{const he={};return C.trim()||(he.name="Name is required"),D.trim()||(he.expression="Expression is required"),he.expression||(await ze()).isValid||(he.expression="Fix validation errors before saving"),U(he),Object.keys(he).length===0},ct=()=>{const{orderedTokens:he,orderedFields:Le}=wm(D,Ce),ut=Le.filter(bn=>!!bn),It=AD(D,he),zt=Fft(C,It,ut,ae,a,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...zt}:zt},pn=()=>{var It;if(N==="custom"){const{orderedTokens:zt,orderedFields:bn}=wm(D,Ce),cr=bn.filter(vt=>!!vt),bo=(r==null?void 0:r.role)==="metric"?((It=r.calculatedFormula)==null?void 0:It.inputFields)||[]:[],Fe=new Map;bo.forEach(vt=>{const Kn=rf(vt.id);Kn&&Fe.set(Kn,vt),vt.qualifiedFieldName&&Fe.set(vt.qualifiedFieldName,vt),vt.name&&Fe.set(vt.name,vt)});const Nt=cr.map(vt=>{const Kn=rf(vt.id),tr=Kn&&Fe.get(Kn)||vt.qualifiedFieldName&&Fe.get(vt.qualifiedFieldName)||Fe.get(vt.name),nr=((tr==null?void 0:tr.role)==="metric"?tr.aggregate:void 0)||(vt.role==="metric"?vt.aggregate:void 0)||Cm(vt);return t_(vt,nr)}),En=AD(D,zt),tn=gB(C,N,null,null,{},a,r==null?void 0:r.id,En,void 0,Nt);return r&&r.role==="metric"?wB(r,tn):tn}const he=k?t_(k.field,k.aggregate):null,Le=E?t_(E.field,E.aggregate):null,ut=gB(C,N,he,Le,{},a,r==null?void 0:r.id,void 0,N==="scale"?M:void 0);return r&&r.role==="metric"?wB(r,ut):ut},Qr=async he=>{if(he==="domain"){U(ut=>({...ut,scope:"Domain scope is not available in this explorer."}));return}if(y==="dimension"){const ut=ct();if(he==="dashboard"){if(!i){U(It=>({...It,scope:"Shared sheet scope is not available"}));return}await i(ut),bt();return}await o(ut),bt();return}const Le=pn();if(he==="dashboard"){if(!i){U(ut=>({...ut,scope:"Shared sheet scope is not available"}));return}await i(Le),bt();return}await o(Le),bt()},Nr=async()=>{if(ke)return;if(U({}),y==="metric"){if(!await ve())return}else if(!await nt())return;const he=me?B:s||"card";if(y==="metric"&&he!=="domain"&&We&&!r){z(he),Y(!0);return}J(!0);try{await Qr(he)}finally{J(!1)}},Jr=w.useMemo(()=>{if(!Pe||N==="custom")return"";if(N==="scale"){const he=Number.isFinite(M)?M:1;return`${JT(k)} x ${he}`}return`${JT(k)||"A"} ${Pe.symbol} ${JT(E)||"B"}`},[Pe,N,k,E,M]),ei=w.useMemo(()=>_e.kind==="inline"?"Inline":"Multi-Entity",[_e]),go=y==="metric"?hht:mht,Ha=y==="metric"?pht:ght,nu=y==="metric"?"Calculated Metric":"Calculated Dimension",yt=y==="metric"?"border-emerald-600/30 bg-emerald-500/10 text-emerald-700":"border-sky-600/30 bg-sky-500/10 text-sky-700";return l.jsxs(l.Fragment,{children:[l.jsxs(zr,{modal:!1,open:e,onOpenChange:he=>{he?t(!0):bt()},children:[e&&l.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),l.jsxs(Tr,{className:"max-w-5xl max-h-[90vh] overflow-hidden",onInteractOutside:he=>{he.preventDefault()},children:[l.jsxs(_r,{children:[l.jsxs(Ir,{className:"flex items-center gap-2",children:[l.jsxs("span",{children:[r?"Edit":"Create"," Calculated Field"]}),l.jsx(Xe,{variant:"outline",className:yt,children:nu}),l.jsx(Xe,{variant:"secondary",children:ei})]}),l.jsx(ss,{children:"Build calculated metrics and dimensions using expressions."})]}),l.jsxs("div",{className:"grid h-[70vh] min-h-0 grid-cols-[280px_1fr] gap-6",children:[l.jsx(Oft,{groups:ye,searchTerm:W,onSearchTermChange:X,onFieldClick:an,selectedFieldIds:Te,disabled:ke}),l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 overflow-y-auto pr-2 pb-6",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(ge,{children:"Field Type"}),l.jsx(Pft,{value:y,onChange:Ue,disabled:ke||!!r,options:u||["metric","dimension"]})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(ge,{htmlFor:"calculated-name",children:"Name"}),l.jsx(lt,{id:"calculated-name",value:C,onChange:he=>S(he.target.value),placeholder:y==="metric"?"e.g., Profit Margin":"e.g., Sales Tier",className:R.name?"border-destructive":"",disabled:ke}),R.name&&l.jsx("p",{className:"text-xs text-destructive",children:R.name})]}),me&&Me&&l.jsx("div",{className:"space-y-3",children:l.jsx(Uft,{scope:B,onChange:V,showDashboardScope:Me,error:R.scope,disabled:ke})}),y==="metric"&&l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(ge,{children:"Operation"}),l.jsx(Lft,{value:N,onChange:et,allowCustom:!0,disabled:ke}),R.operation&&l.jsx("p",{className:"text-xs text-destructive",children:R.operation})]}),N==="custom"?l.jsxs("div",{className:"space-y-3",children:[l.jsx(xB,{ref:ne,value:D,onChange:he=>{A(he)},onGenerate:()=>H(!0),showGenerate:!!pe&&!ke,docsUrl:go,placeholder:Ha,disabled:ke}),l.jsx(yB,{onValidate:ze,isValidating:Ge,validationResult:$e,error:Ke,disabled:ke}),R.expression&&l.jsx("p",{className:"text-xs text-destructive",children:R.expression})]}):l.jsxs("div",{className:"space-y-3",children:[l.jsx(ge,{children:"Inputs"}),l.jsx(bB,{label:"A",input:k,availableFields:Ce,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:he=>{const Le=e_(he,(k==null?void 0:k.aggregate)||Cm(he));T(um(he,Le))},onAggregateChange:he=>Tt("A",he),onRemove:()=>T(null),onActivate:()=>I("A"),allowMedian:x,disabled:ke}),R.inputA&&l.jsx("p",{className:"text-xs text-destructive",children:R.inputA}),N!=="scale"&&l.jsxs(l.Fragment,{children:[l.jsx(bB,{label:"B",input:E,availableFields:Ce,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:he=>{const Le=e_(he,(E==null?void 0:E.aggregate)||Cm(he));_(um(he,Le))},onAggregateChange:he=>Tt("B",he),onRemove:()=>_(null),onActivate:()=>I("B"),allowMedian:x,disabled:ke}),R.inputB&&l.jsx("p",{className:"text-xs text-destructive",children:R.inputB})]}),N==="scale"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(ge,{htmlFor:"constantFactor",children:"Multiplication Factor"}),l.jsx(lt,{id:"constantFactor",type:"number",step:"any",value:Number.isNaN(M)?"":M,onChange:he=>P(he.target.value===""?Number.NaN:Number(he.target.value)),className:R.constant?"border-destructive":"",placeholder:"e.g., 0.15",disabled:ke}),R.constant&&l.jsx("p",{className:"text-xs text-destructive",children:R.constant})]}),l.jsx("div",{className:"rounded-md border bg-muted/40 p-3 font-mono text-sm",children:Jr||"Select inputs to preview formula"}),R.inputs&&l.jsxs(Lj,{variant:"destructive",children:[l.jsx($c,{className:"h-4 w-4"}),l.jsx($j,{children:R.inputs})]})]})]}),y==="dimension"&&l.jsxs("div",{className:"space-y-3",children:[l.jsx(xB,{ref:ne,value:D,onChange:he=>{A(he)},onGenerate:()=>H(!0),showGenerate:!!pe&&!ke,docsUrl:go,placeholder:Ha,disabled:ke}),l.jsx(yB,{onValidate:ze,isValidating:Ge,validationResult:$e,error:Ke,disabled:ke}),R.expression&&l.jsx("p",{className:"text-xs text-destructive",children:R.expression}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(ge,{children:"Output Type"}),l.jsxs(pt,{value:ae,onValueChange:he=>$(he),disabled:ke,children:[l.jsx(ft,{children:l.jsx(gt,{placeholder:"Select output type"})}),l.jsx(ht,{children:CB.map(he=>l.jsx(Ie,{value:he.value,children:he.label},he.value))})]}),st&&!L&&l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Suggested type: ",st]})]})]})]})]}),l.jsxs(Ds,{children:[l.jsx(re,{variant:"outline",onClick:bt,disabled:G,children:"Cancel"}),l.jsx(re,{onClick:()=>void Nr(),disabled:G||Ge||ke,children:G?l.jsxs(l.Fragment,{children:[l.jsx(Mn,{className:"mr-2 h-4 w-4 animate-spin"}),r?"Updating":"Saving"," ",y==="metric"?"Metric":"Dimension","..."]}):l.jsxs(l.Fragment,{children:[r?"Update":"Save"," ",y==="metric"?"Metric":"Dimension"]})})]})]})]}),l.jsx(Gft,{open:Z,onOpenChange:H,availableFields:Ce,fieldType:y,onExpressionGenerated:async he=>{A(he),Ze()},endpoint:pe,dialect:f==null?void 0:f.dialect}),l.jsx(qc,{open:q,onOpenChange:Y,children:l.jsxs(Pl,{children:[l.jsxs(Ol,{children:[l.jsx($l,{children:"Name Conflict"}),l.jsxs(zl,{children:['A domain metric named "',C.trim(),'" already exists. Your local version will override it in this'," ",K==="dashboard"?"dashboard":"card",". Continue?"]})]}),l.jsxs(Ll,{children:[l.jsx(Bl,{onClick:()=>{z(null)},children:"Choose Different Name"}),l.jsx(Vl,{onClick:async()=>{if(K){Y(!1),J(!0);try{await Qr(K)}finally{J(!1),z(null)}}},children:"Continue"})]})]})})]})}function bht(e,t){const n=e.fieldScope==="dashboard";if(e.role==="metric"){const r=t.metricFields.find(s=>Lu(s,e,{allowComparableFallback:n}));if(r)return r}if(e.role==="groupby"){const r=t.groupByFields.find(s=>Lu(s,e,{allowComparableFallback:n}));if(r)return r}return t.storedCalculatedFields.find(r=>Lu(r,e,{allowComparableFallback:n}))}function xht(e,t){const n={...e,fieldScope:"domain"};return t.find(r=>r.fieldScope==="domain"&&Lu(r,n))}function ace(e,t){var n,r,s,o;if(e.role==="metric"&&t.role==="metric"){const i=e,a=t;return{...a,parameters:i.parameters||a.parameters?{filters:((n=i.parameters)==null?void 0:n.filters)??((r=a.parameters)==null?void 0:r.filters),windowTransform:((s=i.parameters)==null?void 0:s.windowTransform)??((o=a.parameters)==null?void 0:o.windowTransform)}:void 0,aliasTemplate:i.aliasTemplate??a.aliasTemplate,valueAliases:i.valueAliases??a.valueAliases,customFormat:i.customFormat??a.customFormat,comparisonType:i.comparisonType??a.comparisonType,comparisonDisplay:i.comparisonDisplay??a.comparisonDisplay,targetValue:i.targetValue??a.targetValue}}if(e.role==="groupby"&&t.role==="groupby"){const i=e,a=t;return{...a,granularity:i.granularity??a.granularity,dateFormat:i.dateFormat??a.dateFormat,customFormat:i.customFormat??a.customFormat,timeDrillPath:i.timeDrillPath??a.timeDrillPath}}return t}function lce(e,t,n,r){if(!n)return null;const o=Y7(e,n||t,r);if(n&&o<0)return null;if(o>=0){const i=e[o],a=i==null?void 0:i.id,c=r!=null&&r.mergeMatchedField?r.mergeMatchedField(i,t):t,d=a&&a!==c.id&&!((i==null?void 0:i.fieldScope)==="domain"&&c.fieldScope==="domain")?{...c,id:a}:c;return e.map((f,h)=>h===o?d:f)}return null}function cce(e,t){return{...e,fieldScope:t}}function RD(e){const t=cce(e.updatedField,"card"),n=lce(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="dashboard",mergeMatchedField:ace}),r=K7(e.storedFields,t,e.editingField,{allowComparableFallback:e.previousScope==="dashboard"}),s=e.previousScope==="dashboard"&&e.editingField?Nm(e.sharedFields,e.editingField,{allowComparableFallback:!0}):e.sharedFields;return{nextActiveFields:n,nextStoredFields:r,nextSharedFields:s}}function FD(e){const t=cce(e.updatedField,"dashboard"),n=lce(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="dashboard",mergeMatchedField:ace}),r=K7(e.sharedFields,t,e.editingField,{allowComparableFallback:!0}),s=e.previousScope==="card"&&e.editingField?Nm(e.storedFields,e.editingField,{allowComparableFallback:!0}):e.storedFields;return{nextActiveFields:n,nextStoredFields:s,nextSharedFields:r}}function Sm(e){const{nextSharedFields:t,currentSharedFields:n,isVisualEditing:r,selectedSheetId:s,updateFrame:o,updateSheetCalculatedFields:i,currentFrame:a,nextFramePatch:c,persistFrame:u,persistFrames:d}=e,f=c?{...c,calculatedFields:t}:{calculatedFields:t};(t!==n||c)&&o(f),s&&(r||(u&&(d!=null&&d.length)?d.forEach(h=>{u(s,{...h,calculatedFields:void 0})}):u&&a&&c&&u(s,{...a,...c,calculatedFields:void 0}),i&&i(s,t)))}const uce=w.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var Ot,xt,an,Tt;const[s,o]=w.useState(""),[i,a]=w.useState("all"),[c,u]=w.useState(!1),[d,f]=w.useState(null),[h,m]=w.useState("card"),[p,g]=w.useState("metric"),[b,x]=w.useState(null),[y,v]=w.useState(!1);Ve(ve=>ve.isDevMode);const C=Ve(ve=>ve.card.dataSource),S=Ve(ve=>ve.card.config),N=Ve(ve=>ve.card),j=Ve(ve=>ve.frame),k=Ve(ve=>ve.actions.updateCardConfig),T=Ve(ve=>ve.actions.updateCard),E=Ve(ve=>ve.actions.updateFrame),_=ee(ve=>ve.isVisualEditing),M=ee(ve=>ve.selectedSheetId),P=ee(ve=>ve.actions.updateSheetCalculatedFields),{userContext:D}=Lo(),{autoJoinMetadata:A}=kl(N),{rawColumnGroups:L,scopedFields:$,dashboardFilterableFields:B,inlineFilterableFields:V,scopedCalculatedFields:R,sharedCalculatedFields:U,inlineCalculatedFields:O,isLoading:I,error:W}=Tle(),X=(C==null?void 0:C.mode)==="semanticDomain"?C.semanticDomainId:void 0,{data:Z}=Q5(X),H=w.useMemo(()=>[...(S==null?void 0:S.groupByColumns)||[],...(S==null?void 0:S.metricColumns)||[],...(S==null?void 0:S.detailColumns)||[]],[S==null?void 0:S.groupByColumns,S==null?void 0:S.metricColumns,S==null?void 0:S.detailColumns]);(xt=(Ot=S==null?void 0:S.joinPlan)==null?void 0:Ot.baseEntity)==null||xt.name,(Tt=(an=A==null?void 0:A.resolvedJoinPlan)==null?void 0:an.baseEntity)==null||Tt.name,Fle();const K=t==="editor"?R:t==="filter"?U:O,z=K.length>0,q=(D==null?void 0:D.type)==="organization",Y=t==="editor"?$:t==="filter"?B:V,G=L,J=s.toLowerCase(),ne=(S==null?void 0:S.metricColumns)||[],be=(S==null?void 0:S.groupByColumns)||[],te=N.calculatedFields||[],ce=ve=>ve.name.toLowerCase().includes(J)||ve.dataType.toLowerCase().includes(J)||ve.label&&ve.label.toLowerCase().includes(J)||ve.qualifiedEntityName&&ve.qualifiedEntityName.toLowerCase().includes(J),se=w.useCallback(ve=>(ve.label||ve.name).toLowerCase().trim(),[]),ue=w.useCallback((ve,nt)=>se(ve).localeCompare(se(nt),void 0,{numeric:!0,sensitivity:"base"}),[se]),Re=Y.filter(ce).sort(ue),je=w.useCallback(ve=>t==="editor"?Qg(ve):va(ve),[t]),ke=ve=>{if(je(ve))return"calculated";if(ve.dataType==="number"||ve.dataType==="integer"||ve.dataType==="float"||ve.dataType==="decimal"||ve.dataType==="currency")return"metrics";const nt=Sn(ve.dataType);return["date","string","boolean"].includes(nt)?"dimensions":nt==="number"?"metrics":"dimensions"},me=ve=>{const nt=ve.filter(ce);return i==="all"?nt:nt.filter(ct=>ke(ct)===i)},Me=i==="all"?Re:Re.filter(ve=>ke(ve)===i),Se=z?me(K).sort(ue):[],ie=Y.filter(ve=>ke(ve)!=="calculated"),Ne=me(ie).sort(ue).reduce((ve,nt)=>{const ct=nt.qualifiedEntityName||"Other Fields";return ve[ct]||(ve[ct]={label:Kf(nt.entityName),fields:[]}),ve[ct].fields.push(nt),ve},{}),de=w.useMemo(()=>Object.entries(Ne).map(([ve,nt])=>{const ct=G.find(Qr=>Qr.entityName===ve)||{entityName:ve,label:nt.label},pn=ve===Io?"Domain Calculated Fields":ct.label||ct.entityName;return{groupName:ve,groupLabel:pn,fields:[...nt.fields].sort(ue)}}).sort((ve,nt)=>ve.groupLabel.localeCompare(nt.groupLabel,void 0,{numeric:!0,sensitivity:"base"})),[Ne,G,ue]),fe=ve=>ve.id||`${ve.entityName}-${ve.qualifiedEntityName}-${ve.name}-${ve.role||"field"}`,Oe=w.useMemo(()=>{const ve=new Map;return Y.forEach(ct=>{ve.set(fe(ct),kF(ct,{joinabilityMap:(Z==null?void 0:Z.joinabilityMap)||null,selectedFields:H,cardConfig:S,autoJoinMetadata:A}))}),ve},[Y,Z==null?void 0:Z.joinabilityMap,H,S,A]),ye=z?[{key:"scope-calculated",label:"Calculated Fields",fields:Se}].filter(ve=>ve.fields.length>0):[],$e=[...ye.map(ve=>ve.key),...de.map(ve=>ve.groupName)],ze=Re.filter(ve=>ke(ve)==="dimensions").length,Ge=Re.filter(ve=>ke(ve)==="metrics").length,Ke=Re.filter(ve=>ke(ve)==="calculated").length,Ze=Re.length>0&&t!=="inline-filter",st=t==="inline-filter"?"w-full":"w-[290px]";if(I)return l.jsx("div",{className:Q("flex h-full flex-col items-center justify-center py-8",st),children:l.jsx(ad,{size:"md",color:"muted","aria-label":"Loading data"})});if(W)return l.jsxs("div",{className:Q("flex h-full flex-col items-center justify-center py-8",st),children:[l.jsx(pl,{className:"mb-4 h-12 w-12 text-red-300"}),l.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),l.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:W.message||"Failed to load column data"})]});if(!C||!C.selectedEntities||C.selectedEntities.length===0)return l.jsxs("div",{className:Q("flex flex-col items-center justify-center py-8 text-center",st),children:[l.jsx(pl,{className:"mb-4 h-12 w-12 text-gray-300"}),l.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),l.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"||t==="inline-filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]});const ae=t==="inline-filter"?"px-3 pb-3":"px-3 pb-6",Pe=t==="inline-filter"?"overflow-hidden":"",Ee=ve=>bht(ve,{storedCalculatedFields:te,metricFields:ne,groupByFields:be}),_e=ve=>{T(N.id,{calculatedFields:Nm(te,ve,{allowComparableFallback:ve.fieldScope==="dashboard"})})},We=ve=>{var nt;return(nt=j==null?void 0:j.calculatedFields)==null?void 0:nt.find(ct=>Lu(ct,ve))},Te=ve=>{if(ve.role==="metric"){k(N.id,{metricColumns:Nm(ne,ve,{allowComparableFallback:ve.fieldScope==="dashboard"})});return}ve.role==="groupby"&&k(N.id,{groupByColumns:Nm(be,ve,{allowComparableFallback:ve.fieldScope==="dashboard"})})},Ue=ve=>{if(!j)return;const nt=Nm(j.calculatedFields||[],ve);Sm({nextSharedFields:nt,currentSharedFields:j.calculatedFields||[],isVisualEditing:_,selectedSheetId:M,updateFrame:E,updateSheetCalculatedFields:P})},et=ve=>{if(!q)return;if(ve.fieldScope==="domain"){qe.error("Domain calculated fields are read-only in this explorer.");return}if(ve.fieldScope==="dashboard"){const ct=We(ve);if(!ct)return;f(ct),m("dashboard"),g(ct.role==="metric"?"metric":"dimension"),u(!0);return}const nt=Ee(ve);nt&&(f(nt),m("card"),g(nt.role==="metric"?"metric":"dimension"),u(!0))},bt=async ve=>{if(q){if(ve.fieldScope==="domain"){qe.error("Domain calculated fields are read-only in this explorer.");return}if(ve.fieldScope==="dashboard"){Ue(ve),Te(ve);return}Te(ve),_e(ve)}},dt=async()=>{if(b){v(!0);try{await bt(b),x(null)}catch{}finally{v(!1)}}},St=ve=>{if(!q)return null;const nt=ve.fieldScope==="domain",ct=nt;return l.jsxs(pd,{children:[l.jsx(gd,{asChild:!0,children:l.jsx(re,{variant:"ghost",size:"icon",className:"h-6 w-6 rounded-full","aria-label":"Calculated field actions",children:l.jsx(_h,{className:"h-3.5 w-3.5"})})}),l.jsxs(Hc,{align:"end",className:"w-36",children:[nt?l.jsx(zs,{disabled:!0,children:"Read Only In Explorer"}):l.jsx(zs,{onClick:()=>et(ve),children:"Edit"}),l.jsx(zs,{className:"text-destructive focus:text-destructive",disabled:ct,onClick:()=>x(ve),children:"Delete"})]})]})};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:Q("mt-2 flex h-full w-full grow flex-col gap-2",ae,Pe),children:[l.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[Y.length>0&&l.jsxs("div",{className:"relative",children:[l.jsx(Ws,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx(lt,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:s,onChange:ve=>o(ve.target.value)}),s&&l.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>o(""),type:"button",children:l.jsx(Mt,{className:"size-3.5"})})]}),Ze&&l.jsx(As,{defaultValue:"all",value:i,onValueChange:ve=>a(ve),className:"mb-4",children:l.jsxs(ys,{className:"grid h-11 w-full grid-cols-4 rounded-lg border border-border/60 bg-muted/50 p-1",children:[l.jsxs(on,{value:"all",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:["All",l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Re.length})]}),l.jsxs(on,{value:"dimensions",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(bN,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:ze})]}),l.jsxs(on,{value:"metrics",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(fN,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Ge})]}),l.jsxs(on,{value:"calculated",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(AA,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Ke})]})]})}),t==="editor"&&i==="calculated"&&q&&l.jsx("div",{className:"flex items-center justify-end gap-2",children:l.jsxs(re,{size:"sm",variant:"outline",className:"w-full",onClick:()=>{f(null),m("card"),g("dimension"),u(!0)},children:[l.jsx($r,{className:"mr-2 h-3.5 w-3.5"}),"Add calculated field"]})})]}),l.jsxs(za,{className:"min-h-0 flex-1",children:[l.jsxs(zE,{type:"multiple",defaultValue:$e,className:"space-y-2",children:[ye.map(ve=>l.jsxs(Wp,{value:ve.key,className:"border-none",children:[l.jsx(qp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:ve.label}),l.jsx(Xe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:ve.fields.length})]})}),l.jsx(Yp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:ve.fields.map(nt=>{const ct=Oe.get(fe(nt)),pn=t==="editor"&&q&&va(nt);return l.jsx(mB,{field:nt,context:t,fieldState:ct,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:pn?St(nt):void 0},nt.id)})})})]},ve.key)),de.map(({groupName:ve,groupLabel:nt,fields:ct})=>l.jsxs(Wp,{value:ve,className:"border-none",children:[l.jsx(qp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{title:nt,className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:nt}),l.jsx(Xe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:ct.length})]})}),l.jsx(Yp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:ct.map(pn=>{const Qr=Oe.get(fe(pn)),Nr=t==="editor"&&q&&va(pn);return l.jsx(mB,{field:pn,context:t,fieldState:Qr,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:Nr?St(pn):void 0},pn.id)})})})]},ve))]}),Y.length===0&&l.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[l.jsx("p",{children:"No fields found for selected data source"}),l.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Y.length>0&&Me.length===0&&l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),l.jsx(Da,{orientation:"horizontal"}),l.jsx(Da,{orientation:"vertical"})]})]}),l.jsx(qc,{open:!!b,onOpenChange:ve=>{ve||x(null)},children:l.jsxs(Pl,{children:[l.jsxs(Ol,{children:[l.jsx($l,{children:"Delete calculated field?"}),l.jsxs(zl,{children:["This will remove"," ",l.jsx("span",{className:"font-medium text-foreground",children:(b==null?void 0:b.label)||(b==null?void 0:b.name)||"this calculated field"})," ",(b==null?void 0:b.fieldScope)==="domain"?"from the semantic domain.":"from this configuration."]})]}),l.jsxs(Ll,{children:[l.jsx(Bl,{disabled:y,children:"Cancel"}),l.jsx(Vl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,onClick:ve=>{ve.preventDefault(),dt()},children:y?"Deleting...":"Delete"})]})]})}),l.jsx(ice,{open:c,onOpenChange:ve=>{u(ve),ve||(f(null),m("card"))},availableFields:$,existingField:d??void 0,existingFieldScope:h,initialFieldType:p,onSave:ve=>{const nt=d,ct=(j==null?void 0:j.calculatedFields)||[];if(ve.role==="metric"){const{nextActiveFields:Jr,nextStoredFields:ei,nextSharedFields:go}=RD({activeFields:ne,storedFields:te,sharedFields:ct,updatedField:ve,editingField:nt,previousScope:h});Jr&&k(N.id,{metricColumns:Jr}),T(N.id,{calculatedFields:ei}),j&&go!==ct&&Sm({nextSharedFields:go,currentSharedFields:ct,isVisualEditing:_,selectedSheetId:M,updateFrame:E,updateSheetCalculatedFields:P});return}const{nextActiveFields:pn,nextStoredFields:Qr,nextSharedFields:Nr}=RD({activeFields:be,storedFields:te,sharedFields:ct,updatedField:ve,editingField:nt,previousScope:h});pn&&k(N.id,{groupByColumns:pn}),T(N.id,{calculatedFields:Qr}),j&&Nr!==ct&&Sm({nextSharedFields:Nr,currentSharedFields:ct,isVisualEditing:_,selectedSheetId:M,updateFrame:E,updateSheetCalculatedFields:P})},onSaveToDashboard:ve=>{const nt=d,ct=(j==null?void 0:j.calculatedFields)||[];if(ve.role==="metric"){const{nextActiveFields:Jr,nextStoredFields:ei,nextSharedFields:go}=FD({activeFields:ne,storedFields:te,sharedFields:ct,updatedField:ve,editingField:nt,previousScope:h});j&&Sm({nextSharedFields:go,currentSharedFields:ct,isVisualEditing:_,selectedSheetId:M,updateFrame:E,updateSheetCalculatedFields:P}),Jr&&k(N.id,{metricColumns:Jr}),T(N.id,{calculatedFields:ei});return}const{nextActiveFields:pn,nextStoredFields:Qr,nextSharedFields:Nr}=FD({activeFields:be,storedFields:te,sharedFields:ct,updatedField:ve,editingField:nt,previousScope:h});j&&Sm({nextSharedFields:Nr,currentSharedFields:ct,isVisualEditing:_,selectedSheetId:M,updateFrame:E,updateSheetCalculatedFields:P}),pn&&k(N.id,{groupByColumns:pn}),T(N.id,{calculatedFields:Qr})},cardId:N.id})]})}),dce=w.memo(function({context:t="editor"}={}){return l.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",l.jsx(uce,{context:t})," "]})});function fce(){const e=Ve(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=lr();w.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:c,connectionId:u}=e4(e),d=(m=e.selectedEntities)==null?void 0:m[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(c||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function yht(){fce();const e=ee(c=>c.selectedSheetId),t=ee(c=>c.selectedFrameId),n=ee(c=>c.dashboard),r=ee(c=>c.actions.getSelectedFrame),{setSelectedFrameId:s}=en(),{setCard:o}=lr(),i=Ve(c=>c.card.dataSource);return w.useEffect(()=>{var u,d;let c=r();if(!c){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(m=>m.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),c=h)}if(c){const f=c.cards.find(h=>h.id===c.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function vht(){const e=ee(o=>o.dashboard.filterLayout),{setFilterLayout:t}=en(),n=(e==null?void 0:e.displayMode)||"canvas",r=(e==null?void 0:e.toolbarWrap)??!1,s=(e==null?void 0:e.showDownloadButton)??!1;return l.jsxs(Gr,{children:[l.jsx(Kr,{asChild:!0,children:l.jsx(re,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:l.jsx(gl,{className:"h-4 w-4"})})}),l.jsx(Zr,{className:"w-[280px]",align:"end",children:l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"mb-3 text-sm font-medium",children:"Filter Display"}),l.jsxs(Do,{value:n,onValueChange:o=>t({displayMode:o}),className:"space-y-2",children:[l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx($n,{value:"canvas",id:"canvas",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(ge,{htmlFor:"canvas",className:"cursor-pointer font-normal",children:"Canvas Cards"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters as draggable, resizable cards on the dashboard"})]})]}),l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx($n,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(ge,{htmlFor:"toolbar",className:"cursor-pointer font-normal",children:"Toolbar"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Compact horizontal toolbar below dashboard controls"})]})]})]})]}),n==="toolbar"&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-center space-x-2 border-t pt-4",children:[l.jsx(Jt,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),l.jsx(ge,{htmlFor:"wrap",className:"cursor-pointer text-sm font-normal",children:"Wrap filters to multiple lines"})]}),l.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[l.jsx(Jt,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),l.jsx(ge,{htmlFor:"download",className:"cursor-pointer text-sm font-normal",children:"Show download button"})]})]}),l.jsx("p",{className:"border-t pt-3 text-xs text-muted-foreground",children:"Individual filters can override this setting in their configuration."})]})})]})}function wht(){const e=ee(n=>n.actions.setShowFilters),{hasEntities:t}=yht();return l.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[l.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[l.jsx(ge,{className:"px-2 text-base",children:"Dashboard Filters"}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(vht,{}),l.jsx(re,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:l.jsx(sse,{})})]})]}),!t&&l.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[l.jsx(pl,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),l.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&l.jsx("div",{className:"flex grow overflow-y-auto",children:l.jsx(vv,{collisionDetection:bv,children:l.jsx(wv,{items:[],strategy:r5,children:l.jsx(dce,{context:"filter"})})})})]})}function Cht(){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?l.jsx("div",{className:Q("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(ZO,{filter:r}),l.jsx(Vg,{filter:r})]},r.id))}):null}function Sht(){const e=ee(r=>r.showFilters),t=ee(r=>r.isVisualEditing),n=ee(r=>r.isDashboardEditing);return l.jsxs("div",{role:"dashboard-plus-main",className:Q("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[l.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&l.jsx(Cht,{}),l.jsx(vle,{})]}),e&&l.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:l.jsx(wht,{})})]})}const Nht=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-Cm_n6Dce.js"))),jht=w.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-DEuJScSB.js"))),Eht=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json--iZU90D2.js"))),kht=w.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-DMHJbuqI.js")).then(e=>({default:e.ResourceManagementPanel})));function Tht({showControls:e=!1,showFooter:t=!0,...n}){const r=ee(c=>c.isDashboardPanelOpen),s=ee(c=>c.isVisualEditing),o=ee(c=>c.showDashboardJSON),i=ee(c=>c.actions.setIsDashboardPanelOpen),{preferences:a}=n;return l.jsx(Ra,{FallbackComponent:iE,children:l.jsxs(MA,{dashboardProps:n,children:[l.jsx(T0e,{}),l.jsx(Z5,{componentType:"surfboard",componentId:n.id}),l.jsx(K5,{children:l.jsxs(Cle,{preferences:a,children:[o&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Eht,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Nht,{})}),l.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(kht,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(JF,{...n,type:"dashboard",children:[s&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(jht,{})}),l.jsx(Sht,{})]})})]})]})]})})]})})}var _ht=Object.defineProperty,Iht=(e,t,n)=>t in e?_ht(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,d1=(e,t,n)=>Iht(e,typeof t!="symbol"?t+"":t,n);const Mht={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},Dht={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}},Aht={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function Rht(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function hce(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const Fht={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=hce(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},Pht={stringify:e=>`${e}`,parse:e=>parseFloat(e)},Oht={stringify:e=>e,parse:e=>e},n_={string:Oht,number:Pht,boolean:Mht,function:Dht,method:Fht,json:Aht},kb=Symbol.for("r2wc.render"),f1=Symbol.for("r2wc.connected"),Ud=Symbol.for("r2wc.context"),si=Symbol.for("r2wc.props");function Lht(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),c={},u={},d={},f={};for(const m of i){c[m]=Array.isArray(t.props)?"string":t.props[m];const p=Rht(m);d[m]=p,f[p]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),d1(this,o,!0),d1(this,s),d1(this,r,{}),d1(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[si].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=c[p],y=x?n_[x]:null;if(x==="method"){const v=hce(g);Object.defineProperty(this[si].container,v,{enumerable:!0,configurable:!0,get(){return this[si][v]},set(C){this[si][v]=C,this[kb]()}}),this[si][p]=y.parse(b,g,this)}y!=null&&y.parse&&b&&(this[si][p]=y.parse(b,g,this))}for(const p of a)this[si][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[f1]=!0,this[kb]()}disconnectedCallback(){this[f1]=!1,this[Ud]&&n.unmount(this[Ud]),delete this[Ud]}attributeChangedCallback(p,g,b){const x=f[p],y=c[x],v=y?n_[y]:null;x in c&&v!=null&&v.parse&&b&&(this[si][x]=v.parse(b,p,this),this[kb]())}[(o=f1,s=Ud,r=si,kb)](){this[f1]&&(this[Ud]?n.update(this[Ud],this[si]):this[Ud]=n.mount(this.container,e,this[si]))}}for(const m of i){const p=d[m],g=c[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[si][m]},set(b){this[si][m]=b;const x=g?n_[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[kb]()}})}return h}function $ht(e,t,n){const r=due.createRoot(e),s=w.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function zht({root:e,ReactComponent:t},n){const r=w.createElement(t,n);e.render(r)}function Vht({root:e}){e.unmount()}function Bht(e,t={}){return Lht(e,t,{mount:$ht,update:zht,unmount:Vht})}const Uht={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"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"},Hht=Bht(Sle,{props:Uht});function SB(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Wht(e){if(Array.isArray(e))return e}function qht(e,t,n){return(t=Jht(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Yht(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,o,i,a=[],c=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(c=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(u)throw s}}return a}}function Ght(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1393
+ `);return l.jsxs(wn,{delayDuration:120,children:[l.jsx(Cn,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":t?"Validation failed. Hover to view details.":"Validation passed. Hover to view details.",className:Q("inline-flex h-5 w-5 items-center justify-center rounded-full transition-colors",t?"bg-destructive text-destructive-foreground hover:bg-destructive/90":"bg-emerald-600 text-white hover:bg-emerald-700"),children:t?l.jsx(Mt,{className:"h-3 w-3","aria-hidden":!0}):l.jsx(qr,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(i4,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(440px,calc(100vw-32px))] p-0",children:[l.jsxs("div",{className:"space-y-2.5 p-3 text-xs",children:[l.jsx("div",{className:Q("font-semibold",t?"text-destructive":"text-emerald-700"),children:t?"Validation failed":"Validation passed"}),l.jsxs("div",{className:"flex flex-wrap gap-x-2 gap-y-1 text-[11px] text-muted-foreground",children:[l.jsx("span",{children:n}),r&&l.jsx("span",{children:r}),s&&l.jsx("span",{children:s}),e.inferredDataType&&l.jsxs("span",{children:["type: ",e.inferredDataType]})]}),e.tokens.length>0&&l.jsxs("div",{className:"space-y-1.5 border-t pt-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Tokens"}),l.jsx("div",{className:"max-h-28 space-y-1 overflow-y-auto pr-1 select-text",children:e.tokens.map((i,a)=>l.jsxs("div",{className:"flex items-start gap-1.5",children:[l.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 font-mono leading-none",children:`{${i.token}}`}),l.jsx(DA,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}),i.field?l.jsx("span",{className:"break-all text-muted-foreground",children:i.field.qualifiedFieldName||i.field.name}):l.jsx("span",{className:"text-muted-foreground",children:"Unresolved"})]},`${i.token}-${a}`))})]}),e.errors.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-destructive",children:"Errors"}),l.jsx(Fc,{text:o,ariaLabel:"Copy validation errors",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-destructive select-text",children:e.errors.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.warnings.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-amber-700",children:"Warnings"}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-amber-700 select-text",children:e.warnings.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.inferredDataType&&l.jsxs("div",{className:"border-t pt-2 text-[11px] text-muted-foreground",children:["Inferred output type:"," ",l.jsx("span",{className:"font-medium text-foreground",children:e.inferredDataType})]})]}),l.jsx(nce,{className:"fill-popover"})]})]})}function yB({onValidate:e,isValidating:t,validationResult:n,error:r,disabled:s}){return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(re,{type:"button",variant:"outline",size:"sm",onClick:e,disabled:t||s,children:t?"Validating expression (may take a few seconds)...":"Validate Expression"}),n&&l.jsx(Bft,{result:n}),!n&&r&&l.jsxs(wn,{delayDuration:120,children:[l.jsx(Cn,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Validation failed. Hover to view details.",className:"inline-flex h-5 w-5 items-center justify-center rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90",children:l.jsx(Mt,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(i4,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(420px,calc(100vw-32px))] p-3",children:[l.jsxs("div",{className:"space-y-2 text-xs",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("span",{className:"font-semibold text-destructive",children:"Validation failed"}),l.jsx(Fc,{text:r,ariaLabel:"Copy validation error",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("p",{className:"max-h-40 overflow-y-auto break-words text-destructive select-text",children:r})]}),l.jsx(nce,{className:"fill-popover"})]})]})]})}function Uft({scope:e,onChange:t,showDashboardScope:n,error:r,disabled:s}){return l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(ge,{children:"Availability"}),l.jsxs(Do,{value:e,onValueChange:o=>t(o),className:"gap-0.5",disabled:s,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx($n,{id:"scope-card",value:"card"}),l.jsx(ge,{htmlFor:"scope-card",className:"text-sm font-normal",children:"This card only"})]}),n&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx($n,{id:"scope-dashboard",value:"dashboard"}),l.jsx(ge,{htmlFor:"scope-dashboard",className:"text-sm font-normal",children:"All cards on this sheet"})]})]}),r&&l.jsx("p",{className:"text-xs text-destructive",children:r})]})}function Hft(e){var r;const t=f0(e,"AI generation failed"),n=(r=ime(e))==null?void 0:r[0];return n?n.hint?`${n.message} Hint: ${n.hint}`:n.message||t:t}function Wft({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=rt(),[o,i]=w.useState(!1),[a,c]=w.useState(null);return{generateExpression:w.useCallback(async d=>{var f;if(!e)return c("AI generation is not available"),null;if(!d.trim())return c("Describe what you want to calculate"),null;i(!0),c(null);try{const h={type:"calculated-field-expression",context:{userQuery:d,availableFields:t.map(p=>({name:p.tokenLabel,dataType:p.dataType,...p.role==="metric"||p.role==="groupby"?{role:p.role}:{}})),fieldType:n},options:{dialect:r}},m=await Is(e,(s==null?void 0:s.accessToken)||"",h);if(!m.success||!((f=m.result)!=null&&f.generated))throw new Error(m.error||"No expression generated");return m.result.generated}catch(h){return c(Hft(h)),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),isGenerating:o,error:a}}function rce(e){return e.entityName===Io||e.qualifiedEntityName===Io||e.entityName===uo}function qft(e){return rce(e)?Io:e.qualifiedEntityName||e.entityName||"Other"}function Yft(e){return rce(e)?"Calculated Fields":e.qualifiedEntityName?Kf(e.entityName||e.qualifiedEntityName):Kf(e.entityName||"Other")}function Gft({open:e,onOpenChange:t,availableFields:n,fieldType:r,onExpressionGenerated:s,endpoint:o,dialect:i}){const[a,c]=w.useState(""),[u,d]=w.useState(""),[f,h]=w.useState(""),[m,p]=w.useState([]),g=w.useRef(null),{generateExpression:b,isGenerating:x,error:y}=Wft({endpoint:o,availableFields:n,fieldType:r,dialect:i}),v=w.useMemo(()=>{const M=f.trim().toLowerCase();return M?n.filter(P=>[P.label,P.baseLabel,P.name,P.tokenLabel,P.entityName,P.qualifiedEntityName].filter(Boolean).join(" ").toLowerCase().includes(M)):n},[n,f]),C=w.useMemo(()=>{const M=new Map;return v.forEach(P=>{var L;const D=qft(P),A=Yft(P);M.has(D)||M.set(D,{id:D,label:A,fields:[]}),(L=M.get(D))==null||L.fields.push(P)}),Array.from(M.values())},[v]),S=w.useMemo(()=>C.map(M=>M.id),[C]);w.useEffect(()=>{e&&p(S)},[e,S]),w.useEffect(()=>{if(e){if(f.trim()){p(S);return}p(M=>{const P=M.filter(D=>S.includes(D));return P.length>0?P:S})}},[e,f,S]);const N=M=>{const D=(M.name||M.baseLabel||M.label||M.tokenLabel||"").trim();return D.includes(".")&&D.split(".").pop()||D},j=M=>{const P=`{${M}}`,D=g.current;if(!D){c($=>$+P);return}const A=D.selectionStart||0,L=D.selectionEnd||0;c($=>`${$.slice(0,A)}${P}${$.slice(L)}`),requestAnimationFrame(()=>{D.focus();const $=A+P.length;D.setSelectionRange($,$)})},k=M=>{const P=M.tokenLabel||M.name||M.baseLabel||M.label||"";P.trim()&&j(P.trim())},T=async()=>{const M=await b(a.trim());M&&d(M)},E=()=>{u.trim()&&(s(u.trim()),c(""),d(""),t(!1))},_=()=>{c(""),d(""),h(""),p([]),t(!1)};return l.jsx(zr,{open:e,onOpenChange:M=>{M?t(!0):_()},children:l.jsxs(Tr,{className:"max-w-3xl",children:[l.jsxs(_r,{children:[l.jsx(Ir,{children:"Generate Expression with AI"}),l.jsx(ss,{children:"Describe what you want to calculate and we will draft a SQL expression."})]}),l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{htmlFor:"ai-prompt",children:"Describe what you want to calculate"}),l.jsx(yi,{id:"ai-prompt",ref:g,value:a,onChange:M=>c(M.target.value),placeholder:"Create a bucket that categorizes orders as 'Large' when amount is greater than 1000",rows:2})]}),l.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[l.jsx("span",{children:"Be specific about conditions, buckets, or math you want to apply."}),l.jsx(re,{size:"sm",onClick:T,disabled:x||!a.trim(),children:x?"Generating...":u?"Regenerate":"Generate"})]}),y&&l.jsx("p",{className:"text-xs text-destructive whitespace-pre-wrap",children:y})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{children:"Available fields"}),l.jsxs("div",{className:"relative",children:[l.jsx(Ws,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),l.jsx(lt,{value:f,onChange:M=>h(M.target.value),placeholder:"Search fields...",className:"pl-9"})]}),l.jsx("div",{className:"overflow-hidden rounded-lg border border-border",children:l.jsx(za,{className:"h-64",children:C.length===0?l.jsx("div",{className:"py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):l.jsx(zE,{type:"multiple",value:m,onValueChange:p,className:"space-y-1 p-2",children:C.map(M=>l.jsxs(Wp,{value:M.id,className:"border-none",children:[l.jsx(qp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[360px] truncate text-sm font-medium text-primary",children:M.label}),l.jsx(Xe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:M.fields.length})]})}),l.jsx(Yp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:M.fields.map(P=>l.jsxs("button",{type:"button",onClick:()=>k(P),className:"group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all hover:bg-muted",children:[l.jsxs("div",{className:"relative shrink-0",children:[bh(P.dataType),P.isCalculated&&l.jsx("span",{className:Q("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",P.role==="metric"?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-mono text-xs text-foreground/90 group-hover/container:text-foreground",children:N(P)}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:P.tokenLabel})]}),l.jsx(Xe,{variant:"secondary",className:"shrink-0 px-1.5 py-0 text-[11px]",children:P.dataType})]},P.id))})})]},M.id))})})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(ge,{children:"Generated expression"}),l.jsx(yi,{value:u,onChange:M=>d(M.target.value),rows:2,className:"font-mono text-sm"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Review and edit the generated expression before using it."})]})]}),l.jsxs(Ds,{className:"gap-2",children:[l.jsx(re,{variant:"ghost",onClick:_,children:"Cancel"}),l.jsx(re,{onClick:E,disabled:!u.trim(),children:"Use Expression"})]})]})})}const Kft=/\{([^}]+)\}/g;function VE(e){return e.trim().toLowerCase()}function sce(e){return Array.from(e.matchAll(Kft)).map(t=>t[1]).filter(Boolean)}function Zft(e){const t=new Set,n=[];return e.forEach(r=>{const s=VE(r);t.has(s)||(t.add(s),n.push(r))}),n}function a4(e){const t=new Map,n=(r,s)=>{const o=VE(r),i=t.get(o)||[];i.some(a=>a.id===s.id)||t.set(o,[...i,s])};return e.forEach(r=>{n(r.tokenLabel,r),r.name&&r.name!==r.tokenLabel&&n(r.name,r),r.baseLabel&&r.baseLabel!==r.tokenLabel&&n(r.baseLabel,r)}),t}function wm(e,t){const n=sce(e),r=Zft(n),s=a4(t),o=r.map(a=>{const c=s.get(VE(a))||[];return c.length===1?c[0]:null}),i=r.filter((a,c)=>!o[c]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function AD(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${Xft(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function Xft(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Qft=e=>e.entityName===Io||e.qualifiedEntityName===Io||e.entityName===uo?"Calculated Fields":e.qualifiedEntityName?Kf(e.entityName||e.qualifiedEntityName):Kf(e.entityName||"Other");function Jft(e){return e.entityName===Io||e.qualifiedEntityName===Io||e.entityName===uo?Io:e.qualifiedEntityName||e.entityName||"Other"}const eht=e=>Sn(e.dataType||"")==="number";function tht(e,t,n){const r=new Set((n||[]).map(s=>rf(s)));return e.filter(s=>{const o=rf(s.id);return o&&r.has(o)?!1:t==="dimension"?s.role!=="metric":!0})}function nht(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==uo?`${r.entityName}.${r.name}`:r.name;const i=o.toLowerCase(),a=n.get(i)||0;a>0&&(o=`${o} ${a+1}`),n.set(i,a+1),t.set(r.id,o)}),t}function rht(e,t,n,r){if(t!=="metric")return e.map(o=>({...o,isCompatible:!0}));if(!n)return e.map(o=>({...o,isCompatible:!0}));const s=n==="COUNT"||n==="DISTINCT";return e.map(o=>{const i=s||eht(o);return{...o,isCompatible:i}}).filter(o=>r)}function sht(e,t){if(!t)return e;const n=t.toLowerCase();return e.filter(r=>r.name.toLowerCase().includes(n)||r.baseLabel.toLowerCase().includes(n)||r.tokenLabel.toLowerCase().includes(n)||r.dataType.toLowerCase().includes(n)||(r.qualifiedEntityName||r.entityName||"").toLowerCase().includes(n))}function oht(e){const t=new Map;return e.forEach(n=>{var s;const r=Jft(n);t.has(r)||t.set(r,{id:r,label:Qft(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function iht({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=w.useMemo(()=>tht(e,t,r),[e,t,r]),a=w.useMemo(()=>nht(i),[i]),c=w.useMemo(()=>i.map(m=>{const p=m.label||m.name,g=m.role==="metric"&&d0(m)||m.role==="groupby"&&W7(m);return{...m,baseLabel:p,tokenLabel:a.get(m.id)||p,isCalculated:g,isCompatible:!0}}),[i,a]),u=w.useMemo(()=>a4(c),[c]),d=w.useMemo(()=>rht(c,t,s,o),[c,t,s,o]),f=w.useMemo(()=>sht(d,n),[d,n]),h=w.useMemo(()=>oht(f),[f]);return{allFields:c,filteredFields:f,groups:h,tokenCandidates:u}}const aht=e=>Sn(e.dataType||"")==="number",vB=e=>aht(e)?"SUM":"COUNT",lht=e=>{if(e.role==="metric"){const n=e;return{...n,aggregate:n.aggregate||vB(e)}}const t=vB(e);return{...e,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`}},cht=(e,t)=>{var r;const n=e.trim();if(n){if(/\bDATE_TRUNC\b/i.test(n))return"date";if(/\bTIMESTAMP\b/i.test(n))return"datetime";if(/\bDATE\b/i.test(n)&&!/\bUPDATE\b/i.test(n))return"date";if(/['"]/.test(n))return"string";if(/[+\-*/]/.test(n))return"number";if(t.length===1){const s=((r=t[0])==null?void 0:r.dataType)||"";if(/date|timestamp/i.test(s))return"date";if(/int|decimal|float|double|num|real/i.test(s))return"number";if(/boolean/i.test(s))return"boolean"}}};function uht({expression:e,availableFields:t,validationEndpoint:n,connectionId:r,dialect:s,fieldType:o,outputType:i,validationContext:a}){const{authToken:c}=rt(),[u,d]=w.useState(null),[f,h]=w.useState(!1),[m,p]=w.useState(null),g=w.useMemo(()=>a4(t),[t]),b=w.useMemo(()=>sce(e).map(S=>{const N=g.get(VE(S))||[];return{token:S,field:N.length===1?N[0]:null}}),[e,g]),x=w.useCallback((C,S)=>{const N=[{code:"SQL_VALIDATION_ERROR",message:C,suggestion:(S==null?void 0:S.suggestion)||(S==null?void 0:S.errorCode)}];return{isValid:!1,tokens:b,errors:N,warnings:[]}},[b]),y=w.useCallback(async()=>{var D;p(null);const C=n==null?void 0:n.trim();if(!C){const A=x("Validation endpoint is not configured");return d(A),A}if(!!!(a!=null&&a.cardConfig&&(a!=null&&a.cardDataSource)&&(a!=null&&a.cardId)&&(a!=null&&a.connectionId||r))){const A=x("Validation context is incomplete for server-side validation");return d(A),A}const{orderedTokens:N,orderedFields:j}=wm(e,t),k=[],T=[];N.forEach((A,L)=>{const $=j[L];$&&(k.push(A),T.push($))});const E=o==="metric"?T.map(lht):T,_=cht(e,T),M=AD(e,k),P={type:"calculated-field-expression",fieldType:o,expression:M,inputFields:E,outputType:i,options:{validateWithExplain:!0},context:{connectionId:(a==null?void 0:a.connectionId)||r,cardId:a==null?void 0:a.cardId,cardConfig:a==null?void 0:a.cardConfig,cardDataSource:a==null?void 0:a.cardDataSource,activeFilters:(a==null?void 0:a.activeFilters)||[],cardType:(a==null?void 0:a.cardType)||"table",dialect:s}};h(!0);try{const A=await Is(C,(c==null?void 0:c.accessToken)||"",P),L=A==null?void 0:A.status,$=A==null?void 0:A.error,B=A==null?void 0:A.errorCode,V=[],R=[];L==="invalid"?V.push({code:"SQL_VALIDATION_ERROR",message:$||"Expression failed SQL validation",suggestion:B?`Validation code: ${B}`:void 0}):L==="unverified"?R.push({code:"EXECUTION_UNVERIFIED",message:$||"Execution could not be fully verified in this environment.",suggestion:"Syntax checks passed. This expression may still run successfully."}):L!=="valid"&&V.push({code:"SQL_VALIDATION_ERROR",message:$||"Unexpected SQL validation response from server",suggestion:B?`Validation code: ${B}`:void 0});const U={isValid:(L==="valid"||L==="unverified")&&V.length===0,tokens:b,errors:V,warnings:R,inferredDataType:(A==null?void 0:A.inferredDataType)??((D=A==null?void 0:A.metadata)==null?void 0:D.inferredDataType)??_??i??void 0};return d(U),U}catch(A){const L=(A==null?void 0:A.error)||(A==null?void 0:A.message)||"Expression validation failed";p(L);const $=x(L);return d($),$}finally{h(!1)}},[n,a,r,e,t,o,i,s,c==null?void 0:c.accessToken,x,b]),v=w.useCallback(()=>{d(null),p(null)},[]);return{validationResult:u,isValidating:f,serverError:m,validateExpression:y,resetValidation:v}}function wB(e,t){const{aggregate:n,...r}=e;return{...r,...t}}function dht({fields:e,normalizedName:t,existingFieldId:n,targetKind:r,targetEntityName:s,targetQualifiedEntityName:o}){return e.some(i=>{if(n&&i.id===n||i.name!==t)return!1;const a=fd(i);if(r==="inline"){const c=wA(i),u=o||s;return a==="inline_expression"&&!!u&&c===u}return a==="domain_calculated"})}const CB=[{value:"string",label:"String"},{value:"number",label:"Number"},{value:"boolean",label:"Boolean"},{value:"date",label:"Date"},{value:"datetime",label:"Datetime"},{value:"json",label:"JSON"},{value:"geo",label:"Geo"}],fht=[],hht="https://docs.semaphor.cloud/docs/concepts/calculated-fields/metrics",mht="https://docs.semaphor.cloud/docs/concepts/calculated-fields/dimensions",pht="SUM({amount} - {discount_amount}) / NULLIF(SUM({quantity}), 0)",ght="CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",JT=e=>{if(!e)return"";const t=e.field.tokenLabel||e.field.label||e.field.name,n=e.aggregate;return n==="DISTINCT"?`COUNT(DISTINCT ${t})`:n==="COUNT"?`COUNT(${t})`:`${n}(${t})`},oce=e=>Sn(e.dataType||"")==="number",Cm=e=>oce(e)?"SUM":"COUNT",e_=(e,t)=>oce(e)||t==="COUNT"||t==="DISTINCT"?t:Cm(e);function t_(e,t){if(e.role==="metric"){const n=e;return d0(n)?n:{...n,aggregate:t}}return{...e,id:`${e.id}_${t.toLowerCase()}`,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`,entityName:e.entityName,entityId:e.entityId,qualifiedEntityName:e.qualifiedEntityName}}function um(e,t){const n=e.role==="metric"&&d0(e);return{field:e,aggregate:n&&e.aggregate||t,isCalculatedField:n}}function ice({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToDashboard:i,cardId:a,initialFieldType:c="metric",allowedFieldTypes:u}){var xe;const{tokenProps:d}=rt(),{selectedConnection:f}=wZ(),h=Ve(he=>{var Le;return(Le=he.card)==null?void 0:Le.config}),m=Ve(he=>{var Le;return(Le=he.card)==null?void 0:Le.dataSource}),p=Ve(he=>{var Le;return(Le=he.card)==null?void 0:Le.type}),b=Ve(he=>he.filterValues)??fht,x=(f==null?void 0:f.dialect)==="bigquery"||(f==null?void 0:f.dialect)==="snowflake",[y,v]=w.useState(c),[C,S]=w.useState(""),[N,j]=w.useState("ratio"),[k,T]=w.useState(null),[E,_]=w.useState(null),[M,P]=w.useState(1),[D,A]=w.useState(""),[L,$]=w.useState(null),[B,V]=w.useState("card"),[R,U]=w.useState({}),[O,I]=w.useState("A"),[W,X]=w.useState(""),[Z,H]=w.useState(!1),[K,z]=w.useState(null),[q,Y]=w.useState(!1),[G,J]=w.useState(!1),ne=w.useRef(null),be=w.useRef(!1),te=w.useRef(null),{userContext:ce}=Lo(),se=w.useMemo(()=>n.filter(he=>he.fieldScope==="domain"&&!!he.expression),[n]),ue=w.useMemo(()=>se.filter(he=>he.role==="metric"),[se]),Re=w.useMemo(()=>se.filter(he=>he.role==="groupby"),[se]),ke=!((ce==null?void 0:ce.type)==="organization"),me=!!i,Me=!!i,Se=(xe=d==null?void 0:d.apiServiceUrl)==null?void 0:xe.replace(/\/$/,""),ie=Se?`${Se}/v1/calculated-fields/validate`:"/v1/calculated-fields/validate",pe=Se?`${Se}/v1/ai/generate`:"/v1/ai/generate",Ne=w.useMemo(()=>{var ut;const he=[...n];return(((ut=r==null?void 0:r.calculatedFormula)==null?void 0:ut.inputFields)||[]).forEach(It=>{he.some(bn=>bn.id===It.id||bn.qualifiedFieldName===It.qualifiedFieldName||bn.name===It.name)||he.push(It)}),he},[n,r]),de=O==="A"?k:E,fe=y==="metric"&&N!=="custom"?de==null?void 0:de.aggregate:void 0,{allFields:Oe,groups:ye}=iht({fields:Ne,mode:y,searchTerm:W,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:fe,showIncompatible:!0}),Ce=Oe,{validationResult:$e,validateExpression:ze,isValidating:Ge,serverError:Ke,resetValidation:Ze}=uht({expression:D,availableFields:Ce,validationEndpoint:ie,connectionId:f==null?void 0:f.id,dialect:f==null?void 0:f.dialect,fieldType:y,outputType:L||void 0,validationContext:{connectionId:(f==null?void 0:f.id)||(m==null?void 0:m.connectionId),cardId:a,cardConfig:h||{},cardDataSource:m||null,activeFilters:b,cardType:p}}),st=$e==null?void 0:$e.inferredDataType,ae=L||st||"string",Pe=Ky.find(he=>he.id===N),Ee=w.useMemo(()=>{if(y==="dimension"){const{orderedFields:he}=wm(D,Ce);return he.filter(Le=>!!Le)}if(N==="custom"){const{orderedFields:he}=wm(D,Ce);return he.filter(Le=>!!Le)}return[k==null?void 0:k.field,E==null?void 0:E.field].filter(he=>!!he)},[Ce,D,y,k==null?void 0:k.field,E==null?void 0:E.field,N]),_e=w.useMemo(()=>o4(Ee),[Ee]),We=w.useMemo(()=>{if(!C.trim())return!1;const he=s4(C);return dht({fields:y==="metric"?ue:Re,normalizedName:he,existingFieldId:s==="domain"?r==null?void 0:r.id:void 0,targetKind:_e.kind==="inline"?"inline":"root",targetEntityName:_e.kind==="inline"?_e.entityName:void 0,targetQualifiedEntityName:_e.kind==="inline"?_e.qualifiedEntityName:void 0})},[_e,Re,ue,r,s,y,C]),Te=w.useMemo(()=>{if(y==="metric"&&N==="custom"){const{orderedFields:Le}=wm(D,Ce);return Le.filter(ut=>!!ut).map(ut=>ut.id)}const he=[];return k!=null&&k.field.id&&he.push(k.field.id),E!=null&&E.field.id&&he.push(E.field.id),he},[Ce,D,y,k,E,N]),Ue=he=>{ke||v(he)},et=he=>{ke||(j(he),he==="scale"&&_(null),he==="custom"&&(T(null),_(null)))},bt=()=>{S(""),j("ratio"),T(null),_(null),P(1),A(""),$(null),V("card"),U({}),X(""),H(!1),z(null),Y(!1),Ze(),t(!1)},dt=w.useCallback(he=>Ne.find(Le=>Le.qualifiedFieldName===he.qualifiedFieldName||Le.name===he.name)||he,[Ne]),St=w.useCallback(he=>{if(!he.calculatedFormula)return;const Le=he.calculatedFormula;if(j(Le.operation),A(""),Le.operation==="scale"){const zt=Le.inputFields[0];zt&&T(um(dt(zt),zt.aggregate||"SUM")),P(Le.constant===void 0?1:Le.constant);return}if(Le.operation==="custom"){A(Ot(he.expression||"",Le.inputFields||[])),T(null),_(null);return}const[ut,It]=Le.inputFields;ut&&T(um(dt(ut),ut.aggregate||"SUM")),It&&_(um(dt(It),It.aggregate||"SUM"))},[dt]),Ot=w.useCallback((he,Le)=>he.replace(/\{field_(\d+)\}/g,(ut,It)=>{var cr;const zt=Le[Number(It)];return zt?`{${((cr=Ce.find(bo=>bo.id===zt.id))==null?void 0:cr.tokenLabel)||zt.label||zt.name}}`:ut}),[Ce]);w.useEffect(()=>{var ut;if(!e){be.current=!1,te.current=null;return}const he=r?`${r.role}-${r.id||r.name}`:"new";if(be.current&&te.current===he)return;if(be.current=!0,te.current=he,U({}),X(""),Ze(),r){if(r.role==="metric"){v("metric"),S(r.label||r.name),V(s||"card"),St(r);return}v("dimension");const It=r;S(It.label||It.name),V(s||"card"),A(Ot(It.expression||"",((ut=It.calculatedFormula)==null?void 0:ut.inputFields)||[]));const zt=CB.some(bn=>bn.value===It.dataType)?It.dataType:"string";$(zt);return}const Le=u&&u.length>0?u.includes(c)?c:u[0]:c;v(Le),S(""),j("ratio"),T(null),_(null),P(1),A(""),$(null),V("card")},[e,r,s,c,u,St,Ot,Ze]);const xt=he=>{const Le=`{${he}}`,ut=ne.current;if(!ut){A(cr=>cr+Le);return}const It=ut.selectionStart||0,zt=ut.selectionEnd||0,bn=`${D.slice(0,It)}${Le}${D.slice(zt)}`;A(bn),requestAnimationFrame(()=>{ut.focus();const cr=It+Le.length;ut.setSelectionRange(cr,cr)})},an=he=>{if(ke)return;if(y==="dimension"||N==="custom"){xt(he.tokenLabel||he.label||he.name);return}const Le=e_(he,O==="A"?(k==null?void 0:k.aggregate)||Cm(he):(E==null?void 0:E.aggregate)||Cm(he)),ut=um(he,Le);if(O==="A"){T(ut),E||I("B");return}_(ut),k||I("A")},Tt=(he,Le)=>{if(!ke){if(he==="A"&&k){T({...k,aggregate:Le});return}he==="B"&&E&&_({...E,aggregate:Le})}},ve=async()=>{const he={};if(C.trim()||(he.name="Name is required"),N==="custom")D.trim()||(he.expression="Expression is required"),he.expression||(await ze()).isValid||(he.expression="Fix validation errors before saving");else if(N==="scale")k||(he.inputA="Please select a metric for input A"),Number.isNaN(M)&&(he.constant="Please enter a valid multiplication factor");else{if(k||(he.inputA="Please select a metric for input A"),E||(he.inputB="Please select a metric for input B"),k&&E){const Le=k.field.id===E.field.id,ut=k.aggregate===E.aggregate;Le&&ut&&(he.inputs="Inputs A and B must be different metrics")}if(r&&r.role==="metric"){const Le=rf(r.id);(rf(k==null?void 0:k.field.id)===Le||rf(E==null?void 0:E.field.id)===Le)&&(he.inputs="Cannot reference the field being edited")}}return U(he),Object.keys(he).length===0},nt=async()=>{const he={};return C.trim()||(he.name="Name is required"),D.trim()||(he.expression="Expression is required"),he.expression||(await ze()).isValid||(he.expression="Fix validation errors before saving"),U(he),Object.keys(he).length===0},ct=()=>{const{orderedTokens:he,orderedFields:Le}=wm(D,Ce),ut=Le.filter(bn=>!!bn),It=AD(D,he),zt=Fft(C,It,ut,ae,a,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...zt}:zt},pn=()=>{var It;if(N==="custom"){const{orderedTokens:zt,orderedFields:bn}=wm(D,Ce),cr=bn.filter(vt=>!!vt),bo=(r==null?void 0:r.role)==="metric"?((It=r.calculatedFormula)==null?void 0:It.inputFields)||[]:[],Fe=new Map;bo.forEach(vt=>{const Kn=rf(vt.id);Kn&&Fe.set(Kn,vt),vt.qualifiedFieldName&&Fe.set(vt.qualifiedFieldName,vt),vt.name&&Fe.set(vt.name,vt)});const Nt=cr.map(vt=>{const Kn=rf(vt.id),tr=Kn&&Fe.get(Kn)||vt.qualifiedFieldName&&Fe.get(vt.qualifiedFieldName)||Fe.get(vt.name),nr=((tr==null?void 0:tr.role)==="metric"?tr.aggregate:void 0)||(vt.role==="metric"?vt.aggregate:void 0)||Cm(vt);return t_(vt,nr)}),En=AD(D,zt),tn=gB(C,N,null,null,{},a,r==null?void 0:r.id,En,void 0,Nt);return r&&r.role==="metric"?wB(r,tn):tn}const he=k?t_(k.field,k.aggregate):null,Le=E?t_(E.field,E.aggregate):null,ut=gB(C,N,he,Le,{},a,r==null?void 0:r.id,void 0,N==="scale"?M:void 0);return r&&r.role==="metric"?wB(r,ut):ut},Qr=async he=>{if(he==="domain"){U(ut=>({...ut,scope:"Domain scope is not available in this explorer."}));return}if(y==="dimension"){const ut=ct();if(he==="dashboard"){if(!i){U(It=>({...It,scope:"Shared sheet scope is not available"}));return}await i(ut),bt();return}await o(ut),bt();return}const Le=pn();if(he==="dashboard"){if(!i){U(ut=>({...ut,scope:"Shared sheet scope is not available"}));return}await i(Le),bt();return}await o(Le),bt()},Nr=async()=>{if(ke)return;if(U({}),y==="metric"){if(!await ve())return}else if(!await nt())return;const he=me?B:s||"card";if(y==="metric"&&he!=="domain"&&We&&!r){z(he),Y(!0);return}J(!0);try{await Qr(he)}finally{J(!1)}},Jr=w.useMemo(()=>{if(!Pe||N==="custom")return"";if(N==="scale"){const he=Number.isFinite(M)?M:1;return`${JT(k)} x ${he}`}return`${JT(k)||"A"} ${Pe.symbol} ${JT(E)||"B"}`},[Pe,N,k,E,M]),ei=w.useMemo(()=>_e.kind==="inline"?"Inline":"Multi-Entity",[_e]),go=y==="metric"?hht:mht,Ha=y==="metric"?pht:ght,nu=y==="metric"?"Calculated Metric":"Calculated Dimension",yt=y==="metric"?"border-emerald-600/30 bg-emerald-500/10 text-emerald-700":"border-sky-600/30 bg-sky-500/10 text-sky-700";return l.jsxs(l.Fragment,{children:[l.jsxs(zr,{modal:!1,open:e,onOpenChange:he=>{he?t(!0):bt()},children:[e&&l.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),l.jsxs(Tr,{className:"max-w-5xl max-h-[90vh] overflow-hidden",onInteractOutside:he=>{he.preventDefault()},children:[l.jsxs(_r,{children:[l.jsxs(Ir,{className:"flex items-center gap-2",children:[l.jsxs("span",{children:[r?"Edit":"Create"," Calculated Field"]}),l.jsx(Xe,{variant:"outline",className:yt,children:nu}),l.jsx(Xe,{variant:"secondary",children:ei})]}),l.jsx(ss,{children:"Build calculated metrics and dimensions using expressions."})]}),l.jsxs("div",{className:"grid h-[70vh] min-h-0 grid-cols-[280px_1fr] gap-6",children:[l.jsx(Oft,{groups:ye,searchTerm:W,onSearchTermChange:X,onFieldClick:an,selectedFieldIds:Te,disabled:ke}),l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 overflow-y-auto pr-2 pb-6",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(ge,{children:"Field Type"}),l.jsx(Pft,{value:y,onChange:Ue,disabled:ke||!!r,options:u||["metric","dimension"]})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(ge,{htmlFor:"calculated-name",children:"Name"}),l.jsx(lt,{id:"calculated-name",value:C,onChange:he=>S(he.target.value),placeholder:y==="metric"?"e.g., Profit Margin":"e.g., Sales Tier",className:R.name?"border-destructive":"",disabled:ke}),R.name&&l.jsx("p",{className:"text-xs text-destructive",children:R.name})]}),me&&Me&&l.jsx("div",{className:"space-y-3",children:l.jsx(Uft,{scope:B,onChange:V,showDashboardScope:Me,error:R.scope,disabled:ke})}),y==="metric"&&l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(ge,{children:"Operation"}),l.jsx(Lft,{value:N,onChange:et,allowCustom:!0,disabled:ke}),R.operation&&l.jsx("p",{className:"text-xs text-destructive",children:R.operation})]}),N==="custom"?l.jsxs("div",{className:"space-y-3",children:[l.jsx(xB,{ref:ne,value:D,onChange:he=>{A(he)},onGenerate:()=>H(!0),showGenerate:!!pe&&!ke,docsUrl:go,placeholder:Ha,disabled:ke}),l.jsx(yB,{onValidate:ze,isValidating:Ge,validationResult:$e,error:Ke,disabled:ke}),R.expression&&l.jsx("p",{className:"text-xs text-destructive",children:R.expression})]}):l.jsxs("div",{className:"space-y-3",children:[l.jsx(ge,{children:"Inputs"}),l.jsx(bB,{label:"A",input:k,availableFields:Ce,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:he=>{const Le=e_(he,(k==null?void 0:k.aggregate)||Cm(he));T(um(he,Le))},onAggregateChange:he=>Tt("A",he),onRemove:()=>T(null),onActivate:()=>I("A"),allowMedian:x,disabled:ke}),R.inputA&&l.jsx("p",{className:"text-xs text-destructive",children:R.inputA}),N!=="scale"&&l.jsxs(l.Fragment,{children:[l.jsx(bB,{label:"B",input:E,availableFields:Ce,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:he=>{const Le=e_(he,(E==null?void 0:E.aggregate)||Cm(he));_(um(he,Le))},onAggregateChange:he=>Tt("B",he),onRemove:()=>_(null),onActivate:()=>I("B"),allowMedian:x,disabled:ke}),R.inputB&&l.jsx("p",{className:"text-xs text-destructive",children:R.inputB})]}),N==="scale"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(ge,{htmlFor:"constantFactor",children:"Multiplication Factor"}),l.jsx(lt,{id:"constantFactor",type:"number",step:"any",value:Number.isNaN(M)?"":M,onChange:he=>P(he.target.value===""?Number.NaN:Number(he.target.value)),className:R.constant?"border-destructive":"",placeholder:"e.g., 0.15",disabled:ke}),R.constant&&l.jsx("p",{className:"text-xs text-destructive",children:R.constant})]}),l.jsx("div",{className:"rounded-md border bg-muted/40 p-3 font-mono text-sm",children:Jr||"Select inputs to preview formula"}),R.inputs&&l.jsxs(Lj,{variant:"destructive",children:[l.jsx($c,{className:"h-4 w-4"}),l.jsx($j,{children:R.inputs})]})]})]}),y==="dimension"&&l.jsxs("div",{className:"space-y-3",children:[l.jsx(xB,{ref:ne,value:D,onChange:he=>{A(he)},onGenerate:()=>H(!0),showGenerate:!!pe&&!ke,docsUrl:go,placeholder:Ha,disabled:ke}),l.jsx(yB,{onValidate:ze,isValidating:Ge,validationResult:$e,error:Ke,disabled:ke}),R.expression&&l.jsx("p",{className:"text-xs text-destructive",children:R.expression}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(ge,{children:"Output Type"}),l.jsxs(pt,{value:ae,onValueChange:he=>$(he),disabled:ke,children:[l.jsx(ft,{children:l.jsx(gt,{placeholder:"Select output type"})}),l.jsx(ht,{children:CB.map(he=>l.jsx(Ie,{value:he.value,children:he.label},he.value))})]}),st&&!L&&l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Suggested type: ",st]})]})]})]})]}),l.jsxs(Ds,{children:[l.jsx(re,{variant:"outline",onClick:bt,disabled:G,children:"Cancel"}),l.jsx(re,{onClick:()=>void Nr(),disabled:G||Ge||ke,children:G?l.jsxs(l.Fragment,{children:[l.jsx(Mn,{className:"mr-2 h-4 w-4 animate-spin"}),r?"Updating":"Saving"," ",y==="metric"?"Metric":"Dimension","..."]}):l.jsxs(l.Fragment,{children:[r?"Update":"Save"," ",y==="metric"?"Metric":"Dimension"]})})]})]})]}),l.jsx(Gft,{open:Z,onOpenChange:H,availableFields:Ce,fieldType:y,onExpressionGenerated:async he=>{A(he),Ze()},endpoint:pe,dialect:f==null?void 0:f.dialect}),l.jsx(qc,{open:q,onOpenChange:Y,children:l.jsxs(Pl,{children:[l.jsxs(Ol,{children:[l.jsx($l,{children:"Name Conflict"}),l.jsxs(zl,{children:['A domain metric named "',C.trim(),'" already exists. Your local version will override it in this'," ",K==="dashboard"?"dashboard":"card",". Continue?"]})]}),l.jsxs(Ll,{children:[l.jsx(Bl,{onClick:()=>{z(null)},children:"Choose Different Name"}),l.jsx(Vl,{onClick:async()=>{if(K){Y(!1),J(!0);try{await Qr(K)}finally{J(!1),z(null)}}},children:"Continue"})]})]})})]})}function bht(e,t){const n=e.fieldScope==="dashboard";if(e.role==="metric"){const r=t.metricFields.find(s=>Lu(s,e,{allowComparableFallback:n}));if(r)return r}if(e.role==="groupby"){const r=t.groupByFields.find(s=>Lu(s,e,{allowComparableFallback:n}));if(r)return r}return t.storedCalculatedFields.find(r=>Lu(r,e,{allowComparableFallback:n}))}function xht(e,t){const n={...e,fieldScope:"domain"};return t.find(r=>r.fieldScope==="domain"&&Lu(r,n))}function ace(e,t){var n,r,s,o;if(e.role==="metric"&&t.role==="metric"){const i=e,a=t;return{...a,parameters:i.parameters||a.parameters?{filters:((n=i.parameters)==null?void 0:n.filters)??((r=a.parameters)==null?void 0:r.filters),windowTransform:((s=i.parameters)==null?void 0:s.windowTransform)??((o=a.parameters)==null?void 0:o.windowTransform)}:void 0,aliasTemplate:i.aliasTemplate??a.aliasTemplate,valueAliases:i.valueAliases??a.valueAliases,customFormat:i.customFormat??a.customFormat,comparisonType:i.comparisonType??a.comparisonType,comparisonDisplay:i.comparisonDisplay??a.comparisonDisplay,targetValue:i.targetValue??a.targetValue}}if(e.role==="groupby"&&t.role==="groupby"){const i=e,a=t;return{...a,granularity:i.granularity??a.granularity,dateFormat:i.dateFormat??a.dateFormat,customFormat:i.customFormat??a.customFormat,timeDrillPath:i.timeDrillPath??a.timeDrillPath}}return t}function lce(e,t,n,r){if(!n)return null;const o=Y7(e,n||t,r);if(n&&o<0)return null;if(o>=0){const i=e[o],a=i==null?void 0:i.id,c=r!=null&&r.mergeMatchedField?r.mergeMatchedField(i,t):t,d=a&&a!==c.id&&!((i==null?void 0:i.fieldScope)==="domain"&&c.fieldScope==="domain")?{...c,id:a}:c;return e.map((f,h)=>h===o?d:f)}return null}function cce(e,t){return{...e,fieldScope:t}}function RD(e){const t=cce(e.updatedField,"card"),n=lce(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="dashboard",mergeMatchedField:ace}),r=K7(e.storedFields,t,e.editingField,{allowComparableFallback:e.previousScope==="dashboard"}),s=e.previousScope==="dashboard"&&e.editingField?Nm(e.sharedFields,e.editingField,{allowComparableFallback:!0}):e.sharedFields;return{nextActiveFields:n,nextStoredFields:r,nextSharedFields:s}}function FD(e){const t=cce(e.updatedField,"dashboard"),n=lce(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="dashboard",mergeMatchedField:ace}),r=K7(e.sharedFields,t,e.editingField,{allowComparableFallback:!0}),s=e.previousScope==="card"&&e.editingField?Nm(e.storedFields,e.editingField,{allowComparableFallback:!0}):e.storedFields;return{nextActiveFields:n,nextStoredFields:s,nextSharedFields:r}}function Sm(e){const{nextSharedFields:t,currentSharedFields:n,isVisualEditing:r,selectedSheetId:s,updateFrame:o,updateSheetCalculatedFields:i,currentFrame:a,nextFramePatch:c,persistFrame:u,persistFrames:d}=e,f=c?{...c,calculatedFields:t}:{calculatedFields:t};(t!==n||c)&&o(f),s&&(r||(u&&(d!=null&&d.length)?d.forEach(h=>{u(s,{...h,calculatedFields:void 0})}):u&&a&&c&&u(s,{...a,...c,calculatedFields:void 0}),i&&i(s,t)))}const uce=w.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var Ot,xt,an,Tt;const[s,o]=w.useState(""),[i,a]=w.useState("all"),[c,u]=w.useState(!1),[d,f]=w.useState(null),[h,m]=w.useState("card"),[p,g]=w.useState("metric"),[b,x]=w.useState(null),[y,v]=w.useState(!1);Ve(ve=>ve.isDevMode);const C=Ve(ve=>ve.card.dataSource),S=Ve(ve=>ve.card.config),N=Ve(ve=>ve.card),j=Ve(ve=>ve.frame),k=Ve(ve=>ve.actions.updateCardConfig),T=Ve(ve=>ve.actions.updateCard),E=Ve(ve=>ve.actions.updateFrame),_=ee(ve=>ve.isVisualEditing),M=ee(ve=>ve.selectedSheetId),P=ee(ve=>ve.actions.updateSheetCalculatedFields),{userContext:D}=Lo(),{autoJoinMetadata:A}=kl(N),{rawColumnGroups:L,scopedFields:$,dashboardFilterableFields:B,inlineFilterableFields:V,scopedCalculatedFields:R,sharedCalculatedFields:U,inlineCalculatedFields:O,isLoading:I,error:W}=Tle(),X=(C==null?void 0:C.mode)==="semanticDomain"?C.semanticDomainId:void 0,{data:Z}=Q5(X),H=w.useMemo(()=>[...(S==null?void 0:S.groupByColumns)||[],...(S==null?void 0:S.metricColumns)||[],...(S==null?void 0:S.detailColumns)||[]],[S==null?void 0:S.groupByColumns,S==null?void 0:S.metricColumns,S==null?void 0:S.detailColumns]);(xt=(Ot=S==null?void 0:S.joinPlan)==null?void 0:Ot.baseEntity)==null||xt.name,(Tt=(an=A==null?void 0:A.resolvedJoinPlan)==null?void 0:an.baseEntity)==null||Tt.name,Fle();const K=t==="editor"?R:t==="filter"?U:O,z=K.length>0,q=(D==null?void 0:D.type)==="organization",Y=t==="editor"?$:t==="filter"?B:V,G=L,J=s.toLowerCase(),ne=(S==null?void 0:S.metricColumns)||[],be=(S==null?void 0:S.groupByColumns)||[],te=N.calculatedFields||[],ce=ve=>ve.name.toLowerCase().includes(J)||ve.dataType.toLowerCase().includes(J)||ve.label&&ve.label.toLowerCase().includes(J)||ve.qualifiedEntityName&&ve.qualifiedEntityName.toLowerCase().includes(J),se=w.useCallback(ve=>(ve.label||ve.name).toLowerCase().trim(),[]),ue=w.useCallback((ve,nt)=>se(ve).localeCompare(se(nt),void 0,{numeric:!0,sensitivity:"base"}),[se]),Re=Y.filter(ce).sort(ue),je=w.useCallback(ve=>t==="editor"?Qg(ve):va(ve),[t]),ke=ve=>{if(je(ve))return"calculated";if(ve.dataType==="number"||ve.dataType==="integer"||ve.dataType==="float"||ve.dataType==="decimal"||ve.dataType==="currency")return"metrics";const nt=Sn(ve.dataType);return["date","string","boolean"].includes(nt)?"dimensions":nt==="number"?"metrics":"dimensions"},me=ve=>{const nt=ve.filter(ce);return i==="all"?nt:nt.filter(ct=>ke(ct)===i)},Me=i==="all"?Re:Re.filter(ve=>ke(ve)===i),Se=z?me(K).sort(ue):[],ie=Y.filter(ve=>ke(ve)!=="calculated"),Ne=me(ie).sort(ue).reduce((ve,nt)=>{const ct=nt.qualifiedEntityName||"Other Fields";return ve[ct]||(ve[ct]={label:Kf(nt.entityName),fields:[]}),ve[ct].fields.push(nt),ve},{}),de=w.useMemo(()=>Object.entries(Ne).map(([ve,nt])=>{const ct=G.find(Qr=>Qr.entityName===ve)||{entityName:ve,label:nt.label},pn=ve===Io?"Domain Calculated Fields":ct.label||ct.entityName;return{groupName:ve,groupLabel:pn,fields:[...nt.fields].sort(ue)}}).sort((ve,nt)=>ve.groupLabel.localeCompare(nt.groupLabel,void 0,{numeric:!0,sensitivity:"base"})),[Ne,G,ue]),fe=ve=>ve.id||`${ve.entityName}-${ve.qualifiedEntityName}-${ve.name}-${ve.role||"field"}`,Oe=w.useMemo(()=>{const ve=new Map;return Y.forEach(ct=>{ve.set(fe(ct),kF(ct,{joinabilityMap:(Z==null?void 0:Z.joinabilityMap)||null,selectedFields:H,cardConfig:S,autoJoinMetadata:A}))}),ve},[Y,Z==null?void 0:Z.joinabilityMap,H,S,A]),ye=z?[{key:"scope-calculated",label:"Calculated Fields",fields:Se}].filter(ve=>ve.fields.length>0):[],$e=[...ye.map(ve=>ve.key),...de.map(ve=>ve.groupName)],ze=Re.filter(ve=>ke(ve)==="dimensions").length,Ge=Re.filter(ve=>ke(ve)==="metrics").length,Ke=Re.filter(ve=>ke(ve)==="calculated").length,Ze=Re.length>0&&t!=="inline-filter",st=t==="inline-filter"?"w-full":"w-[290px]";if(I)return l.jsx("div",{className:Q("flex h-full flex-col items-center justify-center py-8",st),children:l.jsx(ad,{size:"md",color:"muted","aria-label":"Loading data"})});if(W)return l.jsxs("div",{className:Q("flex h-full flex-col items-center justify-center py-8",st),children:[l.jsx(pl,{className:"mb-4 h-12 w-12 text-red-300"}),l.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),l.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:W.message||"Failed to load column data"})]});if(!C||!C.selectedEntities||C.selectedEntities.length===0)return l.jsxs("div",{className:Q("flex flex-col items-center justify-center py-8 text-center",st),children:[l.jsx(pl,{className:"mb-4 h-12 w-12 text-gray-300"}),l.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),l.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"||t==="inline-filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]});const ae=t==="inline-filter"?"px-3 pb-3":"px-3 pb-6",Pe=t==="inline-filter"?"overflow-hidden":"",Ee=ve=>bht(ve,{storedCalculatedFields:te,metricFields:ne,groupByFields:be}),_e=ve=>{T(N.id,{calculatedFields:Nm(te,ve,{allowComparableFallback:ve.fieldScope==="dashboard"})})},We=ve=>{var nt;return(nt=j==null?void 0:j.calculatedFields)==null?void 0:nt.find(ct=>Lu(ct,ve))},Te=ve=>{if(ve.role==="metric"){k(N.id,{metricColumns:Nm(ne,ve,{allowComparableFallback:ve.fieldScope==="dashboard"})});return}ve.role==="groupby"&&k(N.id,{groupByColumns:Nm(be,ve,{allowComparableFallback:ve.fieldScope==="dashboard"})})},Ue=ve=>{if(!j)return;const nt=Nm(j.calculatedFields||[],ve);Sm({nextSharedFields:nt,currentSharedFields:j.calculatedFields||[],isVisualEditing:_,selectedSheetId:M,updateFrame:E,updateSheetCalculatedFields:P})},et=ve=>{if(!q)return;if(ve.fieldScope==="domain"){qe.error("Domain calculated fields are read-only in this explorer.");return}if(ve.fieldScope==="dashboard"){const ct=We(ve);if(!ct)return;f(ct),m("dashboard"),g(ct.role==="metric"?"metric":"dimension"),u(!0);return}const nt=Ee(ve);nt&&(f(nt),m("card"),g(nt.role==="metric"?"metric":"dimension"),u(!0))},bt=async ve=>{if(q){if(ve.fieldScope==="domain"){qe.error("Domain calculated fields are read-only in this explorer.");return}if(ve.fieldScope==="dashboard"){Ue(ve),Te(ve);return}Te(ve),_e(ve)}},dt=async()=>{if(b){v(!0);try{await bt(b),x(null)}catch{}finally{v(!1)}}},St=ve=>{if(!q)return null;const nt=ve.fieldScope==="domain",ct=nt;return l.jsxs(pd,{children:[l.jsx(gd,{asChild:!0,children:l.jsx(re,{variant:"ghost",size:"icon",className:"h-6 w-6 rounded-full","aria-label":"Calculated field actions",children:l.jsx(_h,{className:"h-3.5 w-3.5"})})}),l.jsxs(Hc,{align:"end",className:"w-36",children:[nt?l.jsx(zs,{disabled:!0,children:"Read Only In Explorer"}):l.jsx(zs,{onClick:()=>et(ve),children:"Edit"}),l.jsx(zs,{className:"text-destructive focus:text-destructive",disabled:ct,onClick:()=>x(ve),children:"Delete"})]})]})};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:Q("mt-2 flex h-full w-full grow flex-col gap-2",ae,Pe),children:[l.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[Y.length>0&&l.jsxs("div",{className:"relative",children:[l.jsx(Ws,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx(lt,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:s,onChange:ve=>o(ve.target.value)}),s&&l.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>o(""),type:"button",children:l.jsx(Mt,{className:"size-3.5"})})]}),Ze&&l.jsx(As,{defaultValue:"all",value:i,onValueChange:ve=>a(ve),className:"mb-4",children:l.jsxs(ys,{className:"grid h-11 w-full grid-cols-4 rounded-lg border border-border/60 bg-muted/50 p-1",children:[l.jsxs(on,{value:"all",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:["All",l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Re.length})]}),l.jsxs(on,{value:"dimensions",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(bN,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:ze})]}),l.jsxs(on,{value:"metrics",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(fN,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Ge})]}),l.jsxs(on,{value:"calculated",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(AA,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Ke})]})]})}),t==="editor"&&i==="calculated"&&q&&l.jsx("div",{className:"flex items-center justify-end gap-2",children:l.jsxs(re,{size:"sm",variant:"outline",className:"w-full",onClick:()=>{f(null),m("card"),g("dimension"),u(!0)},children:[l.jsx($r,{className:"mr-2 h-3.5 w-3.5"}),"Add calculated field"]})})]}),l.jsxs(za,{className:"min-h-0 flex-1",children:[l.jsxs(zE,{type:"multiple",defaultValue:$e,className:"space-y-2",children:[ye.map(ve=>l.jsxs(Wp,{value:ve.key,className:"border-none",children:[l.jsx(qp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:ve.label}),l.jsx(Xe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:ve.fields.length})]})}),l.jsx(Yp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:ve.fields.map(nt=>{const ct=Oe.get(fe(nt)),pn=t==="editor"&&q&&va(nt);return l.jsx(mB,{field:nt,context:t,fieldState:ct,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:pn?St(nt):void 0},nt.id)})})})]},ve.key)),de.map(({groupName:ve,groupLabel:nt,fields:ct})=>l.jsxs(Wp,{value:ve,className:"border-none",children:[l.jsx(qp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{title:nt,className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:nt}),l.jsx(Xe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:ct.length})]})}),l.jsx(Yp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:ct.map(pn=>{const Qr=Oe.get(fe(pn)),Nr=t==="editor"&&q&&va(pn);return l.jsx(mB,{field:pn,context:t,fieldState:Qr,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:Nr?St(pn):void 0},pn.id)})})})]},ve))]}),Y.length===0&&l.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[l.jsx("p",{children:"No fields found for selected data source"}),l.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Y.length>0&&Me.length===0&&l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),l.jsx(Da,{orientation:"horizontal"}),l.jsx(Da,{orientation:"vertical"})]})]}),l.jsx(qc,{open:!!b,onOpenChange:ve=>{ve||x(null)},children:l.jsxs(Pl,{children:[l.jsxs(Ol,{children:[l.jsx($l,{children:"Delete calculated field?"}),l.jsxs(zl,{children:["This will remove"," ",l.jsx("span",{className:"font-medium text-foreground",children:(b==null?void 0:b.label)||(b==null?void 0:b.name)||"this calculated field"})," ",(b==null?void 0:b.fieldScope)==="domain"?"from the semantic domain.":"from this configuration."]})]}),l.jsxs(Ll,{children:[l.jsx(Bl,{disabled:y,children:"Cancel"}),l.jsx(Vl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,onClick:ve=>{ve.preventDefault(),dt()},children:y?"Deleting...":"Delete"})]})]})}),l.jsx(ice,{open:c,onOpenChange:ve=>{u(ve),ve||(f(null),m("card"))},availableFields:$,existingField:d??void 0,existingFieldScope:h,initialFieldType:p,onSave:ve=>{const nt=d,ct=(j==null?void 0:j.calculatedFields)||[];if(ve.role==="metric"){const{nextActiveFields:Jr,nextStoredFields:ei,nextSharedFields:go}=RD({activeFields:ne,storedFields:te,sharedFields:ct,updatedField:ve,editingField:nt,previousScope:h});Jr&&k(N.id,{metricColumns:Jr}),T(N.id,{calculatedFields:ei}),j&&go!==ct&&Sm({nextSharedFields:go,currentSharedFields:ct,isVisualEditing:_,selectedSheetId:M,updateFrame:E,updateSheetCalculatedFields:P});return}const{nextActiveFields:pn,nextStoredFields:Qr,nextSharedFields:Nr}=RD({activeFields:be,storedFields:te,sharedFields:ct,updatedField:ve,editingField:nt,previousScope:h});pn&&k(N.id,{groupByColumns:pn}),T(N.id,{calculatedFields:Qr}),j&&Nr!==ct&&Sm({nextSharedFields:Nr,currentSharedFields:ct,isVisualEditing:_,selectedSheetId:M,updateFrame:E,updateSheetCalculatedFields:P})},onSaveToDashboard:ve=>{const nt=d,ct=(j==null?void 0:j.calculatedFields)||[];if(ve.role==="metric"){const{nextActiveFields:Jr,nextStoredFields:ei,nextSharedFields:go}=FD({activeFields:ne,storedFields:te,sharedFields:ct,updatedField:ve,editingField:nt,previousScope:h});j&&Sm({nextSharedFields:go,currentSharedFields:ct,isVisualEditing:_,selectedSheetId:M,updateFrame:E,updateSheetCalculatedFields:P}),Jr&&k(N.id,{metricColumns:Jr}),T(N.id,{calculatedFields:ei});return}const{nextActiveFields:pn,nextStoredFields:Qr,nextSharedFields:Nr}=FD({activeFields:be,storedFields:te,sharedFields:ct,updatedField:ve,editingField:nt,previousScope:h});j&&Sm({nextSharedFields:Nr,currentSharedFields:ct,isVisualEditing:_,selectedSheetId:M,updateFrame:E,updateSheetCalculatedFields:P}),pn&&k(N.id,{groupByColumns:pn}),T(N.id,{calculatedFields:Qr})},cardId:N.id})]})}),dce=w.memo(function({context:t="editor"}={}){return l.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",l.jsx(uce,{context:t})," "]})});function fce(){const e=Ve(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=lr();w.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:c,connectionId:u}=e4(e),d=(m=e.selectedEntities)==null?void 0:m[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(c||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function yht(){fce();const e=ee(c=>c.selectedSheetId),t=ee(c=>c.selectedFrameId),n=ee(c=>c.dashboard),r=ee(c=>c.actions.getSelectedFrame),{setSelectedFrameId:s}=en(),{setCard:o}=lr(),i=Ve(c=>c.card.dataSource);return w.useEffect(()=>{var u,d;let c=r();if(!c){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(m=>m.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),c=h)}if(c){const f=c.cards.find(h=>h.id===c.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function vht(){const e=ee(o=>o.dashboard.filterLayout),{setFilterLayout:t}=en(),n=(e==null?void 0:e.displayMode)||"canvas",r=(e==null?void 0:e.toolbarWrap)??!1,s=(e==null?void 0:e.showDownloadButton)??!1;return l.jsxs(Gr,{children:[l.jsx(Kr,{asChild:!0,children:l.jsx(re,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:l.jsx(gl,{className:"h-4 w-4"})})}),l.jsx(Zr,{className:"w-[280px]",align:"end",children:l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"mb-3 text-sm font-medium",children:"Filter Display"}),l.jsxs(Do,{value:n,onValueChange:o=>t({displayMode:o}),className:"space-y-2",children:[l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx($n,{value:"canvas",id:"canvas",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(ge,{htmlFor:"canvas",className:"cursor-pointer font-normal",children:"Canvas Cards"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters as draggable, resizable cards on the dashboard"})]})]}),l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx($n,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(ge,{htmlFor:"toolbar",className:"cursor-pointer font-normal",children:"Toolbar"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Compact horizontal toolbar below dashboard controls"})]})]})]})]}),n==="toolbar"&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-center space-x-2 border-t pt-4",children:[l.jsx(Jt,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),l.jsx(ge,{htmlFor:"wrap",className:"cursor-pointer text-sm font-normal",children:"Wrap filters to multiple lines"})]}),l.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[l.jsx(Jt,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),l.jsx(ge,{htmlFor:"download",className:"cursor-pointer text-sm font-normal",children:"Show download button"})]})]}),l.jsx("p",{className:"border-t pt-3 text-xs text-muted-foreground",children:"Individual filters can override this setting in their configuration."})]})})]})}function wht(){const e=ee(n=>n.actions.setShowFilters),{hasEntities:t}=yht();return l.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[l.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[l.jsx(ge,{className:"px-2 text-base",children:"Dashboard Filters"}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(vht,{}),l.jsx(re,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:l.jsx(sse,{})})]})]}),!t&&l.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[l.jsx(pl,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),l.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&l.jsx("div",{className:"flex grow overflow-y-auto",children:l.jsx(vv,{collisionDetection:bv,children:l.jsx(wv,{items:[],strategy:r5,children:l.jsx(dce,{context:"filter"})})})})]})}function Cht(){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?l.jsx("div",{className:Q("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(ZO,{filter:r}),l.jsx(Vg,{filter:r})]},r.id))}):null}function Sht(){const e=ee(r=>r.showFilters),t=ee(r=>r.isVisualEditing),n=ee(r=>r.isDashboardEditing);return l.jsxs("div",{role:"dashboard-plus-main",className:Q("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[l.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&l.jsx(Cht,{}),l.jsx(vle,{})]}),e&&l.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:l.jsx(wht,{})})]})}const Nht=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-CLd_NTpW.js"))),jht=w.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-NyBBQhsY.js"))),Eht=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-CPyonfsi.js"))),kht=w.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-lglhpWpc.js")).then(e=>({default:e.ResourceManagementPanel})));function Tht({showControls:e=!1,showFooter:t=!0,...n}){const r=ee(c=>c.isDashboardPanelOpen),s=ee(c=>c.isVisualEditing),o=ee(c=>c.showDashboardJSON),i=ee(c=>c.actions.setIsDashboardPanelOpen),{preferences:a}=n;return l.jsx(Ra,{FallbackComponent:iE,children:l.jsxs(MA,{dashboardProps:n,children:[l.jsx(T0e,{}),l.jsx(Z5,{componentType:"surfboard",componentId:n.id}),l.jsx(K5,{children:l.jsxs(Cle,{preferences:a,children:[o&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Eht,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Nht,{})}),l.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(kht,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(JF,{...n,type:"dashboard",children:[s&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(jht,{})}),l.jsx(Sht,{})]})})]})]})]})})]})})}var _ht=Object.defineProperty,Iht=(e,t,n)=>t in e?_ht(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,d1=(e,t,n)=>Iht(e,typeof t!="symbol"?t+"":t,n);const Mht={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},Dht={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}},Aht={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function Rht(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function hce(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const Fht={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=hce(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},Pht={stringify:e=>`${e}`,parse:e=>parseFloat(e)},Oht={stringify:e=>e,parse:e=>e},n_={string:Oht,number:Pht,boolean:Mht,function:Dht,method:Fht,json:Aht},kb=Symbol.for("r2wc.render"),f1=Symbol.for("r2wc.connected"),Ud=Symbol.for("r2wc.context"),si=Symbol.for("r2wc.props");function Lht(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),c={},u={},d={},f={};for(const m of i){c[m]=Array.isArray(t.props)?"string":t.props[m];const p=Rht(m);d[m]=p,f[p]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),d1(this,o,!0),d1(this,s),d1(this,r,{}),d1(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[si].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=c[p],y=x?n_[x]:null;if(x==="method"){const v=hce(g);Object.defineProperty(this[si].container,v,{enumerable:!0,configurable:!0,get(){return this[si][v]},set(C){this[si][v]=C,this[kb]()}}),this[si][p]=y.parse(b,g,this)}y!=null&&y.parse&&b&&(this[si][p]=y.parse(b,g,this))}for(const p of a)this[si][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[f1]=!0,this[kb]()}disconnectedCallback(){this[f1]=!1,this[Ud]&&n.unmount(this[Ud]),delete this[Ud]}attributeChangedCallback(p,g,b){const x=f[p],y=c[x],v=y?n_[y]:null;x in c&&v!=null&&v.parse&&b&&(this[si][x]=v.parse(b,p,this),this[kb]())}[(o=f1,s=Ud,r=si,kb)](){this[f1]&&(this[Ud]?n.update(this[Ud],this[si]):this[Ud]=n.mount(this.container,e,this[si]))}}for(const m of i){const p=d[m],g=c[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[si][m]},set(b){this[si][m]=b;const x=g?n_[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[kb]()}})}return h}function $ht(e,t,n){const r=due.createRoot(e),s=w.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function zht({root:e,ReactComponent:t},n){const r=w.createElement(t,n);e.render(r)}function Vht({root:e}){e.unmount()}function Bht(e,t={}){return Lht(e,t,{mount:$ht,update:zht,unmount:Vht})}const Uht={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"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"},Hht=Bht(Sle,{props:Uht});function SB(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Wht(e){if(Array.isArray(e))return e}function qht(e,t,n){return(t=Jht(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Yht(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,o,i,a=[],c=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(c=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(u)throw s}}return a}}function Ght(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1394
1394
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function NB(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 jB(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?NB(Object(n),!0).forEach(function(r){qht(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):NB(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Kht(e,t){if(e==null)return{};var n,r,s=Zht(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function Zht(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Xht(e,t){return Wht(e)||Yht(e,t)||emt(e,t)||Ght()}function Qht(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 Jht(e){var t=Qht(e,"string");return typeof t=="symbol"?t:t+""}function emt(e,t){if(e){if(typeof e=="string")return SB(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?SB(e,t):void 0}}function tmt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function EB(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 kB(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?EB(Object(n),!0).forEach(function(r){tmt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):EB(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function nmt(){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 cx(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),c=0;c<i;c++)a[c]=arguments[c];return t.apply(n,[].concat(s,a))}}}function GS(e){return{}.toString.call(e).includes("Object")}function rmt(e){return!Object.keys(e).length}function Zy(e){return typeof e=="function"}function smt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function omt(e,t){return GS(t)||qu("changeType"),Object.keys(t).some(function(n){return!smt(e,n)})&&qu("changeField"),t}function imt(e){Zy(e)||qu("selectorType")}function amt(e){Zy(e)||GS(e)||qu("handlerType"),GS(e)&&Object.values(e).some(function(t){return!Zy(t)})&&qu("handlersType")}function lmt(e){e||qu("initialIsRequired"),GS(e)||qu("initialType"),rmt(e)&&qu("initialContent")}function cmt(e,t){throw new Error(e[t]||e.default)}var umt={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"},qu=cx(cmt)(umt),h1={changes:omt,selector:imt,handler:amt,initial:lmt};function dmt(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};h1.initial(e),h1.handler(t);var n={current:e},r=cx(mmt)(n,t),s=cx(hmt)(n),o=cx(h1.changes)(e),i=cx(fmt)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return h1.selector(u),u(n.current)}function c(u){nmt(r,s,o,i)(u)}return[a,c]}function fmt(e,t){return Zy(t)?t(e.current):t}function hmt(e,t){return e.current=kB(kB({},e.current),t),t}function mmt(e,t,n){return Zy(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 pmt={create:dmt},gmt={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs"}};function bmt(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),c=0;c<i;c++)a[c]=arguments[c];return t.apply(n,[].concat(s,a))}}}function xmt(e){return{}.toString.call(e).includes("Object")}function ymt(e){return e||TB("configIsRequired"),xmt(e)||TB("configType"),e.urls?(vmt(),{paths:{vs:e.urls.monacoBase}}):e}function vmt(){console.warn(mce.deprecation)}function wmt(e,t){throw new Error(e[t]||e.default)}var mce={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!
1395
1395
  You are using deprecated way of configuration.
1396
1396