react-semaphor 0.0.655 → 0.0.657
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{dashboard-plus-BzFxeDDs.js → dashboard-plus-CeHc-__J.js} +18 -18
- package/dist/chunks/{dashboard-plus-CIbnRZm1.js → dashboard-plus-DXzOsUvd.js} +3191 -3127
- package/dist/chunks/{index-BHCyo6jW.js → index-Bei7De_X.js} +64 -64
- package/dist/chunks/{index-D0V_kgoc.js → index-C428CnQH.js} +3371 -3374
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -3
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const e=require("react/jsx-runtime"),s=require("./index-
|
|
1
|
+
"use strict";const e=require("react/jsx-runtime"),s=require("./index-Bei7De_X.js"),A=require("react");require("react-dom");function aa(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const Ee=aa(A);/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
*
|
|
49
49
|
* This source code is licensed under the ISC license.
|
|
50
50
|
* See the LICENSE file in the root directory of this source tree.
|
|
51
|
-
*/const
|
|
51
|
+
*/const Bs=s.createLucideIcon("Building",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2",key:"76otgf"}],["path",{d:"M9 22v-4h6v4",key:"r93iot"}],["path",{d:"M8 6h.01",key:"1dz90k"}],["path",{d:"M16 6h.01",key:"1x0f13"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M8 14h.01",key:"6423bh"}]]);/**
|
|
52
52
|
* @license lucide-react v0.453.0 - ISC
|
|
53
53
|
*
|
|
54
54
|
* This source code is licensed under the ISC license.
|
|
@@ -73,7 +73,7 @@
|
|
|
73
73
|
*
|
|
74
74
|
* This source code is licensed under the ISC license.
|
|
75
75
|
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
-
*/const
|
|
76
|
+
*/const ze=s.createLucideIcon("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/**
|
|
77
77
|
* @license lucide-react v0.453.0 - ISC
|
|
78
78
|
*
|
|
79
79
|
* This source code is licensed under the ISC license.
|
|
@@ -168,7 +168,7 @@
|
|
|
168
168
|
*
|
|
169
169
|
* This source code is licensed under the ISC license.
|
|
170
170
|
* See the LICENSE file in the root directory of this source tree.
|
|
171
|
-
*/const
|
|
171
|
+
*/const qe=s.createLucideIcon("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/**
|
|
172
172
|
* @license lucide-react v0.453.0 - ISC
|
|
173
173
|
*
|
|
174
174
|
* This source code is licensed under the ISC license.
|
|
@@ -193,7 +193,7 @@
|
|
|
193
193
|
*
|
|
194
194
|
* This source code is licensed under the ISC license.
|
|
195
195
|
* See the LICENSE file in the root directory of this source tree.
|
|
196
|
-
*/const
|
|
196
|
+
*/const Ps=s.createLucideIcon("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/**
|
|
197
197
|
* @license lucide-react v0.453.0 - ISC
|
|
198
198
|
*
|
|
199
199
|
* This source code is licensed under the ISC license.
|
|
@@ -213,12 +213,12 @@
|
|
|
213
213
|
*
|
|
214
214
|
* This source code is licensed under the ISC license.
|
|
215
215
|
* See the LICENSE file in the root directory of this source tree.
|
|
216
|
-
*/const
|
|
216
|
+
*/const Ba=s.createLucideIcon("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);/**
|
|
217
217
|
* @license lucide-react v0.453.0 - ISC
|
|
218
218
|
*
|
|
219
219
|
* This source code is licensed under the ISC license.
|
|
220
220
|
* See the LICENSE file in the root directory of this source tree.
|
|
221
|
-
*/const
|
|
221
|
+
*/const Pa=s.createLucideIcon("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]]);/**
|
|
222
222
|
* @license lucide-react v0.453.0 - ISC
|
|
223
223
|
*
|
|
224
224
|
* This source code is licensed under the ISC license.
|
|
@@ -238,7 +238,7 @@
|
|
|
238
238
|
*
|
|
239
239
|
* This source code is licensed under the ISC license.
|
|
240
240
|
* See the LICENSE file in the root directory of this source tree.
|
|
241
|
-
*/const
|
|
241
|
+
*/const Ve=s.createLucideIcon("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/**
|
|
242
242
|
* @license lucide-react v0.453.0 - ISC
|
|
243
243
|
*
|
|
244
244
|
* This source code is licensed under the ISC license.
|
|
@@ -313,7 +313,7 @@
|
|
|
313
313
|
*
|
|
314
314
|
* This source code is licensed under the ISC license.
|
|
315
315
|
* See the LICENSE file in the root directory of this source tree.
|
|
316
|
-
*/const Wa=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function Ka(){const{setTheme:t}=s.useTheme(),n=s.useDashboardStore(a=>a.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx($a,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Ra,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function as(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>at(c))}})}})}}function at(t){return{...t,customCfg:Qa(t.customCfg),data:[]}}function Qa(t){var n,a;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(a=(n=t==null?void 0:t.data)==null?void 0:n.datasets)==null?void 0:a.map(r=>({...r,data:[]}))}}:null}async function Ja(t,n,a,r,l){if(!l)return null;const o=JSON.stringify(a),c=`${t}/v1/lens`;return await s.postRequest(c,l,{name:n,template:o,filterValues:r,operation:"create"})}async function ys(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:o,isDefault:c,shared:i}=n,d=`${t}/v1/lens`;return await s.postRequest(d,a,{lensId:r,template:l,filterValues:o,isDefault:c,shared:i,operation:"update"})}async function Xa(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function Za(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),l=s.useDashboardStore(g=>g.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=A.useState(!1),[u,m]=A.useState(!1),h=s.useDashboardStore(g=>g.dashboard),x=s.useDashboardStore(g=>g.filterValues),{authToken:j,tokenProps:b}=s.useSemaphorContext();async function p(){d(!0);const g=as(h),f=await Ja(b.apiServiceUrl,t,g,x,j==null?void 0:j.accessToken);f&&(o([...l||[],f]),c(f.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:g=>{n(g.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:p,disabled:i,children:i?"Creating...":"Add"})})]})]})}function en(){const[t,n]=A.useState(!1),a=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c,tokenProps:i}=s.useSemaphorContext();async function d(h){o(h)}async function u(h){if(await Xa(i.apiServiceUrl,h,c==null?void 0:c.accessToken)){const j=a==null?void 0:a.filter(b=>b.id!==h);l(j||[]),o("original")}}async function m(h){const x=a==null?void 0:a.map(p=>p.id===h.id?{...p,isDefault:!h.isDefault}:{...p,isDefault:!1});l(x||[]);const j={...h,isDefault:!h.isDefault};await ys(i.apiServiceUrl,j,c==null?void 0:c.accessToken);const b=a==null?void 0:a.find(p=>p.isDefault);if(b&&b.id!==h.id){const p={...b,isDefault:!1};await ys(i.apiServiceUrl,p,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Sa,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:d,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:x=>{x.preventDefault(),m(h)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:x=>{x.preventDefault(),u(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function sn({iconClassName:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(""),[o,c]=A.useState(!1),i=s.useDashboardStore(h=>h.isDownloadingPdf),{tokenProps:d}=s.useSemaphorContext();async function u(){const h=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl),s.ue.dismiss(h),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",x)}}async function m(){if(!r)return;a(!1),l(""),c(!1);const h=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl,r),s.ue.dismiss(h),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",x)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(s.Lock,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:n,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:h=>l(h.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:h=>{h.key==="Enter"&&r&&m()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:m,disabled:!r,children:"Download"})]})]})})]})}function nt({triggerButtonClassName:t}){const[n,a]=A.useState(!1),r=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.id}),l=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.title}),o=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.sheets}),c=s.useDashboardStore(i=>i.selectedSheetId);return o==null||o.find(i=>i.id===c),r?e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),onClick:()=>a(!0),children:e.jsx(s.Clock,{className:"size-4"})}),e.jsx(s.EmailScheduleDialog,{open:n,onOpenChange:a,dashboardId:r,dashboardName:l})]}):null}function ns({value:t,onChange:n,placeholder:a="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:a,value:t,onChange:r=>n(r.target.value),className:"pl-9"})]})}function Re({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=a.find(u=>u.value===t))==null?void 0:d.label)||t,i=a.filter(u=>u.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>n(u.value),disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function rt({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>a(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(Re,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>a(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function lt({usersToRemove:t,allUsers:n,onRemove:a}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>a(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>a(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function ot({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=n.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function it(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=A.useRef(null);return A.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function ye(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function tn(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function ct(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function an(t,n,a){const r=ct(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function nn({user:t}){return ct(t)==="tenant"?e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="POWER_USER"?"Power User":"Viewer"}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="ADMIN"?"Admin":t.role==="POWER_USER"?"Power User":"Viewer"})}function rn({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=tn((r==null?void 0:r.type)||""),i=a.some(h=>h.id===t.id),d=a.find(h=>h.id===t.id),u=d?d.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Re,{currentRole:u,onRoleChange:h=>{o(t.id,n.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:ye(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function ln({hasAccess:t,isUserRemoving:n,isSelected:a,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!n&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),n&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),a&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Pe,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function on({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function cn({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((x,j)=>{var f,y;const b=((f=n.find(E=>E.id===x.orgUserId))==null?void 0:f.name)||"Unknown User",p=((y=n.find(E=>E.id===x.orgUserId))==null?void 0:y.type)||"",g=ye(x.role,a(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},j)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((x,j)=>{var f,y;const b=((f=n.find(E=>E.id===x.tenantUserId))==null?void 0:f.name)||"Unknown User",p=((y=n.find(E=>E.id===x.tenantUserId))==null?void 0:y.type)||"",g=ye(x.role,a(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},j)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((x,j)=>{const b=ye(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},j)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((x,j)=>{const b=ye(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},j)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((x,j)=>{const b=ye(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},j)})})]}),!i.length&&!d.length&&!u.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var j,b;const m=((j=n.find(p=>p.id===d.tenantUserId))==null?void 0:j.name)||"Unknown User",h=((b=n.find(p=>p.id===d.tenantUserId))==null?void 0:b.type)||"",x=ye(d.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:x})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=ye(d.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var x,j;const u=((x=n.find(b=>b.id===i.tenantUserId))==null?void 0:x.name)||"Unknown User",m=((j=n.find(b=>b.id===i.tenantUserId))==null?void 0:j.type)||"",h=ye(i.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=ye(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function dn({isInitialLoading:t,searchQuery:n,availableUsers:a}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):a.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:n?"No users found matching your search.":"No users available to share with."}):null}function un({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:x,handleUserRoleChange:j}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?a?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(nn,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Re,{currentRole:n==null?void 0:n.role,onRoleChange:b=>x(t.id,n.role,b),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(rn,{user:t,userShare:n,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:x}),o&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(Re,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:b=>j(t.id,b),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(ln,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(on,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function dt({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),j=s.useShareSearchQuery(),b=s.useShareManagementActions(),p=c||(N=>{const D=m.some(C=>C.id===N),v=h.includes(N);D?b.removeSelectedUser(N):v?b.removeUserFromRemove(N):b.addSelectedUser({id:N,role:"VIEWER"})}),g=i||b.updateSelectedUserRole,f=d||b.addUserToRemove,y=u||((N,D,v)=>{b.addUserToUpdate({id:N,currentRole:D,newRole:v})}),E=l,T=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(E??[]).length,")"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(cn,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(E==null?void 0:E.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===E.length?b.setSelectedUsers([]):b.setSelectedUsers(E.map(N=>({id:N.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===E.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(dn,{isInitialLoading:n,isSearching:a,searchQuery:j,availableUsers:E||[]}),!n&&!a&&(E==null?void 0:E.length)>0&&E.map(N=>{const D=t?an(N,t,o):void 0,v=T.includes(N.id),C=!!D,S=C&&!v,F=m.some(k=>k.id===N.id),I=m.find(k=>k.id===N.id),P=r(N.type);return e.jsx(un,{user:N,userShare:D,isUserRemoving:v,hasAccess:S,hasAccessFromAPI:C,isSelected:F,selectedUser:I,roleOptions:P,currentUser:o,usersToUpdate:x,handleUserToggle:p,handleRemoveAccess:f,handleUpdateAccess:y,handleUserRoleChange:g},N.id)})]})]})}function ws({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(s.User,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const be=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function mn({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=be().filter(y=>y.value==="VIEWER"||y.value==="EDITOR"||y.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",h=l?l.newRole:m,x=n.role!=="NONE"&&!o&&(!l||l.newRole===m),j=l!==null&&l.newRole!==m,b=o,p=m==="NONE"||!m,g=y=>{switch(y){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(_a,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},f=y=>{r(m,y)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",j&&!b&&!p?"border-orange-300 bg-orange-50":x?"border-green-300 bg-green-50":b||p?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",x&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),j&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(b||p)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:b||p?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(y=>e.jsxs(s.Button,{variant:h===y.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>f(y.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[g(y.value),e.jsx("span",{className:"font-medium",children:y.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:y.description})]},y.value))})]})})]})})}function ut({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=p=>p==="OWNER"?"CONTRIBUTOR":p,h=n?{role:u(n.role)}:{role:"NONE"},x=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,j=(p,g)=>{o(p,g)},b=()=>{c()};return e.jsx(mn,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:j,onRemoveAccess:b,allUsersToUpdate:x,allUsersToRemove:d})}function ze(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=A.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading:d,isError:u}=s.useUnifiedUsers(c),m=s.useResourceShares(r,a);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function hn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var V,K;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),x=s.useShareSelectedUsers(),j=s.useShareUsersToRemove(),b=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),g=s.useShareOrgWideRole(),f=s.useShareManagementActions(),[y,E]=A.useState("specific_users"),T=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},N=()=>{if(i==="tenant"&&d)return d},{allUsers:D,existingShares:v,isLoadingUsers:C}=ze({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:T(),tenantId:N()});A.useEffect(()=>{f.setCurrentContext("org-tab"),f.setCurrentMode(y==="all_users"?"allOrgUsers":"specificOrgUsers")},[f,y]);const S=q=>{var $,X;const Z=q;if(E(Z),r==null||r(Z),f.setCurrentContext("org-tab"),Z==="specific_users")f.setCurrentMode("specificOrgUsers");else if(Z==="all_users"){f.setCurrentMode("allOrgUsers");const _=(X=($=v==null?void 0:v.shares)==null?void 0:$.orgUsersOnly)==null?void 0:X[0];_&&_.role!==void 0&&f.setOrgWideRole(_.role)}},F=D.filter(q=>q.name.toLowerCase().includes(u.toLowerCase())||q.email.toLowerCase().includes(u.toLowerCase())),I=D.filter(q=>x.some(Z=>Z.id===q.id)),P=q=>{var _,G;const Z=x.some(se=>se.id===q),$=j.includes(q),X=(G=(_=v==null?void 0:v.shares)==null?void 0:_.specificOrgUsers)==null?void 0:G.some(se=>se.orgUserId===q);Z?f.removeSelectedUser(q):$?f.removeUserFromRemove(q):X||f.addSelectedUser({id:q,role:"VIEWER"})},k=(q,Z)=>{f.updateSelectedUserRole(q,Z)},w=q=>{f.addUserToRemove(q),f.removeSelectedUser(q)},M=q=>{f.removeUserFromRemove(q)},O=q=>{f.removeUserFromUpdate(q)},R=(q,Z)=>{f.setOrgWideRole(Z)},L=()=>{f.setOrgWideRole((B==null?void 0:B.role)||"NONE")},B=(K=(V=v==null?void 0:v.shares)==null?void 0:V.orgUsersOnly)==null?void 0:K[0];A.useEffect(()=>{y==="all_users"&&B&&B.role!==void 0&&f.setOrgWideRole(B.role)},[y,B,f]);const Y=C,J=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(ws,{shareType:y,onShareTypeChange:S,currentUser:a,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),y==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(ns,{value:u,onChange:m}),e.jsx(rt,{selectedUsers:x,selectedUserObjects:I,onRemove:P,onRoleChange:k,getRoleOptions:be}),e.jsx(lt,{usersToRemove:j,allUsers:F,onRemove:M}),e.jsx(ot,{usersToUpdate:b,allUsers:F,onRemove:O,getRoleOptions:be}),e.jsx(dt,{existingShares:v,isInitialLoading:Y,isSearching:J,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:F,currentUser:a,handleUserToggle:P,handleUserRoleChange:k,handleRemoveAccess:w,handleUpdateAccess:(q,Z,$)=>{f.addUserToUpdate({id:q,currentRole:Z,newRole:$})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(ut,{currentUser:a,currentShare:B,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:R,onRemoveAccess:L,allUsersToUpdate:p==="allOrgUsers"&&g!==((B==null?void 0:B.role)||"NONE")?{currentRole:(B==null?void 0:B.role)||"NONE",newRole:g}:null,allUsersToRemove:p==="allOrgUsers"&&(B==null?void 0:B.role)===void 0})})]}):null}function xn(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function pn(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function mt({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:l,currentUser:o,handleGroupToggle:c,handleGroupRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),j=s.useShareManagementActions(),b=l(o==null?void 0:o.type);return a?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):t.length===0?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No groups available to share with"}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Available Groups"}),e.jsx("div",{className:"max-h-[300px] space-y-2 overflow-y-auto rounded-md border p-3",children:t.map(p=>{const g=n==null?void 0:n.find(v=>v.groupId===p.id),f=m.some(v=>v.id===p.id),y=h.includes(p.id),E=x.find(v=>v.id===p.id),T=!!g&&!y;let D=(g==null?void 0:g.role)||"VIEWER";if(f){const v=m.find(C=>C.id===p.id);D=(v==null?void 0:v.role)||"VIEWER"}else E&&(D=E.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",T&&!y?"border border-green-200 bg-green-50":y?"border border-red-200 bg-red-50":f?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(s.Checkbox,{id:`group-${p.id}`,checked:T?!y:f,disabled:!1,onCheckedChange:()=>{T?y?j.removeGroupFromRemove(p.id):d==null||d(p.id):c==null||c(p.id)}}),e.jsxs("label",{htmlFor:`group-${p.id}`,className:"flex cursor-pointer flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:p.name}),p.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-3 w-3 text-blue-600"}):e.jsx(s.Users,{className:"h-3 w-3 text-green-600"}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[p.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",pn(p.type)),children:xn(p.type)}),p.type==="TENANT_GROUP"&&p.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",p.tenantName]})]}),p.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[T&&!y?e.jsx(Re,{currentRole:D,onRoleChange:v=>{g&&v!==g.role&&(u==null||u(p.id,g.role,v))},roleOptions:b,disabled:!1,allowDropdown:!0,className:E?"border-orange-300 bg-orange-100":""}):f&&!T&&e.jsx(Re,{currentRole:D,onRoleChange:v=>i==null?void 0:i(p.id,v),roleOptions:b,disabled:!1}),T&&!y&&!E&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>d==null?void 0:d(p.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),y&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j.removeGroupFromRemove(p.id),children:"Undo"}),E&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j.removeGroupFromUpdate(p.id),children:"Cancel"})]})]},p.id)})})]})}function ht({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){if(t.length===0)return null;const o=l();return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",t.length,")"]}),e.jsx("div",{className:"space-y-1",children:t.map(c=>{const i=n.find(d=>d.id===c.id);return i?e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/50 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-4 w-4 text-blue-600"}):e.jsx(s.Users,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm font-medium",children:i.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[i.memberCount," members"]}),i.type==="TENANT_GROUP"&&i.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",i.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{currentRole:c.role,onRoleChange:d=>r(c.id,d),roleOptions:o}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(c.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},c.id):null})})]})}function Vs({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var Q;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),j=s.useShareSelectedGroups(),b=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate(),g=s.useShareCurrentMode(),f=s.useShareTenantWideRole(),y=s.useShareAllTenantsRole(),E=s.useShareSelectedTenant(),T=s.useShareManagementActions(),{data:N,isLoading:D}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:v,isLoading:C}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||E),[S,F]=A.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(T.setCurrentContext("tenant-dialog"),T.setCurrentMode("specificTenantUsers")):(T.setCurrentContext("tenant-tab"),T.setCurrentMode("allTenants"))},[T,a==null?void 0:a.type]);const I=U=>{var te,oe,ae,je;F(U);let H;if(U==="specific_tenant_users"?H="specific_users":U==="all_tenant_users"||U==="all_tenants"?H="all_users":U==="groups"?H="groups":H="specific_users",r==null||r(H),U==="groups"?(T.setCurrentContext("group-share"),T.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(T.setCurrentContext("tenant-dialog"),U==="specific_tenant_users"?T.setCurrentMode("specificTenantUsers"):U==="all_tenant_users"&&(T.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&T.setSelectedTenant(a.tenantId))):(T.setCurrentContext("tenant-tab"),U==="specific_tenant_users"?T.setCurrentMode("specificTenantUsers"):U==="all_tenant_users"?T.setCurrentMode("allTenantUsers"):U==="all_tenants"&&T.setCurrentMode("allTenants")),U==="all_tenant_users"){const me=(oe=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:oe[0];me&&me.role!==void 0&&T.setTenantWideRole(me.role)}else if(U==="all_tenants"){const me=(je=(ae=w==null?void 0:w.shares)==null?void 0:ae.allTenantsOnly)==null?void 0:je[0];me&&me.role!==void 0&&T.setAllTenantsRole(me.role)}},P=U=>{T.setSelectedTenant(U)},{allUsers:k,existingShares:w,isLoadingUsers:M,isErrorLoadingUsers:O,isLoadingShares:R,isErrorLoadingShares:L}=ze({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:E}),B=U=>{var ae,je;const H=m.some(me=>me.id===U),te=h.includes(U),oe=(je=(ae=w==null?void 0:w.shares)==null?void 0:ae.specificTenantUsers)==null?void 0:je.some(me=>me.tenantUserId===U);H?T.removeSelectedUser(U):te?T.removeUserFromRemove(U):oe||T.addSelectedUser({id:U,role:"VIEWER"})},Y=(U,H)=>{T.updateSelectedUserRole(U,H)},J=U=>{T.addUserToRemove(U),T.removeSelectedUser(U)},V=U=>{T.removeUserFromRemove(U)},K=U=>{T.removeUserFromUpdate(U)},q=(U,H,te)=>{T.addUserToUpdate({id:U,currentRole:H,newRole:te})},Z=(U,H)=>{S==="all_tenant_users"?T.setTenantWideRole(H):S==="all_tenants"&&T.setAllTenantsRole(H)},$=()=>{S==="all_tenant_users"?T.setTenantWideRole("VIEWER"):S==="all_tenants"&&T.setAllTenantsRole("VIEWER")},_=(()=>{var U,H,te,oe;return g==="allTenants"?(H=(U=w==null?void 0:w.shares)==null?void 0:U.allTenantsOnly)==null?void 0:H[0]:g==="allTenantUsers"?(oe=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:oe[0]:null})();A.useEffect(()=>{var U,H,te,oe;if(S==="all_tenant_users"){const ae=(H=(U=w==null?void 0:w.shares)==null?void 0:U.tenantWide)==null?void 0:H[0];ae&&ae.role!==void 0&&T.setTenantWideRole(ae.role)}else if(S==="all_tenants"){const ae=(oe=(te=w==null?void 0:w.shares)==null?void 0:te.allTenantsOnly)==null?void 0:oe[0];ae&&ae.role!==void 0&&T.setAllTenantsRole(ae.role)}},[S,w,T]);const G=k.filter(U=>m.some(H=>H.id===U.id)),se=U=>{const H=j.some(ae=>ae.id===U),te=b.includes(U),oe=le==null?void 0:le.some(ae=>ae.groupId===U);H?T.removeSelectedGroup(U):te?T.removeGroupFromRemove(U):oe||T.addSelectedGroup({id:U,role:"VIEWER"})},re=(U,H)=>{T.updateSelectedGroupRole(U,H)},he=U=>{T.addGroupToRemove(U),T.removeSelectedGroup(U)},z=(U,H,te)=>{T.addGroupToUpdate({id:U,currentRole:H,newRole:te})},ee=v.filter(U=>j.some(H=>H.id===U.id)),ne=A.useMemo(()=>S!=="groups"?[]:v.filter(U=>U.type!=="TENANT_GROUP"?!1:U.name.toLowerCase().includes(i.toLowerCase())||U.description&&U.description.toLowerCase().includes(i.toLowerCase())),[v,S,i]),le=A.useMemo(()=>{var H,te;const U=((H=w==null?void 0:w.shares)==null?void 0:H.specificGroups)||((te=w==null?void 0:w.shares)==null?void 0:te.groups)||[];return!U||U.length===0?[]:U.filter(oe=>{const ae=v.find(je=>je.id===oe.groupId);return(ae==null?void 0:ae.type)==="TENANT_GROUP"})},[w,v]),de=M||R||S==="groups"&&C,xe=O||L,pe=()=>(a==null?void 0:a.type)==="tenant"||S==="all_tenants"||S==="groups"?!0:E&&(S==="specific_tenant_users"||S==="all_tenant_users");return e.jsxs(e.Fragment,{children:[xe&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s.CircleAlert,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),e.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!xe&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(ws,{shareType:S,onShareTypeChange:I,currentUser:a,options:(a==null?void 0:a.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(Ps,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.type)==="organization"&&(S==="specific_tenant_users"||S==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:E||"",onValueChange:P,disabled:D,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:D?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(Q=N==null?void 0:N.tenants)==null?void 0:Q.map(U=>e.jsx(s.SelectItem,{value:U.id,children:U.name},U.id))})]})]}),pe()?e.jsx(e.Fragment,{children:S==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ns,{value:i,onChange:u}),e.jsx(rt,{selectedUsers:m,selectedUserObjects:G,onRemove:U=>B(U),onRoleChange:Y,getRoleOptions:be}),e.jsx(lt,{usersToRemove:h,allUsers:k,onRemove:V}),e.jsx(ot,{usersToUpdate:x,allUsers:k,onRemove:K,getRoleOptions:be}),e.jsx(dt,{existingShares:w,isInitialLoading:!!de,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:k,currentUser:a,handleUserToggle:B,handleUserRoleChange:Y,handleRemoveAccess:J,handleUpdateAccess:q})]}):S==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ns,{value:i,onChange:u,placeholder:"Search groups..."}),e.jsx(ht,{selectedGroups:j,groupObjects:ee,onRemove:se,onRoleChange:re,getRoleOptions:be}),b.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",b.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),p.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",p.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(mt,{groups:ne,existingGroupShares:le,isLoading:C,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:se,handleGroupRoleChange:re,handleRemoveAccess:he,handleUpdateAccess:z})]}):S==="all_tenant_users"||S==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(ut,{currentUser:a,currentShare:_,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:Z,onRemoveAccess:$,allUsersToUpdate:g==="allTenantUsers"&&((_==null?void 0:_.role)===void 0||f!==_.role)||g==="allTenants"&&((_==null?void 0:_.role)===void 0||y!==_.role)?{currentRole:(_==null?void 0:_.role)||"VIEWER",newRole:g==="allTenantUsers"?f:y}:null,allUsersToRemove:g==="allTenantUsers"&&(_==null?void 0:_.role)===void 0||g==="allTenants"&&(_==null?void 0:_.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(S==="specific_tenant_users"||S==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ps,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}function fn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var O,R;const{searchQuery:i,setSearchQuery:d}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),x=s.useShareManagementActions(),[j,b]=A.useState("org_groups"),[p,g]=A.useState(""),{data:f,isLoading:y}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&j==="tenant_groups"}),E=Array.isArray(f)?f:(f==null?void 0:f.tenants)||[],T=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:N,isLoading:D}=s.useShareableGroups(T(),j==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?p:a==null?void 0:a.tenantId),{existingShares:v}=ze({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),C=N.filter(L=>j==="org_groups"&&L.type!=="ORG_GROUP"||j==="tenant_groups"&&L.type!=="TENANT_GROUP"||j==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!p||L.tenantId&&L.tenantId!==p)?!1:L.name.toLowerCase().includes(i.toLowerCase())||L.description&&L.description.toLowerCase().includes(i.toLowerCase())),S=((O=v==null?void 0:v.shares)==null?void 0:O.specificGroups)||((R=v==null?void 0:v.shares)==null?void 0:R.groups)||[];A.useEffect(()=>{x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},[x]);const F=L=>{const B=L;b(B),B==="org_groups"&&g(""),r==null||r(B==="org_groups"?"specific_groups":"all_groups"),x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},I=N.filter(L=>u.some(B=>B.id===L.id)),P=L=>{const B=u.some(V=>V.id===L),Y=m.includes(L),J=S==null?void 0:S.some(V=>V.groupId===L);B?x.removeSelectedGroup(L):Y?x.removeGroupFromRemove(L):J||x.addSelectedGroup({id:L,role:"VIEWER"})},k=(L,B)=>{x.updateSelectedGroupRole(L,B)},w=L=>{x.addGroupToRemove(L),x.removeSelectedGroup(L)},M=(L,B,Y)=>{x.addGroupToUpdate({id:L,currentRole:B,newRole:Y})};return a?e.jsxs(e.Fragment,{children:[e.jsx(ws,{shareType:j,onShareTypeChange:F,currentUser:a,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:e.jsx(s.Building2,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"tenant_groups",label:"Tenant Groups",description:"Share with tenant-level groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]}),j==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(s.Label,{children:"Select Tenant"}),e.jsxs(s.Select,{value:p,onValueChange:g,disabled:y,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:y?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:E.map(L=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:L.id,children:L.name},L.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:j==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!p?e.jsx("div",{className:"rounded-md border border-dashed p-6 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant above to view and share with its groups"})}):e.jsxs(e.Fragment,{children:[e.jsx(ns,{value:i,onChange:d,placeholder:"Search groups..."}),e.jsx(ht,{selectedGroups:u,groupObjects:I,onRemove:P,onRoleChange:k,getRoleOptions:be}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",m.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",h.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(mt,{groups:C,existingGroupShares:S,isLoading:D,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:P,handleGroupRoleChange:k,handleRemoveAccess:w,handleUpdateAccess:M})]})})]}):null}const xt=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedGroups(),c=s.useShareGroupsToRemove(),i=s.useShareGroupsToUpdate(),d=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),h=s.useShareTenantWideRole(),x=s.useShareGroupWideRole(),j=A.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedGroups:o,groupsToRemove:c,groupsToUpdate:i,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}),[t,n,a,r,l,o,c,i,d,u,m,h,x]),b=A.useMemo(()=>g=>s.validateShareData(g),[]),p=A.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!d)return!1}else if(n==="specificTenantUsers")return d?a.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||l.length>0:!0;case"group-share":return n==="specificGroups"?o.length>0||c.length>0||i.length>0:!0}return!1},[t,n,a,r,l,o,c,i,d]);return{buildShareData:j,validateShareData:b,isCurrentStateValid:p,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}};function _s({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),j=s.useShareSelectedTenant(),b=s.useShareOrgWideRole(),p=s.useShareAllTenantsRole(),g=s.useShareTenantWideRole(),{buildShareData:f,validateShareData:y,isCurrentStateValid:E}=xt(),T=a||r||l,N=()=>{var F,I,P,k;if(T)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const w=m.length+h.length+x.length;return w===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${w} user${w!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&x.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Update access for ${x.length} user${x.length!==1?"s":""}`:`Update access for ${w} user${w!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const w=d.role;return b===w?"Remove Access":"Update Access"}else if(i==="all_tenants"){const w=(I=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:I[0];if(!w||w.role===void 0)return"Share with All Tenants";const M=w.role;return p===M?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const w=(k=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:k[0];if(!w||w.role===void 0)return"Share with All Tenant Users";const M=w.role;return g===M?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const w=m.length+h.length+x.length;return w===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${w} user${w!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&x.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Update access for ${x.length} user${x.length!==1?"s":""}`:`Update access for ${w} user${w!==1?"s":""}`}return"Share"},D=()=>T||!t||i==="all_tenant_users"&&!j||i==="specific_tenant_users"&&!j?!0:!E,v=()=>{const F=f();F&&y(F)&&o(F)},C=()=>{var F,I,P,k;if(i==="all_users")if(!d||d.role===void 0){const w=f();w&&y(w)&&o(w)}else{const w=d.role;if(b===w)u==null||u();else{const O=f();if(O&&y(O)){const R={...O,updateAccess:!0};o(R)}}}else if(i==="all_tenants"){const w=(I=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:I[0];if(!w||w.role===void 0){const M=f();M&&y(M)&&o(M)}else{const M=w.role;if(p===M)u==null||u();else{const R=f();if(R&&y(R)){const L={...R,updateAccess:!0};o(L)}}}}else if(i==="all_tenant_users"){const w=(k=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:k[0];if(!w||w.role===void 0){const M=f();M&&y(M)&&o(M)}else{const M=w.role;if(g===M)u==null||u();else{const R=f();if(R&&y(R)){const L={...R,updateAccess:!0};o(L)}}}}},S=()=>{var F,I,P,k;if(i==="all_users"){if(!d||d.role===void 0)return"default";const w=d.role;return b===w?"destructive":"default"}else if(i==="all_tenants"){const w=(I=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:I[0];if(!w||w.role===void 0)return"default";const M=w.role;return p===M?"destructive":"default"}else if(i==="all_tenant_users"){const w=(k=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:k[0];if(!w||w.role===void 0)return"default";const M=w.role;return g===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:T,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||x.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||T,variant:"default",children:[T?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!T&&N()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:C,disabled:D(),variant:S(),children:[T?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),!T&&N()]})]})}function gn({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),h=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),j=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const b=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:g,isCurrentStateValid:f}=xt(),y=n||a||r,E=()=>{if(y)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const S=d.length+u.length+m.length;return S===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${S} user${S!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${S} user${S!==1?"s":""}`}else if(c==="groups"){if(h.length===0&&x.length===0&&j.length===0)return"Select groups to share with";const S=h.length+x.length+j.length;return S===0?"Select groups to share with":h.length>0&&x.length>0?`Update access for ${S} group${S!==1?"s":""}`:x.length>0&&h.length===0&&j.length===0?`Remove access for ${x.length} group${x.length!==1?"s":""}`:h.length>0&&x.length===0&&j.length===0?`Share with ${h.length} group${h.length!==1?"s":""}`:j.length>0&&h.length===0&&x.length===0?`Update access for ${j.length} group${j.length!==1?"s":""}`:`Update access for ${S} group${S!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const S=i.role;return b===S?"Remove Access":"Update Access"}return"Share"},T=()=>y||!t?!0:!f,N=()=>{const S=p();S&&g(S)&&l(S)},D=()=>{const S=p();S&&g(S)&&l(S)},v=()=>{if(!i||i.role==="NONE"){const S=p();S&&g(S)&&l(S)}else{const S=i.role;if(b===S){const I=p();if(I&&g(I)){const P={...I,removeAccess:!0};l(P)}}else{const I=p();if(I&&g(I)){const P={...I,updateAccess:!0};l(P)}}}},C=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:y,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:N,disabled:!t||y,variant:"default",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!y&&E()]})}),c==="groups"&&e.jsx(e.Fragment,{children:(h.length>0||x.length>0||j.length>0)&&e.jsxs(s.Button,{onClick:D,disabled:!t||y,variant:"default",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!y&&E()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:v,disabled:T(),variant:C(),children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!y&&E()]})]})}function jn({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllGroupsShare:d,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const j=()=>{o({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:h,groupsToUpdate:x})},b=()=>m.length>0||h.length>0||x.length>0,p=()=>h.length>0&&m.length===0&&x.length===0?"Remove Access":x.length>0&&m.length===0&&h.length===0?"Update Access":"Share with Groups",g=a||r||l;return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[m.length>0&&e.jsxs("span",{children:[m.length," groups selected"]}),h.length>0&&e.jsxs("span",{className:"ml-2 text-destructive",children:["• ",h.length," to remove"]}),x.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",x.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:g,children:"Cancel"}),e.jsxs(s.Button,{onClick:j,disabled:!b()||g,children:[g&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),p()]})]})]})}function ge(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Se(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function bn(t,n,a){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=ge(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const x=ge(r,l,u.map(j=>({scope:"specific_org_user",orgUserId:j.id,role:j.role})));o(x,{onSuccess:()=>{d()}})}if(m&&m.length>0){const x=Se(r,l,m.map(j=>{var p,g;const b=(g=(p=i==null?void 0:i.shares)==null?void 0:p.specificOrgUsers)==null?void 0:g.find(f=>f.orgUserId===j);return{scope:"specific_org_user",orgUserId:j,role:(b==null?void 0:b.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(x=>{const j=ge(r,l,[{scope:"specific_org_user",orgUserId:x.id,role:x.newRole}]);o(j,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=ge(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=ge(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:x}=t;if(m&&m.length>0){const j=Se(r,l,m.map(b=>{var g,f;const p=(f=(g=i==null?void 0:i.shares)==null?void 0:g.specificTenantUsers)==null?void 0:f.find(y=>y.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,tenantId:x,role:(p==null?void 0:p.role)||"VIEWER"}}));c(j,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(j=>{const b=ge(r,l,[{scope:"specific_tenant_user",tenantUserId:j.id,tenantId:x,role:j.newRole}]);o(b,{onSuccess:()=>{d()}})}),u&&u.length>0){const j=ge(r,l,u.map(b=>({scope:"specific_tenant_user",tenantUserId:b.id,tenantId:x,role:b.role})));o(j,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=Se(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=ge(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=ge(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const x=ge(r,l,u.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,role:j.role})));o(x,{onSuccess:()=>{d()}})}if(m&&m.length>0){const x=Se(r,l,m.map(j=>{var p,g;const b=(g=(p=i==null?void 0:i.shares)==null?void 0:p.specificTenantUsers)==null?void 0:g.find(f=>f.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,role:(b==null?void 0:b.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(x=>{const j=ge(r,l,[{scope:"specific_tenant_user",tenantUserId:x.id,role:x.newRole}]);o(j,{onSuccess:()=>{d()}})})}break;case"group-share":if(t.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:m,groupsToUpdate:h}=t;if(u&&u.length>0){const x=ge(r,l,u.map(j=>({scope:"group",groupId:j.id,role:j.role})));o(x,{onSuccess:()=>{var j;d(),(j=n.resetGroupSelections)==null||j.call(n),s.ue.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(m&&m.length>0){const x=Se(r,l,m.map(j=>({scope:"group",groupId:j,role:"VIEWER"})));c(x,{onSuccess:()=>{var j;d(),(j=n.resetGroupSelections)==null||j.call(n),s.ue.success(`Removed access from ${m.length} group${m.length!==1?"s":""}`)}})}h&&h.length>0&&h.forEach(x=>{const j=ge(r,l,[{scope:"group",groupId:x.id,role:x.newRole}]);o(j,{onSuccess:()=>{var b;d(),(b=n.resetGroupSelections)==null||b.call(n),s.ue.success("Updated access for group")}})})}break}}function vn(t,n,a,r){var u,m,h,x,j,b;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const p=Se(l,o,t.map(g=>{var y,E;const f=(E=(y=i==null?void 0:i.shares)==null?void 0:y.specificTenantUsers)==null?void 0:E.find(T=>T.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(f==null?void 0:f.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()},onError:g=>{console.error("Remove access failed:",g)}})}else{const p=n==="tenant"&&a==="allTenants",g=n==="tenant"&&a==="allTenantUsers";if(p){const f=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(f){const y=Se(l,o,[{scope:"all_tenants_only",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove all-tenants access failed:",E)}})}}else if(g){const f=(x=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:x[0];if(f){const y=Se(l,o,[{scope:"all_tenant_users",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove all-tenant-users access failed:",E)}})}}else{const f=(b=(j=i==null?void 0:i.shares)==null?void 0:j.orgUsersOnly)==null?void 0:b[0];if(f){const y=Se(l,o,[{scope:"org_users_only",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove org-wide access failed:",E)}})}}}}function yn(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=ze({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=A.useCallback(()=>{r.resetUserSelections()},[r]),m=A.useCallback(()=>{r.resetGroupSelections()},[r]),h=A.useCallback(j=>{if(!t)return;const b={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:u,resetGroupSelections:m};bn(j,b,i)},[t,n,a,d,u,m,i]),x=A.useCallback(()=>{if(!t)return;const j={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:u};vn(l,o||"",c||"",j)},[t,n,a,d,u,m,l,o,c]);return{handleShareSubmit:h,handleRemoveAccess:x}}function is({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var k,w,M,O,R,L,B,Y;const{currentUser:o}=s.useCurrentUserInfo(),[c,i]=A.useState("specific_users"),[d,u]=A.useState("specific_users"),[m,h]=A.useState("specific_groups"),x=s.useShareManagementActions(),j=s.useShareSelectedTab(),b=s.useShareCurrentMode(),p=s.useShareResource(),g=s.useRemoveResourceShares(),{handleShareSubmit:f,handleRemoveAccess:y}=yn(t.id,(J,V)=>{p.mutate(J,{...V,onSuccess:()=>{var K;(K=V==null?void 0:V.onSuccess)==null||K.call(V),r==null||r()}})},(J,V)=>{g.mutate(J,{...V,onSuccess:()=>{var K;(K=V==null?void 0:V.onSuccess)==null||K.call(V),l==null||l()}})}),E=p.isPending,T=g.isPending,N=p.isPending,{existingShares:D}=ze({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:v}=ze({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),C=(w=(k=D==null?void 0:D.shares)==null?void 0:k.tenantWide)==null?void 0:w[0],S=(O=(M=v==null?void 0:v.shares)==null?void 0:M.orgUsersOnly)==null?void 0:O[0],F=()=>{if(j==="org")return d;switch(b){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},I=A.useCallback(()=>{x.resetShareState(),a()},[x,a]),P=(o==null?void 0:o.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:I,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:P?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),P?e.jsxs(s.Tabs,{value:j,onValueChange:J=>{const V=J;x.setSelectedTab(V),x.resetUserSelections(),x.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-3",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"}),e.jsx(s.TabsTrigger,{value:"groups",children:"Groups"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(hn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:u,isSharing:E,isUpdating:N,isRemoving:T})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Vs,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:J=>i(J),isSharing:E,isUpdating:N,isRemoving:T})})}),e.jsx(s.TabsContent,{value:"groups",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(fn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:h,isSharing:E,isUpdating:N,isRemoving:T})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Vs,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:J=>i(J),isSharing:E,isUpdating:N,isRemoving:T})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:P?j==="org"?e.jsx(_s,{resource:t,existingShares:v,isSharing:E,isRemoving:T,isUpdating:N,onShare:f,onClose:a,shareTabType:d,currentAllUsersShare:S,onRemoveAccess:y}):j==="tenant"?e.jsx(_s,{resource:t,existingShares:D,isSharing:E,isRemoving:T,isUpdating:N,onShare:f,onClose:a,shareTabType:F(),currentAllUsersShare:C,onRemoveAccess:y}):e.jsx(jn,{resource:t,existingShares:v,isSharing:E,isRemoving:T,isUpdating:N,onShare:f,onClose:a,shareTabType:m,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(L=(R=v==null?void 0:v.shares)==null?void 0:R.allOrgGroups)==null?void 0:L[0]:(Y=(B=D==null?void 0:D.shares)==null?void 0:B.allTenantGroups)==null?void 0:Y[0],onRemoveAccess:y}):e.jsx(gn,{resource:t,isSharing:E,isRemoving:T,isUpdating:N,onShare:f,onClose:a,shareTabType:c,currentAllUsersShare:C,onRemoveAccess:y})})]})})}function pt({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(u=>u.selectedFrameId),l=s.useManagementStore(u=>u.selectedVisual),o=s.useEditorStore(u=>u.frame);let c;if(t)c=t;else if(n!==void 0)c=n?"linked":"library";else if(!!!(o!=null&&o.visualId||l!=null&&l.id)&&r)c="local";else if(l&&!r)c="library";else if(o!=null&&o.visualId&&r)c="linked";else if(l!=null&&l.id&&r)c="library";else return null;const i={local:"bg-gray-100 text-gray-700",linked:"bg-purple-100 text-purple-700",library:"bg-blue-100 text-blue-700"},d={local:"Local Visual",linked:"Linked Visual",library:"Library Visual"};return e.jsx("span",{className:s.cn("rounded-full px-2.5 py-0.5 text-xs font-medium",i[c],a),children:d[c]})}const Nn=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},Cn=async(t,n,a)=>{const r=`${t}/management/v1/groups/${a}`,l=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!l.ok){const o=await l.text();throw new Error(o||"Failed to delete group")}},Sn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},wn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,o=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.text();throw new Error(c||"Failed to remove group members")}};function Dn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Nn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:()=>{a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Group created successfully")},onError:r=>{console.error("Failed to create group:",r),s.ue.error("Failed to create group",{description:r.message})}})}function Tn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Cn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["groups"]}),a.removeQueries({queryKey:["group",l]}),s.ue.success("Group deleted successfully")},onError:r=>{console.error("Failed to delete group:",r),s.ue.error("Failed to delete group",{description:r.message})}})}function kn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Sn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members added successfully")},onError:r=>{console.error("Failed to add group members:",r),s.ue.error("Failed to add members",{description:r.message})}})}function En(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>wn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members removed successfully")},onError:r=>{console.error("Failed to remove group members:",r),s.ue.error("Failed to remove members",{description:r.message})}})}function In({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=A.useState(""),[o,c]=A.useState(""),[i,d]=A.useState({}),u=Dn(),m=()=>{const x={};return r.trim()?r.length<3?x.name="Group name must be at least 3 characters":r.length>50&&(x.name="Group name must be less than 50 characters"):x.name="Group name is required",o&&o.length>200&&(x.description="Description must be less than 200 characters"),d(x),Object.keys(x).length===0},h=async x=>{if(x.preventDefault(),!m())return;const j={name:r.trim(),description:o.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(j),l(""),c(""),d({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:h,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-name",children:["Group Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(s.Input,{id:"group-name",placeholder:"e.g., Marketing Team, Engineering Squad",value:r,onChange:x=>{l(x.target.value),i.name&&d(j=>({...j,name:""}))},className:i.name?"border-destructive":"",disabled:u.isPending}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-description",children:["Description",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(optional)"})]}),e.jsx(s.Textarea,{id:"group-description",placeholder:"Describe the purpose of this group...",value:o,onChange:x=>{c(x.target.value),i.description&&d(j=>({...j,description:""}))},className:i.description?"border-destructive":"",disabled:u.isPending,rows:3}),i.description&&e.jsx("p",{className:"text-sm text-destructive",children:i.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.length,"/200 characters"]})]}),e.jsx("div",{className:"rounded-lg border bg-muted/50 p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This group will be accessible to users in your workspace. You can add members after creating the group."})]})})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(s.Button,{type:"button",variant:"outline",onClick:()=>{l(""),c(""),d({})},disabled:u.isPending,children:"Clear"}),e.jsx(s.Button,{type:"submit",disabled:u.isPending||!r.trim(),children:u.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),"Create Group"]})})]})]})}function An({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,o]=A.useState("members"),[c,i]=A.useState(""),[d,u]=A.useState([]),[m,h]=A.useState([]),{data:x,isLoading:j,refetch:b}=s.useGroupMembers(a.id),p=a.type==="TENANT_GROUP"?"tenant":"organization",{users:g,isLoading:f}=s.useUnifiedUsers({type:p,tenantId:a.tenantId||void 0,active:!0,limit:100}),y=kn(),E=En(),T=(x==null?void 0:x.members)||[],N=A.useMemo(()=>new Set(T.map(k=>k.userId)),[T]),D=A.useMemo(()=>g.filter(k=>!N.has(k.id)),[g,N]),v=A.useMemo(()=>{if(!c)return D;const k=c.toLowerCase();return D.filter(w=>{var M,O;return((M=w.name)==null?void 0:M.toLowerCase().includes(k))||((O=w.email)==null?void 0:O.toLowerCase().includes(k))})},[D,c]),C=A.useMemo(()=>{if(!c)return T;const k=c.toLowerCase();return T.filter(w=>{var M,O,R,L;return((O=(M=w.user)==null?void 0:M.name)==null?void 0:O.toLowerCase().includes(k))||((L=(R=w.user)==null?void 0:R.email)==null?void 0:L.toLowerCase().includes(k))})},[T,c]),S=async()=>{if(d.length!==0)try{await y.mutateAsync({groupId:a.id,data:{userIds:d,userType:p==="tenant"?"tenant":"org"}}),u([]),o("members"),b(),r==null||r()}catch(k){console.error("Failed to add members:",k)}},F=async()=>{if(m.length!==0)try{await E.mutateAsync({groupId:a.id,data:{userIds:m}}),h([]),b(),r==null||r()}catch(k){console.error("Failed to remove members:",k)}},I=k=>{u(w=>w.includes(k)?w.filter(M=>M!==k):[...w,k])},P=k=>{h(w=>w.includes(k)?w.filter(M=>M!==k):[...w,k])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:a.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[T.length," ",T.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",a.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:k=>{o(k),i(""),h([])},className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"members",children:"Current Members"}),e.jsx(s.TabsTrigger,{value:"add",children:"Add Members"})]}),e.jsxs(s.TabsContent,{value:"members",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search members...",value:c,onChange:k=>i(k.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:j?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(k=>e.jsx(s.Skeleton,{className:"h-16 w-full"},k))}):C.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:c?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:C.map(k=>e.jsx(Mn,{member:k,selected:m.includes(k.userId),onToggle:()=>P(k.userId)},k.id))})}),m.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m.length," member",m.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:F,disabled:E.isPending,children:E.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Removing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove Selected"]})})]})]}),e.jsxs(s.TabsContent,{value:"add",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search users to add...",value:c,onChange:k=>i(k.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:f?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(k=>e.jsx(s.Skeleton,{className:"h-16 w-full"},k))}):v.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.UserPlus,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No available users"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:v.map(k=>e.jsx(Ln,{user:k,selected:d.includes(k.id),onToggle:()=>I(k.id)},k.id))})}),d.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[d.length," user",d.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:S,disabled:y.isPending,children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.UserPlus,{className:"mr-2 h-4 w-4"}),"Add Members"]})})]})]})]})]})})})}function Mn({member:t,selected:n,onToggle:a}){var l,o,c,i;const r=((o=(l=t.user)==null?void 0:l.name)==null?void 0:o.split(" ").map(d=>d[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:((c=t.user)==null?void 0:c.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(i=t.user)==null?void 0:i.email})]})]})}function Ln({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(o=>o[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.email})]})]})}function Rn({open:t,onOpenChange:n}){const[a,r]=A.useState("groups"),[l,o]=A.useState(""),[c,i]=A.useState(null),[d,u]=A.useState(!1),[m,h]=A.useState(null),{tokenProps:x}=s.useSemaphorContext(),{currentUser:j}=s.useCurrentUserInfo(),b=Tn(),p=(j==null?void 0:j.type)==="tenant",g=x==null?void 0:x.tenantId,{groups:f,isLoading:y,refetch:E}=s.useGroups({type:p?"TENANT_GROUP":"all",tenantId:p?g:void 0,includeMembers:!1}),T=f.filter(C=>{var S;return C.name.toLowerCase().includes(l.toLowerCase())||((S=C.description)==null?void 0:S.toLowerCase().includes(l.toLowerCase()))}),N=async()=>{if(m)try{await b.mutateAsync(m.id),h(null),E()}catch(C){console.error("Failed to delete group:",C)}},D=C=>{i(C),u(!0)},v=()=>{r("groups"),E()};return e.jsxs(e.Fragment,{children:[e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-4xl max-h-[80vh]",children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Group Management"]}),e.jsx(s.DialogDescription,{children:"Manage your groups, create new groups, and control group membership"})]}),e.jsxs(s.Tabs,{value:a,onValueChange:r,className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsxs(s.TabsTrigger,{value:"groups",className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4"}),"Groups"]}),e.jsxs(s.TabsTrigger,{value:"create",className:"flex items-center gap-2",children:[e.jsx(s.Plus,{className:"h-4 w-4"}),"Create Group"]})]}),e.jsx(s.TabsContent,{value:"groups",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search groups...",value:l,onChange:C=>o(C.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:y?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(C=>e.jsx(s.Skeleton,{className:"h-24 w-full"},C))}):T.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No groups found"}),e.jsx("p",{className:"text-xs mt-1",children:l?"Try a different search":"Create your first group to get started"})]}):e.jsx("div",{className:"space-y-3",children:T.map(C=>e.jsx(On,{group:C,onManageMembers:()=>D(C),onDelete:()=>h(C),currentUserId:j==null?void 0:j.id},C.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(In,{onSuccess:v,tenantId:g,isTenantUser:p})})]})]})}),c&&e.jsx(An,{open:d,onOpenChange:u,group:c,onUpdate:()=>E()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>h(null),children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Group"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.name,'"? This action cannot be undone and will remove all members from the group.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:N,disabled:b.isPending,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete Group"})]})]})})]})}function On({group:t,onManageMembers:n,onDelete:a,currentUserId:r}){const l=t.createdBy===r;return e.jsx("div",{className:"rounded-lg border bg-card p-4 transition-colors hover:bg-muted/50",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:t.name}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:t.description})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(s.Users,{className:"h-3 w-3"}),t.memberCount," ",t.memberCount===1?"member":"members"]}),e.jsxs("span",{children:["Created ",s.format(new Date(t.createdAt),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:n,title:"Manage members",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:a,title:"Delete group",className:"text-destructive hover:text-destructive",children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]})})}function Ds(t){const[n,a]=A.useState(null),[r,l]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),a(null)}})()},[t]),n}function Fn(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Pn(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return n}}return t[0].id}async function Us(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],o=r.getQueryData(l);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const c=s.ue.loading("Loading visual...",{position:"top-center"});try{const i=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!i.ok)throw new Error("Failed to load visual");const d=await i.json();return r.setQueryData(l,d),s.ue.dismiss(c),{data:d,fromCache:!1}}catch(i){throw s.ue.dismiss(c),i}}function ft(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function Bn(t,n){var o,c;const a=(t==null?void 0:t.frameObject)??((o=t==null?void 0:t.visual)==null?void 0:o.frameObject);if(!a)return!1;const r=ft(a);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(c=r.cards)==null?void 0:c.find(i=>i.id===r.activeCardId);return l?(s.setupEditorWithCard({...n,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function zn(){var x;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(j=>j.frame),a=s.useEditorStore(j=>j.card),r=Ds(((x=a.customCardPreferences)==null?void 0:x.url)||""),l=s.useEditorStore(j=>j.selectedSchemaName),o=s.useEditorStore(j=>j.selectedDatamodelId),c=s.useEditorStore(j=>j.selectedDatabaseName),i=s.useEditorStore(j=>j.selectedTableName),d=s.useEditorStore(j=>j.selectedConnectionId),u=s.useEditorStore(j=>j.isShowingVisual),m=a.sql;return{getUpdatedFrame:A.useCallback(()=>{var f;let j=m;m&&!m.includes("{{")&&(j=Fn(m),t(j));const b=(f=r==null?void 0:r.getState())==null?void 0:f.settings,p={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:j,customCfg:u?a.customCfg:null,preferences:a.preferences,...b&&{customCardPreferences:{...a.customCardPreferences,settings:b}}},g=n.cards.map(y=>y.id===a.id?p:y);return{...n,cards:g,activeCardId:Pn(g,n.activeCardId)}},[a,n,u,l,o,c,i,d,t,r,m])}}function _e(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:j,setSelectedTableName:b,setSelectedDatamodelId:p,setFilterValues:g,setApplyFilters:f}=s.useEditorActions(),{setIsDashboardEditing:y,setIsVisualEditing:E,setSelectedFrameId:T,clearSelectedFrameId:N,addFrame:D,setIsDashboardPanelOpen:v}=s.useDashboardActions(),C=s.useDashboardStore(M=>M.selectedSheetId),S=s.useDashboardStore(M=>M.selectedFrameId),F=s.useDashboardStore(M=>M.dashboard),I=s.useDashboardStore(M=>M.filterValues),P=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),k=A.useCallback(async M=>{try{l(M),N();const{data:O,fromCache:R}=await Us(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a);if(!Bn(O,{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:j,setSelectedTableName:b,setSelectedDatamodelId:p,setFilterValues:g,setApplyFilters:f,setIsDashboardEditing:y,setIsVisualEditing:E,dashboard:F,selectedSheetId:C,selectedFrameId:S,filterValues:I}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:R}}catch(O){return console.error("Error editing visual:",O),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,o,c,y,E,i,d,u,m,h,x,j,b,p,g,f,N,F,C,S,I]),w=A.useCallback(async M=>{var O;try{if(l(M),!C)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:R,fromCache:L}=await Us(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a),B=(R==null?void 0:R.frameObject)??((O=R==null?void 0:R.visual)==null?void 0:O.frameObject);if(!B)return{success:!1,error:"Visual has no frame data"};const Y=ft(B);if(!(Y!=null&&Y.cards)||Y.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const J={...Y,id:s.v4(),visualId:M.id};return D(C,J,"end"),y(!0),T(J.id),v(!1),{success:!0,fromCache:L}}catch(R){return console.error("Error adding visual:",R),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,C,D,y,T,v]);return{visual:P.data,isLoading:P.isLoading,isError:P.isError,error:P.error,handleEditLibraryVisual:k,handleAddLibraryVisual:w,getUpdatedFrame:zn().getUpdatedFrame,refetch:P.refetch}}function Vn({open:t,onOpenChange:n,isLibraryVisual:a,currentVisualName:r,isSaving:l=!1,onConfirm:o}){const[c,i]=A.useState(a&&r?`Copy of ${r}`:r||""),[d,u]=A.useState(""),[m,h]=A.useState(!a),[x,j]=A.useState(!0);A.useEffect(()=>{t&&(i(a&&r?`Copy of ${r}`:r||""),u(""),h(!a),j(!0))},[t,a,r]);const b=()=>{c.trim()&&(!m&&!x||o({name:c.trim(),description:d.trim()||void 0,saveToLibrary:m,saveToCurrentDashboard:x}))},p=c.trim()&&(m||x);return e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Save Visual As"}),e.jsx(s.DialogDescription,{children:a?"Create a copy of this visual with a new name":"Save this visual to make it reusable"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:c,onChange:g=>i(g.target.value),placeholder:"Enter visual name",disabled:l})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Textarea,{id:"description",value:d,onChange:g=>u(g.target.value),placeholder:"Enter visual description",rows:3,disabled:l})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Label,{children:"Save to:"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-dashboard",checked:x,onCheckedChange:g=>j(!!g),disabled:l}),e.jsxs("label",{htmlFor:"save-to-dashboard",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Current Dashboard",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(add copy to this dashboard)":"(keep as local visual)"})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-library",checked:m,onCheckedChange:g=>h(!!g),disabled:l}),e.jsxs("label",{htmlFor:"save-to-library",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Visual Library",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!m&&!x&&e.jsx("p",{className:"text-sm text-destructive",children:"Please select at least one destination"})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),disabled:l,children:"Cancel"}),e.jsxs(s.Button,{onClick:b,disabled:!p||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function gt({className:t,variant:n="outline"}){var i;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(d=>d.frame);const r=s.useEditorStore(d=>d.card);Ds(((i=r.customCardPreferences)==null?void 0:i.url)||""),s.useEditorStore(d=>d.selectedSchemaName),s.useEditorStore(d=>d.selectedDatamodelId),s.useEditorStore(d=>d.selectedDatabaseName),s.useEditorStore(d=>d.selectedTableName),s.useEditorStore(d=>d.selectedConnectionId),s.useEditorStore(d=>d.isShowingVisual),r.sql;const l=s.useEditorStore(d=>d.onSave),{getUpdatedFrame:o}=_e();function c(){const d=o();l==null||l(d)}return e.jsxs(s.Button,{onClick:c,className:s.cn("h-8",t),size:"sm",variant:n,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function _n({className:t}){const n=s.useQueryClient(),[a,r]=A.useState(!1),l=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:c}=_e(),i=s.useSelectedVisual(),d=s.useEditorStore(h=>h.frame),u=s.useUpdateVisualMutation(),m=()=>{const h=c(),x=(d==null?void 0:d.visualId)||(i==null?void 0:i.id);if(!x){s.ue.error("No visual to save");return}r(!0),u.mutate({visualId:x,data:{frameObject:h}},{onSuccess:()=>{r(!1),l(!0),s.ue.success("Visual updated successfully"),n.invalidateQueries({queryKey:["resource-by-id","visual",x],exact:!0})},onError:()=>{r(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:m,className:s.cn("h-8",t),size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"mr-2 size-4 font-bold"}),"Save to Library"]})]})}function Un({className:t}){const{getUpdatedFrame:n}=_e();s.useEditorStore(d=>d.frame);const a=s.useDashboardStore(d=>d.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[o,c]=A.useState(!1),i=()=>{if(!a){s.ue.error("No sheet selected");return}c(!0);const u={...n(),visualId:void 0};r(a,u),setTimeout(()=>{c(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:i,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function jt({className:t}){const{setTempQueryData:n,setSqlGen:a}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),o=s.useEditorStore(u=>u.onClose),c=s.useEditorStore(u=>u.card),{queryKey:i}=s.useDashboardCardQuery(c);function d(){if(l){const{queryKey:u,queryData:m}=l;u&&m&&r.setQueryData(u,m)}a({}),o==null||o()}return e.jsxs(s.Button,{onClick:d,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function cs(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(g=>g.isDevMode),r=s.useEditorStore(g=>g.tempQueryData),l=s.useEditorStore(g=>g.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:x,setCardConfig:j,setCardType:b}=s.useEditorActions();function p(){const g=n.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:g}),n.setQueryData(o,null),n.removeQueries({queryKey:o,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),x(),j(void 0),d(""),u(""),m({}),b("bar")}return e.jsxs(s.Button,{onClick:p,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Gn(){const[t,n]=A.useState(!1),[a,r]=A.useState(!1),[l,o]=A.useState(null),c=s.useEditorStore(T=>T.frame),i=s.useEditorStore(T=>T.card),d=s.useSelectedVisual(),u=s.useDashboardStore(T=>T.selectedSheetId),m=s.useDashboardStore(T=>T.actions.setIsDashboardPanelOpen),{getUpdatedFrame:h}=_e(),{selectVisual:x}=s.useManagementActions(),{addFrame:j,setSelectedFrameId:b,setIsVisualEditing:p}=s.useDashboardActions(),g=!!(c!=null&&c.visualId),f=(d==null?void 0:d.title)||(i==null?void 0:i.title)||"Untitled Visual",y=s.useCreateVisualWithFrame(T=>{if(T!=null&&T.id){if(x(T),a&&l&&u){const N={...l,id:s.v4(),visualId:T.id};j(u,N,"end"),b(N.id),r(!1),o(null),p(!1)}m(!0),n(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:n,handleSaveAs:async T=>{if(!u){s.ue.error("No sheet selected");return}const N=h();if(T.saveToLibrary){r(T.saveToCurrentDashboard),o(N);const D={title:T.name,description:T.description,frameObject:N,isPrivate:!1};y.mutate(D)}else if(T.saveToCurrentDashboard){const D={...N,id:s.v4(),visualId:void 0,cards:N.cards.map(v=>({...v,title:v.id===i.id?T.name:v.title}))};j(u,D,"end"),b(D.id),s.ue.success("Visual saved to dashboard"),n(!1),p(!1)}},isLibraryVisual:g,currentVisualName:f,isSaving:y.isPending}}function bt({className:t}){const n=s.useEditorStore(g=>g.frame),a=s.useManagementStore(g=>g.selectedVisual),r=s.useDashboardStore(g=>g.selectedFrameId),l=s.useDashboardStore(g=>g.selectedSheetId),o=!!(n!=null&&n.visualId||a!=null&&a.id),c=!!(n!=null&&n.visualId&&r),i=o&&!c,{saveAsDialogOpen:d,setSaveAsDialogOpen:u,handleSaveAs:m,isLibraryVisual:h,currentVisualName:x,isSaving:j}=Gn(),{handleAddLibraryVisual:b}=_e(),p=async()=>{if(!l){s.ue.error("No dashboard sheet selected");return}if(!a){s.ue.error("No visual selected");return}const g=await b(a);g.success?s.ue.success("Visual added to dashboard"):s.ue.error(g.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[e.jsx(jt,{className:t}),!o&&e.jsx(gt,{className:t,variant:"default"}),o&&e.jsxs(e.Fragment,{children:[c&&e.jsx(Un,{className:t}),i&&l&&e.jsxs(s.Button,{onClick:p,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(xa,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),e.jsx(_n,{className:t}),e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:g=>{g.stopPropagation(),u(!0)},children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]})]}),!o&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>u(!0),children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(Vn,{open:d,onOpenChange:g=>{j||u(g)},isLibraryVisual:h,currentVisualName:x,isSaving:j,onConfirm:m})]})}function vt({className:t,labelClassName:n,switchClassName:a}){const r=s.useEditorStore(d=>d.isDevMode),l=s.useDashboardStore(d=>d.isVisualEditing),{setIsDevMode:o}=s.useEditorActions(),{config:c}=A.useContext(s.SemaphorContext).tokenProps,i=(c==null?void 0:c.showAdvancedMode)!==!1;return!l||!i?null:e.jsxs("div",{className:s.cn("flex items-center space-x-2",t),children:[e.jsx(s.Switch,{className:s.cn("",a),checked:r,onCheckedChange:()=>o(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:s.cn("text-sm font-medium",n),children:"Advanced Mode"})]})}function Yn(){var de,xe,pe;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:o}=s.useRoleAwareDisplayPreferences(),c=s.useHasDashboardId();s.useDashboardStore(Q=>Q.theme);const i=s.useDashboardStore(Q=>Q.lenses),d=s.useDashboardStore(Q=>Q.selectedLensId),u=i==null?void 0:i.find(Q=>Q.id===d),m=s.useDashboardStore(Q=>Q.dashboard);s.useDashboardStore(Q=>Q.selectedSheetId);const h=s.useDashboardStore(Q=>Q.isDashboardEditing),[x,j]=A.useState(!1),[b,p]=A.useState(!1),[g,f]=A.useState(!1),y=s.useDashboardStore(Q=>Q.isDashboardPanelOpen),E=s.useDashboardStore(Q=>Q.actions.setIsDashboardPanelOpen),T=s.useDashboardStore(Q=>Q.filterValues),N=s.useDashboardStore(Q=>Q.isVisualEditing),D=s.useEditorStore(Q=>Q.card),v=s.useManagementStore(Q=>Q.selectedDashboard),C=s.useManagementStore(Q=>Q.initialDashboard),S=s.useManagementStore(Q=>Q.selectedVisual);s.useDashboardStore(Q=>Q.selectedFrameId),s.useEditorStore(Q=>Q.frame);const F=v?(xe=v==null?void 0:v.permissions)==null?void 0:xe.canEdit:(de=C==null?void 0:C.permissions)==null?void 0:de.canEdit,I=s.useDashboardStore(Q=>Q.showFilters),P=s.useDashboardStore(Q=>Q.showDashboardJSON),k=s.useDashboardStore(Q=>Q.onSaveFunction),w=s.useDashboardStore(Q=>Q.actions.setShowFilters),{setIsDashboardEditing:M,setShowDashboardJSON:O}=s.useDashboardStore(Q=>Q.actions),{setInitialDashboard:R,clearSelectedDashboard:L}=s.useManagementStore(Q=>Q.actions),{resources:B}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:Y}=s.useCurrentUserInfo(),J=s.canUserManageGroups(Y),V=v||C,K=V?{id:V.id,title:(m==null?void 0:m.title)||V.title||"Dashboard"}:null,{handleAddNewFrame:q}=s.useAddNewFrame(),[Z,$]=A.useState(!1),X=s.useUpdateResource(s.ResourceType.DASHBOARD);A.useEffect(()=>{if(B&&B.length>0){const Q=m==null?void 0:m.id;if(Q){const U=B.find(H=>H.id===Q);U&&R(U)}}},[B,m==null?void 0:m.id,R]);const _=n.orgUserId||n.tenantId,G=h&&!N&&_&&F,se=()=>{M(!0)};async function re(){const Q=as(m);$(!0);const U={template:Q};X.mutate({resourceId:Q.id,data:U},{onSuccess:()=>{$(!1),s.ue.success("Dashboard saved!")},onError:()=>{$(!1),s.ue.error("Failed to save dashboard")}})}async function he(){if(j(!0),!d||!u)return;const Q=as(m),U=JSON.stringify(Q),H={...u,template:U,filterValues:T};await ys(n.apiServiceUrl,H,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),k==null||k(Q),j(!1)}const z=(u==null?void 0:u.name)||m.title,ne=B&&B.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),le=v&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-11 items-center justify-between gap-2 border-b px-4 py-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ne&&e.jsxs(e.Fragment,{children:[le&&!N&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>L(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:c?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>{c&&E(!y)},className:"h-7 p-2",buttonProps:{disabled:!c},children:e.jsx(Aa,{className:"h-4 w-4"})})]}),!N&&c&&e.jsx(s.Label,{children:z}),N&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm font-medium",children:(S==null?void 0:S.title)||(D==null?void 0:D.title)||"Untitled Visual"}),e.jsx(pt,{})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[N&&e.jsxs(e.Fragment,{children:[e.jsx(vt,{className:"mr-2"}),e.jsx(bt,{className:"h-7"})]}),r&&!N&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(Ua,{className:"h-4 w-4"})}),!N&&c&&e.jsx(sn,{}),!N&&c&&e.jsx(nt,{}),!N&&c&&J&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!N&&c&&((pe=V==null?void 0:V.permissions)==null?void 0:pe.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),h&&!N&&_&&r&&c&&e.jsx(Za,{}),!N&&_&&r&&c&&e.jsx(en,{}),h&&!N&&_&&u&&r&&c&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:x,onClick:he,size:"sm",children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),h&&!N&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!h,onClick:()=>q(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!N&&!h&&o.canEdit&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:se,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),h&&!N&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{M(!1),O(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),G&&c&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:Z,onClick:re,size:"sm",children:[Z?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(qe,{className:"mr-2 h-4 w-4"}),Z?"Saving...":"Save"]}),!I&&!N&&h&&o.canUseFilters&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>w(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!N&&h&&r&&c&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>O(!P),size:"sm",variant:"ghost",children:e.jsx(Be,{className:"h-4 w-4"})})}),!N&&r&&e.jsx(Ka,{}),b&&K&&e.jsx(is,{resource:K,resourceType:s.ResourceType.DASHBOARD,onClose:()=>p(!1)}),e.jsx(Rn,{open:g,onOpenChange:f})]})]})}function $n({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:u=!1}){const m=Ee.useRef(null),[h,x]=Ee.useState(!1),[j,b]=Ee.useState("100%"),p=u?[...n||[],{id:"none",name:"None"}]:n;Ee.useLayoutEffect(()=>{m.current&&b(m.current.offsetWidth)},[]);function g(){var y;return l?"Loading...":o?"Error":a?(y=n==null?void 0:n.find(E=>E.id===a))==null?void 0:y.name:`Select ${t}`}function f(y,E){r(E),x(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:x,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:g()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:j},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(Zs,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:p==null?void 0:p.map(y=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:y.name,onSelect:E=>f(E,y.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===y.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:y.name,children:y.name})]})},y.id))})]})]})})]})}function Fe({title:t,items:n,value:a,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":a;function x(){if(t==="Connection")return e.jsx(za,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Oa,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(ua,{className:"size-4"})}function j(){return e.jsxs(s.Select,{disabled:u,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(Zs,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((p,g)=>e.jsx(s.SelectItem,{value:p.id,children:p.name},g))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function b(){return e.jsx($n,{icon:x(),items:n,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?j():b()})})}function qn({column:t}){const[n,a]=A.useState(!1),r=s.useEditorStore(p=>p.selectedTableName),l=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedDatabaseName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(p=>p.actions.setSqlGen),h=s.useEditorStore(p=>p.actions.setCardSql),x=s.useEditorStore(p=>p.actions.setRunSql);function j(p,g){var T;const f=s.createSqlGenConfig(p,i,g),y=(T=d==null?void 0:d.find(N=>N.id===c))==null?void 0:T.name;m(f);const E=s.getSql(f,s.fmt(l||""),s.fmt(r),y||"",u,o||"");E&&(h(E),x(!0)),a(!1)}function b(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>j(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>j(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>j(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>j(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>j(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]})}function Hn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx($e,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ke,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function ms({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",n),children:[e.jsx(Hn,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Wn({id:t,children:n,type:a="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:a}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:n})}function Kn({onClick:t,column:n}){const a=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function u(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(n),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(ms,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(ms,{column:n})}),e.jsx(Wn,{id:n.column_name,type:"column",children:e.jsx(ms,{column:n})})]})}const hs={id:"__placeholder__",role:"groupby",type:"string"},xs={id:"__placeholder__",role:"groupby",type:"string"},ps={id:"__placeholder__",role:"metric",type:"number"},fs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},yt={id:"__placeholder__"},Ie="droppable-group-by",Ae="droppable-metrics",Me="droppable-pivot-by",rs="sortable-group-by",Ns="sortable-metrics",ls="sortable-pivot-by",Cs="droppable-filters",Ss="sortable-filters",Ts="sortable-order-by";function Qn(){const t=s.useDndStore(w=>w.insertIndex),n=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.groupByColumns)||[]}),a=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.metricColumns)||[]}),r=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.filterColumns)||[]}),l=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.orderBy)||[]}),o=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:x,setMetricColumns:j,setFilterColumns:b,setOrderByColumns:p,setPivotByColumns:g}=s.useEditorActions(),{columns:f}=s.useDataColumns(),{formattedTableName:y}=s.useEditorAside(),E=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),T=w=>{var R;const{active:M,over:O}=w;if(((R=M.data.current)==null?void 0:R.type)==="column"&&O){const L=O.id,B=f.find(K=>K.column_name===M.id);if(!B)return;const Y=s.isNumberDataType(B.data_type),J=s.isTextDataType(B.data_type),V=s.isDateDataType(B.data_type);if(J||V){if(n.some(q=>q.id===L)){const q=n.findIndex($=>$.id===L);c(q);const Z=n.filter($=>$.id!==hs.id);Z.splice(q,0,hs),d(Z)}else if(O.id===Ie){c(n.length);const q=[...n,hs];d(q),u(a),m(r)}}if(J||V){if(o.some(q=>q.id===L)){const q=o.findIndex($=>$.id===L);c(q);const Z=o.filter($=>$.id!==xs.id);Z.splice(q,0,xs),h(Z)}else if(O.id===Me){c(o.length);const q=[...o,xs];h(q),d(n),u(a),m(r)}}if(Y||J){if(a.some(q=>q.id===L)){console.log("isOverMetricSortable",L);const q=a.findIndex($=>$.id===L);c(q);const Z=a.filter($=>$.id!==ps.id);Z.splice(q,0,ps),u(Z)}else if(O.id===Ae){c(a.length);const q=[...a,ps];u(q),m(r),d(n),h(o)}}if(D(B)){if(r.some(q=>q.id===L)){const q=r.findIndex($=>$.id===L);c(q);const Z=r.filter($=>$.id!==fs.id);Z.splice(q,0,fs),m(Z)}else if(O.id===Cs){c(r.length);const q=[...r,fs];m(q),u(a),d(n),h(o)}}}else d(n),u(a),m(r),h(o)};function N(w){i(w.active.id),c(null),d(n),u(a),m(r),h(o)}function D(w){return!r.some(M=>M.name===w.column_name)}function v(w,M="SUM"){const{column_name:O,data_type:R}=w,L=[...a],B=t!==null?t:a.length,Y={...w,id:Ne(O),name:O,label:We(O,M),type:R,role:"metric",aggregate:M};L.splice(B,0,Y),j(L)}function C(w){const M=s.isTextDataType(w.data_type);s.isDateDataType(w.data_type);const O=[...o],R=t!==null?t:o.length;let L;M?L={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,role:"groupby"}:L={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,role:"groupby",label:Ve(w.column_name,"month"),granularity:"month"},O.splice(R,0,L),g(O)}function S(w){const M=s.isTextDataType(w.data_type);s.isDateDataType(w.data_type);const O=[...n],R=t!==null?t:n.length;let L;M?L={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,role:"groupby"}:L={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,role:"groupby",label:Ve(w.column_name,"month"),granularity:"month"},O.splice(R,0,L),x(O)}function F(w){const M=[...r],O=t!==null?t:r.length,R={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,sql:s.getDefaultFilterSql(w.data_type,y,s.fmt(w.column_name)),role:"filter"};M.splice(O,0,R),b(M)}function I(w){var L,B,Y,J,V,K,q,Z;const{active:M,over:O}=w,R=M.data.current;if((R==null?void 0:R.type)==="column"&&O){const $=f.find(se=>se.column_name===M.id);if(!$)return;const X=s.isNumberDataType($.data_type),_=s.isTextDataType($.data_type),G=s.isDateDataType($.data_type);(_||G)&&(O.id===Ie||((L=O.data.current)==null?void 0:L.type)===rs)&&S($),(_||G)&&(O.id===Me||((B=O.data.current)==null?void 0:B.type)===ls)?C($):(X||_)&&(O.id===Ae||((Y=O.data.current)==null?void 0:Y.type)===Ns)?(X&&v($),_&&v($,"COUNT")):D($)&&(O.id===Cs||((J=O.data.current)==null?void 0:J.type)===Ss)&&F($)}if(O&&((V=O.data.current)==null?void 0:V.type)===rs&&n.some($=>$.id===M.id)){const $=n.findIndex(_=>_.id===M.id),X=n.findIndex(_=>_.id===O.id);if($!==-1&&X!==-1&&$!==X){const _=[...n],[G]=_.splice($,1);_.splice(X,0,G),x(_)}}if(O&&((K=O.data.current)==null?void 0:K.type)===ls&&o.some($=>$.id===M.id)){const $=o.findIndex(_=>_.id===M.id),X=o.findIndex(_=>_.id===O.id);if($!==-1&&X!==-1&&$!==X){const _=[...o],[G]=_.splice($,1);_.splice(X,0,G),g(_)}}if(O&&((q=O.data.current)==null?void 0:q.type)===Ns&&a.some($=>$.id===M.id)){const $=a.findIndex(_=>_.id===M.id),X=a.findIndex(_=>_.id===O.id);if($!==-1&&X!==-1&&$!==X){const _=[...a],[G]=_.splice($,1);_.splice(X,0,G),j(_)}}if(O&&((Z=O.data.current)==null?void 0:Z.type)===Ss&&r.some($=>$.id===M.id)){const $=r.findIndex(_=>_.id===M.id),X=r.findIndex(_=>_.id===O.id);if($!==-1&&X!==-1&&$!==X){const _=[...r],[G]=_.splice($,1);_.splice(X,0,G),b(_)}}P(w),i(null),c(null),d(n),u(a),m(r),h(o)}function P(w){const{active:M,over:O}=w,R=M.data.current;if((R==null?void 0:R.type)===Ts&&O){const L=l.findIndex(Y=>Ye(Y.columnId)===M.id),B=l.findIndex(Y=>Ye(Y.columnId)===O.id);if(L!==-1&&B!==-1&&L!==B){const Y=[...l],[J]=Y.splice(L,1);Y.splice(B,0,J),p(Y)}}}function k(){i(null),c(null),d(n),u(a),m(r)}return{handleDragOver:T,handleDragEnd:I,handleDragStart:N,handleDragCancel:k,sensors:E}}function Ne(t){return`${t}-${s.v4()}`}function We(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"SUM":return`Sum of ${a}`;case"COUNT":return`Count of ${a}`;case"DISTINCT":return`Unique ${a}`;case"AVG":return`Average of ${a}`;case"MIN":return`Min of ${a}`;case"MAX":return`Max of ${a}`;default:return a}}function Ye(t){return`${Ts}-${t}`}function Ve(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function Jn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx($e,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ke,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function Xn({schemaName:t,tableName:n,columns:a,status:r}){const[l,o]=A.useState(""),[c,i]=A.useState("all"),d=s.useEditorStore(L=>L.sqlGen),u=s.useEditorStore(L=>L.isDevMode);s.useEditorStore(L=>L.selectedConnectionId);const m=s.useEditorStore(L=>{var B,Y;return(Y=(B=L.card)==null?void 0:B.queryConfig)==null?void 0:Y.metricColumns});s.useEditorStore(L=>{var B,Y;return(Y=(B=L.card)==null?void 0:B.queryConfig)==null?void 0:Y.groupByColumns});const h=s.useEditorStore(L=>L.selectedDatabaseName);s.useEditorStore(L=>L.selectedSchemaName),s.useEditorStore(L=>L.selectedTableName);const x=s.useEditorStore(L=>L.selectedDatamodelId);s.useDashboardStore(L=>L.dashboard.aiScopeTables);const{addToAIScope:j,removeFromAIScope:b}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:g,setCardSql:f,setRunSql:y,setSqlGen:E,setIsShowingVisual:T}=s.useEditorActions(),{connectionType:N,modelItems:D,selectedDatamodelName:v}=s.useEditorAside();function C(L){var B;if(u){const Y=s.createSqlGenConfig(L,d);E(Y);const J=(B=D==null?void 0:D.find(K=>K.id===x))==null?void 0:B.name,V=s.getSql(Y,s.fmt(t),s.fmt(n),J||"",N,h||"");V&&(f(V),y(!0))}if(!u){if(s.isTextDataType(L.data_type))if(m&&m.length>0){const Y={...L,role:"groupby",id:Ne(L.column_name),name:L.column_name,type:L.data_type};g(Y)}else{const Y={...L,role:"metric",id:Ne(L.column_name),name:L.column_name,label:We(L.column_name,"COUNT"),type:L.data_type,aggregate:"COUNT"};p(Y)}if(s.isDateDataType(L.data_type)){const Y={...L,role:"groupby",id:Ne(L.column_name),name:L.column_name,type:L.data_type,label:Ve(L.column_name,"month"),granularity:"month"};g(Y)}if(s.isNumberDataType(L.data_type)){const Y={...L,role:"metric",id:Ne(L.column_name),name:L.column_name,label:We(L.column_name,"SUM"),type:L.data_type,aggregate:"SUM"};p(Y)}}}function S(){const L=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:N,databaseName:h||""});T(!1);const B=N==="MSSQL"?`SELECT top 10 * FROM ${L}`:`SELECT * FROM ${L} LIMIT 10`;f(B),y(!0)}function F(){const L=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:N,databaseName:h||""});f(`SELECT COUNT(*) as count FROM ${L}`),y(!0)}const I=(a==null?void 0:a.filter(L=>L.column_name.toLowerCase().includes(l.toLowerCase())))||[],P=L=>s.isNumberDataType(L.data_type)?"number":"text",k=c==="all"?I:I.filter(L=>P(L)===c),w=I.filter(L=>P(L)==="text").length,M=I.filter(L=>P(L)==="number").length;function O(L){return u?e.jsxs("div",{className:"group flex cursor-pointer items-center justify-between border border-dashed border-background px-2 py-[6px] text-sm transition-colors hover:bg-muted/50",onClick:()=>C(L),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jn,{dataType:L.data_type}),e.jsx("span",{children:L.column_name})]}),e.jsx("div",{onClick:B=>B.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(L.data_type)&&e.jsx(qn,{column:L})})]}):e.jsx(Kn,{onClick:C,column:L})}function R(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:S,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Ia,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:F,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(et,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-4",children:Array.from({length:3}).map((L,B)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},B))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[u&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:R()}),a&&a.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:L=>o(L.target.value)})]}),I.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:L=>i(L),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:I.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:w})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:M})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[k.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),k.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:k==null?void 0:k.map(L=>e.jsx("div",{children:O(L)},L.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Nt({ColumnsComponent:t,type:n}){var Q;const[a,r]=A.useState(!1),{isConsoleMode:l}=s.useDashboardPreferences(),o=s.useEditorStore(U=>U.card),c=s.useEditorStore(U=>U.selectedConnectionId),i=s.useDashboardStore(U=>U.showFilters),d=s.useEditorStore(U=>U.selectedDatamodelId),u=s.useEditorStore(U=>U.selectedDatabaseName),m=s.useEditorStore(U=>U.selectedSchemaName),h=s.useEditorStore(U=>U.selectedTableName);s.useEditorStore(U=>U.isDevMode);const{setSelectedTableName:x,setIsDevMode:j,setCardSql:b}=s.useEditorActions(),{connectionItems:p,modelItems:g,schemaItems:f,databaseItems:y,tableItems:E,columns:T,isConnectionsLoading:N,isModelsLoading:D,isConnectionsError:v,isModelsError:C,isDatabasesLoadingOrFetching:S,isDatabaseError:F,isSchemaLoadingOrFetching:I,isSchemaError:P,isColumnsError:k,isColumnsLoadingOrFetching:w,isTableLoadingOrFetching:M,isTableError:O,connectionType:R,isNonDbConnection:L,refetchDatabases:B,refetchModels:Y,refetchSchemas:J,refetchTables:V,refetchColumns:K,refetchConnections:q,handleConnectionChange:Z,handleDatabaseChange:$,handleSchemaChange:X,handleDatamodelChange:_,handleTableChange:G,tableName:se,schemaName:re}=s.useEditorAside(),{data:he,refetch:z}=s.useDashboardCardQuery(o);function ee(){return t?t(re,se,T):e.jsx(Xn,{schemaName:re,tableName:se,columns:T,status:w?"Loading...":k?"Error":"Success"})}function ne(){if(!c||R==="S3"||R==="API")return null;if(!d||d==="none")return e.jsx(Fe,{refetch:B,showNone:!0,onChange:$,isError:F,isLoading:S,items:y,value:u||"",title:"Database",type:"combobox"})}function le(){if(c&&!L&&(!u||u==="none")&&(!d||d==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function de(){if(!c||R==="S3"||R==="API")return null;if(!u||u==="none")return e.jsx(Fe,{refetch:Y,showNone:!0,onChange:_,isError:C,isLoading:D,items:g,value:d||"",title:"Model",type:"combobox"})}function xe(){return!c||R==="S3"||R==="API"||!u||u==="none"?null:e.jsx(Fe,{refetch:J,onChange:X,isError:P,isLoading:I,items:f,value:m||"",title:"Schema",type:"combobox"})}function pe(){function U(){let H=!1;return R==="API"?(H=!1,H):((R==="S3"||c&&u&&u!=="none"&&m)&&(H=!0),H)}return U()?e.jsx(Fe,{refetch:V,onChange:G,isError:O,items:E,isLoading:M,value:h||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!i}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":a,"px-4 py-4":!a}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!a),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:a?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!a&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Fe,{refetch:q,items:p,title:"Connection",value:c||"",onChange:Z,isLoading:N,isError:v,type:"combobox",connectionTooltip:((Q=p==null?void 0:p.find(U=>U.id===c))==null?void 0:Q.type)||""}),ne(),le(),de(),xe(),pe()]})]}),ee(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&l&&e.jsx(e.Fragment,{})})]})}function Ct({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:l=!0}){const[o,c]=A.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",r),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Query Error"}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),l&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(La,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function St({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){o(!l),c(t),setTimeout(()=>{i(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[n&&e.jsx(Ct,{error:n,errorSql:a,showFeedbackButton:!1}),!n&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!n&&e.jsxs(s.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(va,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&r&&e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(wa,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function wt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(pa,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(St,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function Zn(t){return s.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function Dt(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(p=>p.theme),r=s.useEditorStore(p=>p.frame),l=s.useEditorStore(p=>p.card),o=s.useEditorStore(p=>p.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=A.useRef(),h=A.useRef({}),x=r.cards.find(p=>p.id===o),j=A.useCallback(()=>{let p="";return t==="python"&&(p=(x==null?void 0:x.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(p=(x==null?void 0:x.sql)||""),p},[t,x]);A.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const p=m.current.getModel();p&&(h.current[l.id]=p);let g=h.current[o];if(!g){const f=j();g=c.editor.createModel(f,t),h.current[o]=g}m.current.setModel(g)}d(o,l),u(!0)}},[o,l,d,c,u,t,j]),A.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",g=a==="system"?p:a;c.editor.defineTheme("default",{base:g==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":g==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),A.useEffect(()=>{const p=m.current;p&&c&&l&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function b(p,g){if(m.current=p,!h.current[l.id]){const f=p.getModel(),y=j();h.current[l.id]=f||(g==null?void 0:g.editor.createModel(y,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:b}}function er(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Dt("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function sr(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Dt("python");function r(l){n(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function tr({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function ar(){const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=A.useState(!1),[l,o]=A.useState(!1);s.useEditorStore(V=>V.frame);const c=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.isShowingVisual),s.useEditorStore(V=>V.selectedConnectionId),s.useEditorStore(V=>V.tempQueryData),s.useEditorStore(V=>V.selectedDatabaseName),s.useEditorStore(V=>V.selectedDatamodelId),s.useEditorStore(V=>V.selectedSchemaName);const i=s.useEditorStore(V=>V.showAIDialog);s.useEditorStore(V=>V.selectedTableName);const d=s.useEditorStore(V=>{var K;return(K=V==null?void 0:V.card)==null?void 0:K.sql}),u=s.useEditorStore(V=>{var K;return(K=V==null?void 0:V.card)==null?void 0:K.python}),{sheetFilterValues:m}=s.useSheetFilterValues(),{setCardCustomCfg:h,setQueryResultColumns:x,setCardSql:j,setTempQueryData:b,setPythonStdOut:p,setCardPreferences:g,setCardType:f,setCardPython:y,runAssistant:E,setShowAIDialog:T}=s.useEditorActions();s.useEditorStore(V=>V.onSave),s.useEditorStore(V=>V.onClose),s.useEditorStore(V=>V.actions.setSqlGen);const N=s.useEditorStore(V=>V.runSql),D=s.useEditorStore(V=>V.actions.setRunSql),v=s.useEditorStore(V=>V.actions.setIsSqlRunning),{data:C,isLoading:S,isFetching:F,isSuccess:I,isError:P,error:k,errorSql:w,queryKey:M,refetch:O,errorMessage:R}=s.useDashboardCardQuery(c);A.useEffect(()=>{if(C&&(C.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),p((C==null?void 0:C.output)||""),C.records.length>0)){const{dimensionKeys:V}=s.getKeys(C.records);x(V)}},[C,x,p]),A.useEffect(()=>{(S||F)&&v(!0),(P||I)&&v(!1),P&&(x([]),p(""))},[S,F,C,p,P,I,v,x,k]),A.useEffect(()=>{N&&(t.getQueryData(M)||O(),D(!1))},[N,O,D,M,t]);async function L(){const V=`Can you help me debug this query?
|
|
316
|
+
*/const Wa=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function Ka(){const{setTheme:t}=s.useTheme(),n=s.useDashboardStore(a=>a.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx($a,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Ra,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function as(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>at(c))}})}})}}function at(t){return{...t,customCfg:Qa(t.customCfg),data:[]}}function Qa(t){var n,a;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(a=(n=t==null?void 0:t.data)==null?void 0:n.datasets)==null?void 0:a.map(r=>({...r,data:[]}))}}:null}async function Ja(t,n,a,r,l){if(!l)return null;const o=JSON.stringify(a),c=`${t}/v1/lens`;return await s.postRequest(c,l,{name:n,template:o,filterValues:r,operation:"create"})}async function ys(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:o,isDefault:c,shared:i}=n,d=`${t}/v1/lens`;return await s.postRequest(d,a,{lensId:r,template:l,filterValues:o,isDefault:c,shared:i,operation:"update"})}async function Xa(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function Za(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),l=s.useDashboardStore(j=>j.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=A.useState(!1),[u,m]=A.useState(!1),h=s.useDashboardStore(j=>j.dashboard),x=s.useDashboardStore(j=>j.filterValues),{authToken:g,tokenProps:b}=s.useSemaphorContext();async function p(){d(!0);const j=as(h),f=await Ja(b.apiServiceUrl,t,j,x,g==null?void 0:g.accessToken);f&&(o([...l||[],f]),c(f.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:j=>{n(j.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:p,disabled:i,children:i?"Creating...":"Add"})})]})]})}function en(){const[t,n]=A.useState(!1),a=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c,tokenProps:i}=s.useSemaphorContext();async function d(h){o(h)}async function u(h){if(await Xa(i.apiServiceUrl,h,c==null?void 0:c.accessToken)){const g=a==null?void 0:a.filter(b=>b.id!==h);l(g||[]),o("original")}}async function m(h){const x=a==null?void 0:a.map(p=>p.id===h.id?{...p,isDefault:!h.isDefault}:{...p,isDefault:!1});l(x||[]);const g={...h,isDefault:!h.isDefault};await ys(i.apiServiceUrl,g,c==null?void 0:c.accessToken);const b=a==null?void 0:a.find(p=>p.isDefault);if(b&&b.id!==h.id){const p={...b,isDefault:!1};await ys(i.apiServiceUrl,p,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Sa,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:d,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:x=>{x.preventDefault(),m(h)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:x=>{x.preventDefault(),u(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function sn({iconClassName:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(""),[o,c]=A.useState(!1),i=s.useDashboardStore(h=>h.isDownloadingPdf),{tokenProps:d}=s.useSemaphorContext();async function u(){const h=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl),s.ue.dismiss(h),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",x)}}async function m(){if(!r)return;a(!1),l(""),c(!1);const h=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl,r),s.ue.dismiss(h),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",x)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(s.Lock,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:n,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:h=>l(h.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:h=>{h.key==="Enter"&&r&&m()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:m,disabled:!r,children:"Download"})]})]})})]})}function nt({triggerButtonClassName:t}){const[n,a]=A.useState(!1),r=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.id}),l=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.title}),o=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.sheets}),c=s.useDashboardStore(i=>i.selectedSheetId);return o==null||o.find(i=>i.id===c),r?e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),onClick:()=>a(!0),children:e.jsx(s.Clock,{className:"size-4"})}),e.jsx(s.EmailScheduleDialog,{open:n,onOpenChange:a,dashboardId:r,dashboardName:l})]}):null}function ns({value:t,onChange:n,placeholder:a="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:a,value:t,onChange:r=>n(r.target.value),className:"pl-9"})]})}function Re({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=a.find(u=>u.value===t))==null?void 0:d.label)||t,i=a.filter(u=>u.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>n(u.value),disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function rt({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>a(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(Re,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>a(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function lt({usersToRemove:t,allUsers:n,onRemove:a}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>a(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>a(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function ot({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=n.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function it(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=A.useRef(null);return A.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function ye(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function tn(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function ct(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function an(t,n,a){const r=ct(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function nn({user:t}){return ct(t)==="tenant"?e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="POWER_USER"?"Power User":"Viewer"}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="ADMIN"?"Admin":t.role==="POWER_USER"?"Power User":"Viewer"})}function rn({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=tn((r==null?void 0:r.type)||""),i=a.some(h=>h.id===t.id),d=a.find(h=>h.id===t.id),u=d?d.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Re,{currentRole:u,onRoleChange:h=>{o(t.id,n.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:ye(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function ln({hasAccess:t,isUserRemoving:n,isSelected:a,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!n&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),n&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),a&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Pe,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function on({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function cn({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((x,g)=>{var f,y;const b=((f=n.find(k=>k.id===x.orgUserId))==null?void 0:f.name)||"Unknown User",p=((y=n.find(k=>k.id===x.orgUserId))==null?void 0:y.type)||"",j=ye(x.role,a(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((x,g)=>{var f,y;const b=((f=n.find(k=>k.id===x.tenantUserId))==null?void 0:f.name)||"Unknown User",p=((y=n.find(k=>k.id===x.tenantUserId))==null?void 0:y.type)||"",j=ye(x.role,a(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((x,g)=>{const b=ye(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((x,g)=>{const b=ye(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((x,g)=>{const b=ye(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),!i.length&&!d.length&&!u.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var g,b;const m=((g=n.find(p=>p.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((b=n.find(p=>p.id===d.tenantUserId))==null?void 0:b.type)||"",x=ye(d.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:x})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=ye(d.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var x,g;const u=((x=n.find(b=>b.id===i.tenantUserId))==null?void 0:x.name)||"Unknown User",m=((g=n.find(b=>b.id===i.tenantUserId))==null?void 0:g.type)||"",h=ye(i.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=ye(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function dn({isInitialLoading:t,searchQuery:n,availableUsers:a}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):a.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:n?"No users found matching your search.":"No users available to share with."}):null}function un({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:x,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?a?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(nn,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Re,{currentRole:n==null?void 0:n.role,onRoleChange:b=>x(t.id,n.role,b),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(rn,{user:t,userShare:n,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:x}),o&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(Re,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:b=>g(t.id,b),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(ln,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(on,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function dt({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),b=s.useShareManagementActions(),p=c||(N=>{const D=m.some(S=>S.id===N),v=h.includes(N);D?b.removeSelectedUser(N):v?b.removeUserFromRemove(N):b.addSelectedUser({id:N,role:"VIEWER"})}),j=i||b.updateSelectedUserRole,f=d||b.addUserToRemove,y=u||((N,D,v)=>{b.addUserToUpdate({id:N,currentRole:D,newRole:v})}),k=l,T=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(k??[]).length,")"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(cn,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(k==null?void 0:k.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===k.length?b.setSelectedUsers([]):b.setSelectedUsers(k.map(N=>({id:N.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===k.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(dn,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:k||[]}),!n&&!a&&(k==null?void 0:k.length)>0&&k.map(N=>{const D=t?an(N,t,o):void 0,v=T.includes(N.id),S=!!D,C=S&&!v,O=m.some(E=>E.id===N.id),I=m.find(E=>E.id===N.id),B=r(N.type);return e.jsx(un,{user:N,userShare:D,isUserRemoving:v,hasAccess:C,hasAccessFromAPI:S,isSelected:O,selectedUser:I,roleOptions:B,currentUser:o,usersToUpdate:x,handleUserToggle:p,handleRemoveAccess:f,handleUpdateAccess:y,handleUserRoleChange:j},N.id)})]})]})}function ws({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(s.User,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const be=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function mn({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=be().filter(y=>y.value==="VIEWER"||y.value==="EDITOR"||y.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",h=l?l.newRole:m,x=n.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,b=o,p=m==="NONE"||!m,j=y=>{switch(y){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(_a,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},f=y=>{r(m,y)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!b&&!p?"border-orange-300 bg-orange-50":x?"border-green-300 bg-green-50":b||p?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",x&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),g&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(b||p)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:b||p?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(y=>e.jsxs(s.Button,{variant:h===y.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>f(y.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(y.value),e.jsx("span",{className:"font-medium",children:y.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:y.description})]},y.value))})]})})]})})}function ut({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=p=>p==="OWNER"?"CONTRIBUTOR":p,h=n?{role:u(n.role)}:{role:"NONE"},x=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,g=(p,j)=>{o(p,j)},b=()=>{c()};return e.jsx(mn,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:b,allUsersToUpdate:x,allUsersToRemove:d})}function _e(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=A.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading:d,isError:u}=s.useUnifiedUsers(c),m=s.useResourceShares(r,a);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function hn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var V,K;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),x=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),b=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),j=s.useShareOrgWideRole(),f=s.useShareManagementActions(),[y,k]=A.useState("specific_users"),T=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},N=()=>{if(i==="tenant"&&d)return d},{allUsers:D,existingShares:v,isLoadingUsers:S}=_e({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:T(),tenantId:N()});A.useEffect(()=>{f.setCurrentContext("org-tab"),f.setCurrentMode(y==="all_users"?"allOrgUsers":"specificOrgUsers")},[f,y]);const C=q=>{var $,X;const Z=q;if(k(Z),r==null||r(Z),f.setCurrentContext("org-tab"),Z==="specific_users")f.setCurrentMode("specificOrgUsers");else if(Z==="all_users"){f.setCurrentMode("allOrgUsers");const _=(X=($=v==null?void 0:v.shares)==null?void 0:$.orgUsersOnly)==null?void 0:X[0];_&&_.role!==void 0&&f.setOrgWideRole(_.role)}},O=D.filter(q=>q.name.toLowerCase().includes(u.toLowerCase())||q.email.toLowerCase().includes(u.toLowerCase())),I=D.filter(q=>x.some(Z=>Z.id===q.id)),B=q=>{var _,G;const Z=x.some(se=>se.id===q),$=g.includes(q),X=(G=(_=v==null?void 0:v.shares)==null?void 0:_.specificOrgUsers)==null?void 0:G.some(se=>se.orgUserId===q);Z?f.removeSelectedUser(q):$?f.removeUserFromRemove(q):X||f.addSelectedUser({id:q,role:"VIEWER"})},E=(q,Z)=>{f.updateSelectedUserRole(q,Z)},w=q=>{f.addUserToRemove(q),f.removeSelectedUser(q)},M=q=>{f.removeUserFromRemove(q)},F=q=>{f.removeUserFromUpdate(q)},R=(q,Z)=>{f.setOrgWideRole(Z)},L=()=>{f.setOrgWideRole((P==null?void 0:P.role)||"NONE")},P=(K=(V=v==null?void 0:v.shares)==null?void 0:V.orgUsersOnly)==null?void 0:K[0];A.useEffect(()=>{y==="all_users"&&P&&P.role!==void 0&&f.setOrgWideRole(P.role)},[y,P,f]);const Y=S,J=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(ws,{shareType:y,onShareTypeChange:C,currentUser:a,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),y==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(ns,{value:u,onChange:m}),e.jsx(rt,{selectedUsers:x,selectedUserObjects:I,onRemove:B,onRoleChange:E,getRoleOptions:be}),e.jsx(lt,{usersToRemove:g,allUsers:O,onRemove:M}),e.jsx(ot,{usersToUpdate:b,allUsers:O,onRemove:F,getRoleOptions:be}),e.jsx(dt,{existingShares:v,isInitialLoading:Y,isSearching:J,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:O,currentUser:a,handleUserToggle:B,handleUserRoleChange:E,handleRemoveAccess:w,handleUpdateAccess:(q,Z,$)=>{f.addUserToUpdate({id:q,currentRole:Z,newRole:$})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(ut,{currentUser:a,currentShare:P,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:R,onRemoveAccess:L,allUsersToUpdate:p==="allOrgUsers"&&j!==((P==null?void 0:P.role)||"NONE")?{currentRole:(P==null?void 0:P.role)||"NONE",newRole:j}:null,allUsersToRemove:p==="allOrgUsers"&&(P==null?void 0:P.role)===void 0})})]}):null}function xn(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function pn(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function mt({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:l,currentUser:o,handleGroupToggle:c,handleGroupRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),g=s.useShareManagementActions(),b=l(o==null?void 0:o.type);return a?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):t.length===0?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No groups available to share with"}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Available Groups"}),e.jsx("div",{className:"max-h-[300px] space-y-2 overflow-y-auto rounded-md border p-3",children:t.map(p=>{const j=n==null?void 0:n.find(v=>v.groupId===p.id),f=m.some(v=>v.id===p.id),y=h.includes(p.id),k=x.find(v=>v.id===p.id),T=!!j&&!y;let D=(j==null?void 0:j.role)||"VIEWER";if(f){const v=m.find(S=>S.id===p.id);D=(v==null?void 0:v.role)||"VIEWER"}else k&&(D=k.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",T&&!y?"border border-green-200 bg-green-50":y?"border border-red-200 bg-red-50":f?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(s.Checkbox,{id:`group-${p.id}`,checked:T?!y:f,disabled:!1,onCheckedChange:()=>{T?y?g.removeGroupFromRemove(p.id):d==null||d(p.id):c==null||c(p.id)}}),e.jsxs("label",{htmlFor:`group-${p.id}`,className:"flex cursor-pointer flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:p.name}),p.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-3 w-3 text-blue-600"}):e.jsx(s.Users,{className:"h-3 w-3 text-green-600"}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[p.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",pn(p.type)),children:xn(p.type)}),p.type==="TENANT_GROUP"&&p.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",p.tenantName]})]}),p.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[T&&!y?e.jsx(Re,{currentRole:D,onRoleChange:v=>{j&&v!==j.role&&(u==null||u(p.id,j.role,v))},roleOptions:b,disabled:!1,allowDropdown:!0,className:k?"border-orange-300 bg-orange-100":""}):f&&!T&&e.jsx(Re,{currentRole:D,onRoleChange:v=>i==null?void 0:i(p.id,v),roleOptions:b,disabled:!1}),T&&!y&&!k&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>d==null?void 0:d(p.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),y&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromRemove(p.id),children:"Undo"}),k&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromUpdate(p.id),children:"Cancel"})]})]},p.id)})})]})}function ht({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){if(t.length===0)return null;const o=l();return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",t.length,")"]}),e.jsx("div",{className:"space-y-1",children:t.map(c=>{const i=n.find(d=>d.id===c.id);return i?e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/50 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-4 w-4 text-blue-600"}):e.jsx(s.Users,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm font-medium",children:i.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[i.memberCount," members"]}),i.type==="TENANT_GROUP"&&i.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",i.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{currentRole:c.role,onRoleChange:d=>r(c.id,d),roleOptions:o}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(c.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},c.id):null})})]})}function Vs({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var Q;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSelectedGroups(),b=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate(),j=s.useShareCurrentMode(),f=s.useShareTenantWideRole(),y=s.useShareAllTenantsRole(),k=s.useShareSelectedTenant(),T=s.useShareManagementActions(),{data:N,isLoading:D}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:v,isLoading:S}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||k),[C,O]=A.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(T.setCurrentContext("tenant-dialog"),T.setCurrentMode("specificTenantUsers")):(T.setCurrentContext("tenant-tab"),T.setCurrentMode("allTenants"))},[T,a==null?void 0:a.type]);const I=U=>{var te,oe,ae,je;O(U);let H;if(U==="specific_tenant_users"?H="specific_users":U==="all_tenant_users"||U==="all_tenants"?H="all_users":U==="groups"?H="groups":H="specific_users",r==null||r(H),U==="groups"?(T.setCurrentContext("group-share"),T.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(T.setCurrentContext("tenant-dialog"),U==="specific_tenant_users"?T.setCurrentMode("specificTenantUsers"):U==="all_tenant_users"&&(T.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&T.setSelectedTenant(a.tenantId))):(T.setCurrentContext("tenant-tab"),U==="specific_tenant_users"?T.setCurrentMode("specificTenantUsers"):U==="all_tenant_users"?T.setCurrentMode("allTenantUsers"):U==="all_tenants"&&T.setCurrentMode("allTenants")),U==="all_tenant_users"){const me=(oe=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:oe[0];me&&me.role!==void 0&&T.setTenantWideRole(me.role)}else if(U==="all_tenants"){const me=(je=(ae=w==null?void 0:w.shares)==null?void 0:ae.allTenantsOnly)==null?void 0:je[0];me&&me.role!==void 0&&T.setAllTenantsRole(me.role)}},B=U=>{T.setSelectedTenant(U)},{allUsers:E,existingShares:w,isLoadingUsers:M,isErrorLoadingUsers:F,isLoadingShares:R,isErrorLoadingShares:L}=_e({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:k}),P=U=>{var ae,je;const H=m.some(me=>me.id===U),te=h.includes(U),oe=(je=(ae=w==null?void 0:w.shares)==null?void 0:ae.specificTenantUsers)==null?void 0:je.some(me=>me.tenantUserId===U);H?T.removeSelectedUser(U):te?T.removeUserFromRemove(U):oe||T.addSelectedUser({id:U,role:"VIEWER"})},Y=(U,H)=>{T.updateSelectedUserRole(U,H)},J=U=>{T.addUserToRemove(U),T.removeSelectedUser(U)},V=U=>{T.removeUserFromRemove(U)},K=U=>{T.removeUserFromUpdate(U)},q=(U,H,te)=>{T.addUserToUpdate({id:U,currentRole:H,newRole:te})},Z=(U,H)=>{C==="all_tenant_users"?T.setTenantWideRole(H):C==="all_tenants"&&T.setAllTenantsRole(H)},$=()=>{C==="all_tenant_users"?T.setTenantWideRole("VIEWER"):C==="all_tenants"&&T.setAllTenantsRole("VIEWER")},_=(()=>{var U,H,te,oe;return j==="allTenants"?(H=(U=w==null?void 0:w.shares)==null?void 0:U.allTenantsOnly)==null?void 0:H[0]:j==="allTenantUsers"?(oe=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:oe[0]:null})();A.useEffect(()=>{var U,H,te,oe;if(C==="all_tenant_users"){const ae=(H=(U=w==null?void 0:w.shares)==null?void 0:U.tenantWide)==null?void 0:H[0];ae&&ae.role!==void 0&&T.setTenantWideRole(ae.role)}else if(C==="all_tenants"){const ae=(oe=(te=w==null?void 0:w.shares)==null?void 0:te.allTenantsOnly)==null?void 0:oe[0];ae&&ae.role!==void 0&&T.setAllTenantsRole(ae.role)}},[C,w,T]);const G=E.filter(U=>m.some(H=>H.id===U.id)),se=U=>{const H=g.some(ae=>ae.id===U),te=b.includes(U),oe=le==null?void 0:le.some(ae=>ae.groupId===U);H?T.removeSelectedGroup(U):te?T.removeGroupFromRemove(U):oe||T.addSelectedGroup({id:U,role:"VIEWER"})},re=(U,H)=>{T.updateSelectedGroupRole(U,H)},he=U=>{T.addGroupToRemove(U),T.removeSelectedGroup(U)},z=(U,H,te)=>{T.addGroupToUpdate({id:U,currentRole:H,newRole:te})},ee=v.filter(U=>g.some(H=>H.id===U.id)),ne=A.useMemo(()=>C!=="groups"?[]:v.filter(U=>U.type!=="TENANT_GROUP"?!1:U.name.toLowerCase().includes(i.toLowerCase())||U.description&&U.description.toLowerCase().includes(i.toLowerCase())),[v,C,i]),le=A.useMemo(()=>{var H,te;const U=((H=w==null?void 0:w.shares)==null?void 0:H.specificGroups)||((te=w==null?void 0:w.shares)==null?void 0:te.groups)||[];return!U||U.length===0?[]:U.filter(oe=>{const ae=v.find(je=>je.id===oe.groupId);return(ae==null?void 0:ae.type)==="TENANT_GROUP"})},[w,v]),de=M||R||C==="groups"&&S,xe=F||L,pe=()=>(a==null?void 0:a.type)==="tenant"||C==="all_tenants"||C==="groups"?!0:k&&(C==="specific_tenant_users"||C==="all_tenant_users");return e.jsxs(e.Fragment,{children:[xe&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s.CircleAlert,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),e.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!xe&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(ws,{shareType:C,onShareTypeChange:I,currentUser:a,options:(a==null?void 0:a.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(Bs,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.type)==="organization"&&(C==="specific_tenant_users"||C==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:k||"",onValueChange:B,disabled:D,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:D?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(Q=N==null?void 0:N.tenants)==null?void 0:Q.map(U=>e.jsx(s.SelectItem,{value:U.id,children:U.name},U.id))})]})]}),pe()?e.jsx(e.Fragment,{children:C==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ns,{value:i,onChange:u}),e.jsx(rt,{selectedUsers:m,selectedUserObjects:G,onRemove:U=>P(U),onRoleChange:Y,getRoleOptions:be}),e.jsx(lt,{usersToRemove:h,allUsers:E,onRemove:V}),e.jsx(ot,{usersToUpdate:x,allUsers:E,onRemove:K,getRoleOptions:be}),e.jsx(dt,{existingShares:w,isInitialLoading:!!de,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:E,currentUser:a,handleUserToggle:P,handleUserRoleChange:Y,handleRemoveAccess:J,handleUpdateAccess:q})]}):C==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ns,{value:i,onChange:u,placeholder:"Search groups..."}),e.jsx(ht,{selectedGroups:g,groupObjects:ee,onRemove:se,onRoleChange:re,getRoleOptions:be}),b.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",b.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),p.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",p.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(mt,{groups:ne,existingGroupShares:le,isLoading:S,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:se,handleGroupRoleChange:re,handleRemoveAccess:he,handleUpdateAccess:z})]}):C==="all_tenant_users"||C==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(ut,{currentUser:a,currentShare:_,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:Z,onRemoveAccess:$,allUsersToUpdate:j==="allTenantUsers"&&((_==null?void 0:_.role)===void 0||f!==_.role)||j==="allTenants"&&((_==null?void 0:_.role)===void 0||y!==_.role)?{currentRole:(_==null?void 0:_.role)||"VIEWER",newRole:j==="allTenantUsers"?f:y}:null,allUsersToRemove:j==="allTenantUsers"&&(_==null?void 0:_.role)===void 0||j==="allTenants"&&(_==null?void 0:_.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(C==="specific_tenant_users"||C==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Bs,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}function fn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var F,R;const{searchQuery:i,setSearchQuery:d}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),x=s.useShareManagementActions(),[g,b]=A.useState("org_groups"),[p,j]=A.useState(""),{data:f,isLoading:y}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&g==="tenant_groups"}),k=Array.isArray(f)?f:(f==null?void 0:f.tenants)||[],T=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:N,isLoading:D}=s.useShareableGroups(T(),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?p:a==null?void 0:a.tenantId),{existingShares:v}=_e({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),S=N.filter(L=>g==="org_groups"&&L.type!=="ORG_GROUP"||g==="tenant_groups"&&L.type!=="TENANT_GROUP"||g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!p||L.tenantId&&L.tenantId!==p)?!1:L.name.toLowerCase().includes(i.toLowerCase())||L.description&&L.description.toLowerCase().includes(i.toLowerCase())),C=((F=v==null?void 0:v.shares)==null?void 0:F.specificGroups)||((R=v==null?void 0:v.shares)==null?void 0:R.groups)||[];A.useEffect(()=>{x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},[x]);const O=L=>{const P=L;b(P),P==="org_groups"&&j(""),r==null||r(P==="org_groups"?"specific_groups":"all_groups"),x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},I=N.filter(L=>u.some(P=>P.id===L.id)),B=L=>{const P=u.some(V=>V.id===L),Y=m.includes(L),J=C==null?void 0:C.some(V=>V.groupId===L);P?x.removeSelectedGroup(L):Y?x.removeGroupFromRemove(L):J||x.addSelectedGroup({id:L,role:"VIEWER"})},E=(L,P)=>{x.updateSelectedGroupRole(L,P)},w=L=>{x.addGroupToRemove(L),x.removeSelectedGroup(L)},M=(L,P,Y)=>{x.addGroupToUpdate({id:L,currentRole:P,newRole:Y})};return a?e.jsxs(e.Fragment,{children:[e.jsx(ws,{shareType:g,onShareTypeChange:O,currentUser:a,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:e.jsx(s.Building2,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"tenant_groups",label:"Tenant Groups",description:"Share with tenant-level groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]}),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(s.Label,{children:"Select Tenant"}),e.jsxs(s.Select,{value:p,onValueChange:j,disabled:y,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:y?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:k.map(L=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:L.id,children:L.name},L.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!p?e.jsx("div",{className:"rounded-md border border-dashed p-6 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant above to view and share with its groups"})}):e.jsxs(e.Fragment,{children:[e.jsx(ns,{value:i,onChange:d,placeholder:"Search groups..."}),e.jsx(ht,{selectedGroups:u,groupObjects:I,onRemove:B,onRoleChange:E,getRoleOptions:be}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",m.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",h.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(mt,{groups:S,existingGroupShares:C,isLoading:D,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:B,handleGroupRoleChange:E,handleRemoveAccess:w,handleUpdateAccess:M})]})})]}):null}const xt=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedGroups(),c=s.useShareGroupsToRemove(),i=s.useShareGroupsToUpdate(),d=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),h=s.useShareTenantWideRole(),x=s.useShareGroupWideRole(),g=A.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedGroups:o,groupsToRemove:c,groupsToUpdate:i,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}),[t,n,a,r,l,o,c,i,d,u,m,h,x]),b=A.useMemo(()=>j=>s.validateShareData(j),[]),p=A.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!d)return!1}else if(n==="specificTenantUsers")return d?a.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||l.length>0:!0;case"group-share":return n==="specificGroups"?o.length>0||c.length>0||i.length>0:!0}return!1},[t,n,a,r,l,o,c,i,d]);return{buildShareData:g,validateShareData:b,isCurrentStateValid:p,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}};function _s({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSelectedTenant(),b=s.useShareOrgWideRole(),p=s.useShareAllTenantsRole(),j=s.useShareTenantWideRole(),{buildShareData:f,validateShareData:y,isCurrentStateValid:k}=xt(),T=a||r||l,N=()=>{var O,I,B,E;if(T)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const w=m.length+h.length+x.length;return w===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${w} user${w!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&x.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Update access for ${x.length} user${x.length!==1?"s":""}`:`Update access for ${w} user${w!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const w=d.role;return b===w?"Remove Access":"Update Access"}else if(i==="all_tenants"){const w=(I=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:I[0];if(!w||w.role===void 0)return"Share with All Tenants";const M=w.role;return p===M?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const w=(E=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:E[0];if(!w||w.role===void 0)return"Share with All Tenant Users";const M=w.role;return j===M?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const w=m.length+h.length+x.length;return w===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${w} user${w!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&x.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Update access for ${x.length} user${x.length!==1?"s":""}`:`Update access for ${w} user${w!==1?"s":""}`}return"Share"},D=()=>T||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!k,v=()=>{const O=f();O&&y(O)&&o(O)},S=()=>{var O,I,B,E;if(i==="all_users")if(!d||d.role===void 0){const w=f();w&&y(w)&&o(w)}else{const w=d.role;if(b===w)u==null||u();else{const F=f();if(F&&y(F)){const R={...F,updateAccess:!0};o(R)}}}else if(i==="all_tenants"){const w=(I=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:I[0];if(!w||w.role===void 0){const M=f();M&&y(M)&&o(M)}else{const M=w.role;if(p===M)u==null||u();else{const R=f();if(R&&y(R)){const L={...R,updateAccess:!0};o(L)}}}}else if(i==="all_tenant_users"){const w=(E=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:E[0];if(!w||w.role===void 0){const M=f();M&&y(M)&&o(M)}else{const M=w.role;if(j===M)u==null||u();else{const R=f();if(R&&y(R)){const L={...R,updateAccess:!0};o(L)}}}}},C=()=>{var O,I,B,E;if(i==="all_users"){if(!d||d.role===void 0)return"default";const w=d.role;return b===w?"destructive":"default"}else if(i==="all_tenants"){const w=(I=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:I[0];if(!w||w.role===void 0)return"default";const M=w.role;return p===M?"destructive":"default"}else if(i==="all_tenant_users"){const w=(E=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:E[0];if(!w||w.role===void 0)return"default";const M=w.role;return j===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:T,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||x.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||T,variant:"default",children:[T?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!T&&N()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:S,disabled:D(),variant:C(),children:[T?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),!T&&N()]})]})}function gn({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),h=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),g=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const b=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:j,isCurrentStateValid:f}=xt(),y=n||a||r,k=()=>{if(y)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const C=d.length+u.length+m.length;return C===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${C} user${C!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${C} user${C!==1?"s":""}`}else if(c==="groups"){if(h.length===0&&x.length===0&&g.length===0)return"Select groups to share with";const C=h.length+x.length+g.length;return C===0?"Select groups to share with":h.length>0&&x.length>0?`Update access for ${C} group${C!==1?"s":""}`:x.length>0&&h.length===0&&g.length===0?`Remove access for ${x.length} group${x.length!==1?"s":""}`:h.length>0&&x.length===0&&g.length===0?`Share with ${h.length} group${h.length!==1?"s":""}`:g.length>0&&h.length===0&&x.length===0?`Update access for ${g.length} group${g.length!==1?"s":""}`:`Update access for ${C} group${C!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const C=i.role;return b===C?"Remove Access":"Update Access"}return"Share"},T=()=>y||!t?!0:!f,N=()=>{const C=p();C&&j(C)&&l(C)},D=()=>{const C=p();C&&j(C)&&l(C)},v=()=>{if(!i||i.role==="NONE"){const C=p();C&&j(C)&&l(C)}else{const C=i.role;if(b===C){const I=p();if(I&&j(I)){const B={...I,removeAccess:!0};l(B)}}else{const I=p();if(I&&j(I)){const B={...I,updateAccess:!0};l(B)}}}},S=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:y,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:N,disabled:!t||y,variant:"default",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!y&&k()]})}),c==="groups"&&e.jsx(e.Fragment,{children:(h.length>0||x.length>0||g.length>0)&&e.jsxs(s.Button,{onClick:D,disabled:!t||y,variant:"default",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!y&&k()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:v,disabled:T(),variant:S(),children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Pe,{className:"mr-2 h-4 w-4"}),!y&&k()]})]})}function jn({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllGroupsShare:d,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const g=()=>{o({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:h,groupsToUpdate:x})},b=()=>m.length>0||h.length>0||x.length>0,p=()=>h.length>0&&m.length===0&&x.length===0?"Remove Access":x.length>0&&m.length===0&&h.length===0?"Update Access":"Share with Groups",j=a||r||l;return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[m.length>0&&e.jsxs("span",{children:[m.length," groups selected"]}),h.length>0&&e.jsxs("span",{className:"ml-2 text-destructive",children:["• ",h.length," to remove"]}),x.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",x.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:j,children:"Cancel"}),e.jsxs(s.Button,{onClick:g,disabled:!b()||j,children:[j&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),p()]})]})]})}function ge(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Se(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function bn(t,n,a){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=ge(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const x=ge(r,l,u.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(x,{onSuccess:()=>{d()}})}if(m&&m.length>0){const x=Se(r,l,m.map(g=>{var p,j;const b=(j=(p=i==null?void 0:i.shares)==null?void 0:p.specificOrgUsers)==null?void 0:j.find(f=>f.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(x=>{const g=ge(r,l,[{scope:"specific_org_user",orgUserId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=ge(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=ge(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:x}=t;if(m&&m.length>0){const g=Se(r,l,m.map(b=>{var j,f;const p=(f=(j=i==null?void 0:i.shares)==null?void 0:j.specificTenantUsers)==null?void 0:f.find(y=>y.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,tenantId:x,role:(p==null?void 0:p.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const b=ge(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:x,role:g.newRole}]);o(b,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=ge(r,l,u.map(b=>({scope:"specific_tenant_user",tenantUserId:b.id,tenantId:x,role:b.role})));o(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=Se(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=ge(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=ge(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const x=ge(r,l,u.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(x,{onSuccess:()=>{d()}})}if(m&&m.length>0){const x=Se(r,l,m.map(g=>{var p,j;const b=(j=(p=i==null?void 0:i.shares)==null?void 0:p.specificTenantUsers)==null?void 0:j.find(f=>f.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(x=>{const g=ge(r,l,[{scope:"specific_tenant_user",tenantUserId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"group-share":if(t.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:m,groupsToUpdate:h}=t;if(u&&u.length>0){const x=ge(r,l,u.map(g=>({scope:"group",groupId:g.id,role:g.role})));o(x,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(m&&m.length>0){const x=Se(r,l,m.map(g=>({scope:"group",groupId:g,role:"VIEWER"})));c(x,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Removed access from ${m.length} group${m.length!==1?"s":""}`)}})}h&&h.length>0&&h.forEach(x=>{const g=ge(r,l,[{scope:"group",groupId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{var b;d(),(b=n.resetGroupSelections)==null||b.call(n),s.ue.success("Updated access for group")}})})}break}}function vn(t,n,a,r){var u,m,h,x,g,b;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const p=Se(l,o,t.map(j=>{var y,k;const f=(k=(y=i==null?void 0:i.shares)==null?void 0:y.specificTenantUsers)==null?void 0:k.find(T=>T.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,role:(f==null?void 0:f.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()},onError:j=>{console.error("Remove access failed:",j)}})}else{const p=n==="tenant"&&a==="allTenants",j=n==="tenant"&&a==="allTenantUsers";if(p){const f=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(f){const y=Se(l,o,[{scope:"all_tenants_only",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenants access failed:",k)}})}}else if(j){const f=(x=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:x[0];if(f){const y=Se(l,o,[{scope:"all_tenant_users",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenant-users access failed:",k)}})}}else{const f=(b=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:b[0];if(f){const y=Se(l,o,[{scope:"org_users_only",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:k=>{console.error("Remove org-wide access failed:",k)}})}}}}function yn(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=_e({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=A.useCallback(()=>{r.resetUserSelections()},[r]),m=A.useCallback(()=>{r.resetGroupSelections()},[r]),h=A.useCallback(g=>{if(!t)return;const b={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:u,resetGroupSelections:m};bn(g,b,i)},[t,n,a,d,u,m,i]),x=A.useCallback(()=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:u};vn(l,o||"",c||"",g)},[t,n,a,d,u,m,l,o,c]);return{handleShareSubmit:h,handleRemoveAccess:x}}function is({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var E,w,M,F,R,L,P,Y;const{currentUser:o}=s.useCurrentUserInfo(),[c,i]=A.useState("specific_users"),[d,u]=A.useState("specific_users"),[m,h]=A.useState("specific_groups"),x=s.useShareManagementActions(),g=s.useShareSelectedTab(),b=s.useShareCurrentMode(),p=s.useShareResource(),j=s.useRemoveResourceShares(),{handleShareSubmit:f,handleRemoveAccess:y}=yn(t.id,(J,V)=>{p.mutate(J,{...V,onSuccess:()=>{var K;(K=V==null?void 0:V.onSuccess)==null||K.call(V),r==null||r()}})},(J,V)=>{j.mutate(J,{...V,onSuccess:()=>{var K;(K=V==null?void 0:V.onSuccess)==null||K.call(V),l==null||l()}})}),k=p.isPending,T=j.isPending,N=p.isPending,{existingShares:D}=_e({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:v}=_e({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),S=(w=(E=D==null?void 0:D.shares)==null?void 0:E.tenantWide)==null?void 0:w[0],C=(F=(M=v==null?void 0:v.shares)==null?void 0:M.orgUsersOnly)==null?void 0:F[0],O=()=>{if(g==="org")return d;switch(b){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},I=A.useCallback(()=>{x.resetShareState(),a()},[x,a]),B=(o==null?void 0:o.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:I,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:B?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),B?e.jsxs(s.Tabs,{value:g,onValueChange:J=>{const V=J;x.setSelectedTab(V),x.resetUserSelections(),x.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-3",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"}),e.jsx(s.TabsTrigger,{value:"groups",children:"Groups"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(hn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:u,isSharing:k,isUpdating:N,isRemoving:T})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Vs,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:J=>i(J),isSharing:k,isUpdating:N,isRemoving:T})})}),e.jsx(s.TabsContent,{value:"groups",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(fn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:h,isSharing:k,isUpdating:N,isRemoving:T})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Vs,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:J=>i(J),isSharing:k,isUpdating:N,isRemoving:T})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:B?g==="org"?e.jsx(_s,{resource:t,existingShares:v,isSharing:k,isRemoving:T,isUpdating:N,onShare:f,onClose:a,shareTabType:d,currentAllUsersShare:C,onRemoveAccess:y}):g==="tenant"?e.jsx(_s,{resource:t,existingShares:D,isSharing:k,isRemoving:T,isUpdating:N,onShare:f,onClose:a,shareTabType:O(),currentAllUsersShare:S,onRemoveAccess:y}):e.jsx(jn,{resource:t,existingShares:v,isSharing:k,isRemoving:T,isUpdating:N,onShare:f,onClose:a,shareTabType:m,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(L=(R=v==null?void 0:v.shares)==null?void 0:R.allOrgGroups)==null?void 0:L[0]:(Y=(P=D==null?void 0:D.shares)==null?void 0:P.allTenantGroups)==null?void 0:Y[0],onRemoveAccess:y}):e.jsx(gn,{resource:t,isSharing:k,isRemoving:T,isUpdating:N,onShare:f,onClose:a,shareTabType:c,currentAllUsersShare:S,onRemoveAccess:y})})]})})}function pt({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(u=>u.selectedFrameId),l=s.useManagementStore(u=>u.selectedVisual),o=s.useEditorStore(u=>u.frame);let c;if(t)c=t;else if(n!==void 0)c=n?"linked":"library";else if(!!!(o!=null&&o.visualId||l!=null&&l.id)&&r)c="local";else if(l&&!r)c="library";else if(o!=null&&o.visualId&&r)c="linked";else if(l!=null&&l.id&&r)c="library";else return null;const i={local:"bg-gray-100 text-gray-700",linked:"bg-purple-100 text-purple-700",library:"bg-blue-100 text-blue-700"},d={local:"Local Visual",linked:"Linked Visual",library:"Library Visual"};return e.jsx("span",{className:s.cn("rounded-full px-2.5 py-0.5 text-xs font-medium",i[c],a),children:d[c]})}const Nn=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},Cn=async(t,n,a)=>{const r=`${t}/management/v1/groups/${a}`,l=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!l.ok){const o=await l.text();throw new Error(o||"Failed to delete group")}},Sn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},wn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,o=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.text();throw new Error(c||"Failed to remove group members")}};function Dn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Nn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:()=>{a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Group created successfully")},onError:r=>{console.error("Failed to create group:",r),s.ue.error("Failed to create group",{description:r.message})}})}function Tn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Cn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["groups"]}),a.removeQueries({queryKey:["group",l]}),s.ue.success("Group deleted successfully")},onError:r=>{console.error("Failed to delete group:",r),s.ue.error("Failed to delete group",{description:r.message})}})}function kn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Sn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members added successfully")},onError:r=>{console.error("Failed to add group members:",r),s.ue.error("Failed to add members",{description:r.message})}})}function En(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>wn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members removed successfully")},onError:r=>{console.error("Failed to remove group members:",r),s.ue.error("Failed to remove members",{description:r.message})}})}function In({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=A.useState(""),[o,c]=A.useState(""),[i,d]=A.useState({}),u=Dn(),m=()=>{const x={};return r.trim()?r.length<3?x.name="Group name must be at least 3 characters":r.length>50&&(x.name="Group name must be less than 50 characters"):x.name="Group name is required",o&&o.length>200&&(x.description="Description must be less than 200 characters"),d(x),Object.keys(x).length===0},h=async x=>{if(x.preventDefault(),!m())return;const g={name:r.trim(),description:o.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(g),l(""),c(""),d({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:h,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-name",children:["Group Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(s.Input,{id:"group-name",placeholder:"e.g., Marketing Team, Engineering Squad",value:r,onChange:x=>{l(x.target.value),i.name&&d(g=>({...g,name:""}))},className:i.name?"border-destructive":"",disabled:u.isPending}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-description",children:["Description",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(optional)"})]}),e.jsx(s.Textarea,{id:"group-description",placeholder:"Describe the purpose of this group...",value:o,onChange:x=>{c(x.target.value),i.description&&d(g=>({...g,description:""}))},className:i.description?"border-destructive":"",disabled:u.isPending,rows:3}),i.description&&e.jsx("p",{className:"text-sm text-destructive",children:i.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.length,"/200 characters"]})]}),e.jsx("div",{className:"rounded-lg border bg-muted/50 p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This group will be accessible to users in your workspace. You can add members after creating the group."})]})})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(s.Button,{type:"button",variant:"outline",onClick:()=>{l(""),c(""),d({})},disabled:u.isPending,children:"Clear"}),e.jsx(s.Button,{type:"submit",disabled:u.isPending||!r.trim(),children:u.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),"Create Group"]})})]})]})}function An({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,o]=A.useState("members"),[c,i]=A.useState(""),[d,u]=A.useState([]),[m,h]=A.useState([]),{data:x,isLoading:g,refetch:b}=s.useGroupMembers(a.id),p=a.type==="TENANT_GROUP"?"tenant":"organization",{users:j,isLoading:f}=s.useUnifiedUsers({type:p,tenantId:a.tenantId||void 0,active:!0,limit:100}),y=kn(),k=En(),T=(x==null?void 0:x.members)||[],N=A.useMemo(()=>new Set(T.map(E=>E.userId)),[T]),D=A.useMemo(()=>j.filter(E=>!N.has(E.id)),[j,N]),v=A.useMemo(()=>{if(!c)return D;const E=c.toLowerCase();return D.filter(w=>{var M,F;return((M=w.name)==null?void 0:M.toLowerCase().includes(E))||((F=w.email)==null?void 0:F.toLowerCase().includes(E))})},[D,c]),S=A.useMemo(()=>{if(!c)return T;const E=c.toLowerCase();return T.filter(w=>{var M,F,R,L;return((F=(M=w.user)==null?void 0:M.name)==null?void 0:F.toLowerCase().includes(E))||((L=(R=w.user)==null?void 0:R.email)==null?void 0:L.toLowerCase().includes(E))})},[T,c]),C=async()=>{if(d.length!==0)try{await y.mutateAsync({groupId:a.id,data:{userIds:d,userType:p==="tenant"?"tenant":"org"}}),u([]),o("members"),b(),r==null||r()}catch(E){console.error("Failed to add members:",E)}},O=async()=>{if(m.length!==0)try{await k.mutateAsync({groupId:a.id,data:{userIds:m}}),h([]),b(),r==null||r()}catch(E){console.error("Failed to remove members:",E)}},I=E=>{u(w=>w.includes(E)?w.filter(M=>M!==E):[...w,E])},B=E=>{h(w=>w.includes(E)?w.filter(M=>M!==E):[...w,E])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:a.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[T.length," ",T.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",a.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:E=>{o(E),i(""),h([])},className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"members",children:"Current Members"}),e.jsx(s.TabsTrigger,{value:"add",children:"Add Members"})]}),e.jsxs(s.TabsContent,{value:"members",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search members...",value:c,onChange:E=>i(E.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:g?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(E=>e.jsx(s.Skeleton,{className:"h-16 w-full"},E))}):S.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:c?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:S.map(E=>e.jsx(Mn,{member:E,selected:m.includes(E.userId),onToggle:()=>B(E.userId)},E.id))})}),m.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m.length," member",m.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:O,disabled:k.isPending,children:k.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Removing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove Selected"]})})]})]}),e.jsxs(s.TabsContent,{value:"add",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search users to add...",value:c,onChange:E=>i(E.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:f?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(E=>e.jsx(s.Skeleton,{className:"h-16 w-full"},E))}):v.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.UserPlus,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No available users"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:v.map(E=>e.jsx(Ln,{user:E,selected:d.includes(E.id),onToggle:()=>I(E.id)},E.id))})}),d.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[d.length," user",d.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:C,disabled:y.isPending,children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.UserPlus,{className:"mr-2 h-4 w-4"}),"Add Members"]})})]})]})]})]})})})}function Mn({member:t,selected:n,onToggle:a}){var l,o,c,i;const r=((o=(l=t.user)==null?void 0:l.name)==null?void 0:o.split(" ").map(d=>d[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:((c=t.user)==null?void 0:c.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(i=t.user)==null?void 0:i.email})]})]})}function Ln({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(o=>o[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.email})]})]})}function Rn({open:t,onOpenChange:n}){const[a,r]=A.useState("groups"),[l,o]=A.useState(""),[c,i]=A.useState(null),[d,u]=A.useState(!1),[m,h]=A.useState(null),{tokenProps:x}=s.useSemaphorContext(),{currentUser:g}=s.useCurrentUserInfo(),b=Tn(),p=(g==null?void 0:g.type)==="tenant",j=x==null?void 0:x.tenantId,{groups:f,isLoading:y,refetch:k}=s.useGroups({type:p?"TENANT_GROUP":"all",tenantId:p?j:void 0,includeMembers:!1}),T=f.filter(S=>{var C;return S.name.toLowerCase().includes(l.toLowerCase())||((C=S.description)==null?void 0:C.toLowerCase().includes(l.toLowerCase()))}),N=async()=>{if(m)try{await b.mutateAsync(m.id),h(null),k()}catch(S){console.error("Failed to delete group:",S)}},D=S=>{i(S),u(!0)},v=()=>{r("groups"),k()};return e.jsxs(e.Fragment,{children:[e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-4xl max-h-[80vh]",children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Group Management"]}),e.jsx(s.DialogDescription,{children:"Manage your groups, create new groups, and control group membership"})]}),e.jsxs(s.Tabs,{value:a,onValueChange:r,className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsxs(s.TabsTrigger,{value:"groups",className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4"}),"Groups"]}),e.jsxs(s.TabsTrigger,{value:"create",className:"flex items-center gap-2",children:[e.jsx(s.Plus,{className:"h-4 w-4"}),"Create Group"]})]}),e.jsx(s.TabsContent,{value:"groups",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search groups...",value:l,onChange:S=>o(S.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:y?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(S=>e.jsx(s.Skeleton,{className:"h-24 w-full"},S))}):T.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No groups found"}),e.jsx("p",{className:"text-xs mt-1",children:l?"Try a different search":"Create your first group to get started"})]}):e.jsx("div",{className:"space-y-3",children:T.map(S=>e.jsx(On,{group:S,onManageMembers:()=>D(S),onDelete:()=>h(S),currentUserId:g==null?void 0:g.id},S.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(In,{onSuccess:v,tenantId:j,isTenantUser:p})})]})]})}),c&&e.jsx(An,{open:d,onOpenChange:u,group:c,onUpdate:()=>k()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>h(null),children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Group"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.name,'"? This action cannot be undone and will remove all members from the group.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:N,disabled:b.isPending,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete Group"})]})]})})]})}function On({group:t,onManageMembers:n,onDelete:a,currentUserId:r}){const l=t.createdBy===r;return e.jsx("div",{className:"rounded-lg border bg-card p-4 transition-colors hover:bg-muted/50",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:t.name}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:t.description})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(s.Users,{className:"h-3 w-3"}),t.memberCount," ",t.memberCount===1?"member":"members"]}),e.jsxs("span",{children:["Created ",s.format(new Date(t.createdAt),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:n,title:"Manage members",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:a,title:"Delete group",className:"text-destructive hover:text-destructive",children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]})})}function Ds(t){const[n,a]=A.useState(null),[r,l]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),a(null)}})()},[t]),n}function Fn(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Bn(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return n}}return t[0].id}async function Us(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],o=r.getQueryData(l);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const c=s.ue.loading("Loading visual...",{position:"top-center"});try{const i=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!i.ok)throw new Error("Failed to load visual");const d=await i.json();return r.setQueryData(l,d),s.ue.dismiss(c),{data:d,fromCache:!1}}catch(i){throw s.ue.dismiss(c),i}}function ft(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function Pn(t,n){var o,c;const a=(t==null?void 0:t.frameObject)??((o=t==null?void 0:t.visual)==null?void 0:o.frameObject);if(!a)return!1;const r=ft(a);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(c=r.cards)==null?void 0:c.find(i=>i.id===r.activeCardId);return l?(s.setupEditorWithCard({...n,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function zn(){var x;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=Ds(((x=a.customCardPreferences)==null?void 0:x.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),d=s.useEditorStore(g=>g.selectedConnectionId),u=s.useEditorStore(g=>g.isShowingVisual),m=a.sql;return{getUpdatedFrame:A.useCallback(()=>{var f;let g=m;m&&!m.includes("{{")&&(g=Fn(m),t(g));const b=(f=r==null?void 0:r.getState())==null?void 0:f.settings,p={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:u?a.customCfg:null,preferences:a.preferences,...b&&{customCardPreferences:{...a.customCardPreferences,settings:b}}},j=n.cards.map(y=>y.id===a.id?p:y);return{...n,cards:j,activeCardId:Bn(j,n.activeCardId)}},[a,n,u,l,o,c,i,d,t,r,m])}}function Oe(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:g,setSelectedTableName:b,setSelectedDatamodelId:p,setFilterValues:j,setApplyFilters:f}=s.useEditorActions(),{setIsDashboardEditing:y,setIsVisualEditing:k,setSelectedFrameId:T,clearSelectedFrameId:N,addFrame:D,setIsDashboardPanelOpen:v}=s.useDashboardActions(),S=s.useDashboardStore(M=>M.selectedSheetId),C=s.useDashboardStore(M=>M.selectedFrameId),O=s.useDashboardStore(M=>M.dashboard),I=s.useDashboardStore(M=>M.filterValues),B=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),E=A.useCallback(async M=>{try{l(M),N();const{data:F,fromCache:R}=await Us(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a);if(!Pn(F,{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:g,setSelectedTableName:b,setSelectedDatamodelId:p,setFilterValues:j,setApplyFilters:f,setIsDashboardEditing:y,setIsVisualEditing:k,dashboard:O,selectedSheetId:S,selectedFrameId:C,filterValues:I}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:R}}catch(F){return console.error("Error editing visual:",F),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,o,c,y,k,i,d,u,m,h,x,g,b,p,j,f,N,O,S,C,I]),w=A.useCallback(async M=>{var F;try{if(l(M),!S)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:R,fromCache:L}=await Us(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a),P=(R==null?void 0:R.frameObject)??((F=R==null?void 0:R.visual)==null?void 0:F.frameObject);if(!P)return{success:!1,error:"Visual has no frame data"};const Y=ft(P);if(!(Y!=null&&Y.cards)||Y.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const J={...Y,id:s.v4(),visualId:M.id};return D(S,J,"end"),y(!0),T(J.id),v(!1),{success:!0,fromCache:L}}catch(R){return console.error("Error adding visual:",R),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,S,D,y,T,v]);return{visual:B.data,isLoading:B.isLoading,isError:B.isError,error:B.error,handleEditLibraryVisual:E,handleAddLibraryVisual:w,getUpdatedFrame:zn().getUpdatedFrame,refetch:B.refetch}}function Vn({open:t,onOpenChange:n,isLibraryVisual:a,currentVisualName:r,isSaving:l=!1,onConfirm:o}){const[c,i]=A.useState(a&&r?`Copy of ${r}`:r||""),[d,u]=A.useState(""),[m,h]=A.useState(!a),[x,g]=A.useState(!0);A.useEffect(()=>{t&&(i(a&&r?`Copy of ${r}`:r||""),u(""),h(!a),g(!0))},[t,a,r]);const b=()=>{c.trim()&&(!m&&!x||o({name:c.trim(),description:d.trim()||void 0,saveToLibrary:m,saveToCurrentDashboard:x}))},p=c.trim()&&(m||x);return e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Save Visual As"}),e.jsx(s.DialogDescription,{children:a?"Create a copy of this visual with a new name":"Save this visual to make it reusable"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:c,onChange:j=>i(j.target.value),placeholder:"Enter visual name",disabled:l})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Textarea,{id:"description",value:d,onChange:j=>u(j.target.value),placeholder:"Enter visual description",rows:3,disabled:l})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Label,{children:"Save to:"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-dashboard",checked:x,onCheckedChange:j=>g(!!j),disabled:l}),e.jsxs("label",{htmlFor:"save-to-dashboard",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Current Dashboard",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(add copy to this dashboard)":"(keep as local visual)"})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-library",checked:m,onCheckedChange:j=>h(!!j),disabled:l}),e.jsxs("label",{htmlFor:"save-to-library",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Visual Library",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!m&&!x&&e.jsx("p",{className:"text-sm text-destructive",children:"Please select at least one destination"})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),disabled:l,children:"Cancel"}),e.jsxs(s.Button,{onClick:b,disabled:!p||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function gt({className:t,variant:n="outline"}){var i;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(d=>d.frame);const r=s.useEditorStore(d=>d.card);Ds(((i=r.customCardPreferences)==null?void 0:i.url)||""),s.useEditorStore(d=>d.selectedSchemaName),s.useEditorStore(d=>d.selectedDatamodelId),s.useEditorStore(d=>d.selectedDatabaseName),s.useEditorStore(d=>d.selectedTableName),s.useEditorStore(d=>d.selectedConnectionId),s.useEditorStore(d=>d.isShowingVisual),r.sql;const l=s.useEditorStore(d=>d.onSave),{getUpdatedFrame:o}=Oe();function c(){const d=o();l==null||l(d)}return e.jsxs(s.Button,{onClick:c,className:s.cn("h-8",t),size:"sm",variant:n,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function _n({className:t,variant:n="default"}){const a=s.useQueryClient(),[r,l]=A.useState(!1),o=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),{setIsVisualEditing:c}=s.useDashboardActions(),{getUpdatedFrame:i}=Oe(),d=s.useSelectedVisual(),u=s.useEditorStore(x=>x.frame),m=s.useUpdateVisualMutation(),h=()=>{const x=i(),g=(u==null?void 0:u.visualId)||(d==null?void 0:d.id);if(!g){s.ue.error("No visual to save");return}l(!0),m.mutate({visualId:g,data:{frameObject:x}},{onSuccess:()=>{l(!1),o(!0),s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["resource-by-id","visual",g],exact:!0})},onError:()=>{l(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:n,children:[r&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!r&&e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"mr-2 size-4 font-bold"}),"Save to Library"]})]})}function Un({className:t}){const n=s.useQueryClient(),[a,r]=A.useState(!1),l=s.useSelectedVisual(),o=s.useEditorStore(x=>x.frame),c=s.useDashboardStore(x=>x.selectedSheetId),{updateFrame:i,setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:u}=Oe(),m=s.useUpdateVisualMutation(),h=async()=>{if(!c){s.ue.error("No sheet selected");return}const x=(o==null?void 0:o.visualId)||(l==null?void 0:l.id);if(!x){s.ue.error("No visual to update");return}r(!0);try{const g=u();await m.mutateAsync({visualId:x,data:{frameObject:g}});const b={...g,visualId:x};i(c,b),n.invalidateQueries({queryKey:["visuals"]}),n.invalidateQueries({queryKey:["visual",x]}),s.ue.success("Saved to library and applied locally"),setTimeout(()=>{d(!1)},300)}catch(g){console.error("Failed to save and apply:",g),s.ue.error("Failed to save and apply changes")}finally{r(!1)}};return e.jsx(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:"default",disabled:a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"mr-2 size-4 font-bold"}),"Save & Apply"]})})}function Gn({className:t}){const{getUpdatedFrame:n}=Oe();s.useEditorStore(d=>d.frame);const a=s.useDashboardStore(d=>d.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[o,c]=A.useState(!1),i=()=>{if(!a){s.ue.error("No sheet selected");return}c(!0);const u={...n(),visualId:void 0};r(a,u),setTimeout(()=>{c(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:i,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function jt({className:t}){const{setTempQueryData:n,setSqlGen:a}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),o=s.useEditorStore(u=>u.onClose),c=s.useEditorStore(u=>u.card),{queryKey:i}=s.useDashboardCardQuery(c);function d(){if(l){const{queryKey:u,queryData:m}=l;u&&m&&r.setQueryData(u,m)}a({}),o==null||o()}return e.jsxs(s.Button,{onClick:d,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function cs(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(j=>j.isDevMode),r=s.useEditorStore(j=>j.tempQueryData),l=s.useEditorStore(j=>j.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:x,setCardConfig:g,setCardType:b}=s.useEditorActions();function p(){const j=n.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:j}),n.setQueryData(o,null),n.removeQueries({queryKey:o,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),x(),g(void 0),d(""),u(""),m({}),b("bar")}return e.jsxs(s.Button,{onClick:p,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Yn(){const[t,n]=A.useState(!1),[a,r]=A.useState(!1),[l,o]=A.useState(null),c=s.useEditorStore(T=>T.frame),i=s.useEditorStore(T=>T.card),d=s.useSelectedVisual(),u=s.useDashboardStore(T=>T.selectedSheetId),m=s.useDashboardStore(T=>T.actions.setIsDashboardPanelOpen),{getUpdatedFrame:h}=Oe(),{selectVisual:x}=s.useManagementActions(),{addFrame:g,setSelectedFrameId:b,setIsVisualEditing:p}=s.useDashboardActions(),j=!!(c!=null&&c.visualId),f=(d==null?void 0:d.title)||(i==null?void 0:i.title)||"Untitled Visual",y=s.useCreateVisualWithFrame(T=>{if(T!=null&&T.id){if(x(T),a&&l&&u){const N={...l,id:s.v4(),visualId:T.id};g(u,N,"end"),b(N.id),r(!1),o(null),p(!1)}m(!0),n(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:n,handleSaveAs:async T=>{if(!u){s.ue.error("No sheet selected");return}const N=h();if(T.saveToLibrary){r(T.saveToCurrentDashboard),o(N);const D={title:T.name,description:T.description,frameObject:N,isPrivate:!1};y.mutate(D)}else if(T.saveToCurrentDashboard){const D={...N,id:s.v4(),visualId:void 0,cards:N.cards.map(v=>({...v,title:v.id===i.id?T.name:v.title}))};g(u,D,"end"),b(D.id),s.ue.success("Visual saved to dashboard"),n(!1),p(!1)}},isLibraryVisual:j,currentVisualName:f,isSaving:y.isPending}}function bt({className:t}){const n=s.useEditorStore(j=>j.frame),a=s.useManagementStore(j=>j.selectedVisual),r=s.useDashboardStore(j=>j.selectedFrameId),l=s.useDashboardStore(j=>j.selectedSheetId),o=!!(n!=null&&n.visualId||a!=null&&a.id),c=!!(n!=null&&n.visualId&&r),i=o&&!c,{saveAsDialogOpen:d,setSaveAsDialogOpen:u,handleSaveAs:m,isLibraryVisual:h,currentVisualName:x,isSaving:g}=Yn(),{handleAddLibraryVisual:b}=Oe(),p=async()=>{if(!l){s.ue.error("No dashboard sheet selected");return}if(!a){s.ue.error("No visual selected");return}const j=await b(a);j.success?s.ue.success("Visual added to dashboard"):s.ue.error(j.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[e.jsx(jt,{className:t}),!o&&e.jsx(gt,{className:t,variant:"default"}),o&&e.jsxs(e.Fragment,{children:[c&&e.jsx(Gn,{className:t}),i&&l&&e.jsxs(s.Button,{onClick:p,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(xa,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),i&&e.jsx(_n,{className:t,variant:"outline"}),c&&e.jsx(Un,{className:t}),e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:j=>{j.stopPropagation(),u(!0)},children:[e.jsx(Ve,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]})]}),!o&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>u(!0),children:[e.jsx(Ve,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(Vn,{open:d,onOpenChange:j=>{g||u(j)},isLibraryVisual:h,currentVisualName:x,isSaving:g,onConfirm:m})]})}function vt({className:t,labelClassName:n,switchClassName:a}){const r=s.useEditorStore(d=>d.isDevMode),l=s.useDashboardStore(d=>d.isVisualEditing),{setIsDevMode:o}=s.useEditorActions(),{config:c}=A.useContext(s.SemaphorContext).tokenProps,i=(c==null?void 0:c.showAdvancedMode)!==!1;return!l||!i?null:e.jsxs("div",{className:s.cn("flex items-center space-x-2",t),children:[e.jsx(s.Switch,{className:s.cn("",a),checked:r,onCheckedChange:()=>o(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:s.cn("text-sm font-medium",n),children:"Advanced Mode"})]})}function $n(){var de,xe,pe;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:o}=s.useRoleAwareDisplayPreferences(),c=s.useHasDashboardId();s.useDashboardStore(Q=>Q.theme);const i=s.useDashboardStore(Q=>Q.lenses),d=s.useDashboardStore(Q=>Q.selectedLensId),u=i==null?void 0:i.find(Q=>Q.id===d),m=s.useDashboardStore(Q=>Q.dashboard);s.useDashboardStore(Q=>Q.selectedSheetId);const h=s.useDashboardStore(Q=>Q.isDashboardEditing),[x,g]=A.useState(!1),[b,p]=A.useState(!1),[j,f]=A.useState(!1),y=s.useDashboardStore(Q=>Q.isDashboardPanelOpen),k=s.useDashboardStore(Q=>Q.actions.setIsDashboardPanelOpen),T=s.useDashboardStore(Q=>Q.filterValues),N=s.useDashboardStore(Q=>Q.isVisualEditing),D=s.useEditorStore(Q=>Q.card),v=s.useManagementStore(Q=>Q.selectedDashboard),S=s.useManagementStore(Q=>Q.initialDashboard),C=s.useManagementStore(Q=>Q.selectedVisual);s.useDashboardStore(Q=>Q.selectedFrameId),s.useEditorStore(Q=>Q.frame);const O=v?(xe=v==null?void 0:v.permissions)==null?void 0:xe.canEdit:(de=S==null?void 0:S.permissions)==null?void 0:de.canEdit,I=s.useDashboardStore(Q=>Q.showFilters),B=s.useDashboardStore(Q=>Q.showDashboardJSON),E=s.useDashboardStore(Q=>Q.onSaveFunction),w=s.useDashboardStore(Q=>Q.actions.setShowFilters),{setIsDashboardEditing:M,setShowDashboardJSON:F}=s.useDashboardStore(Q=>Q.actions),{setInitialDashboard:R,clearSelectedDashboard:L}=s.useManagementStore(Q=>Q.actions),{resources:P}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:Y}=s.useCurrentUserInfo(),J=s.canUserManageGroups(Y),V=v||S,K=V?{id:V.id,title:(m==null?void 0:m.title)||V.title||"Dashboard"}:null,{handleAddNewFrame:q}=s.useAddNewFrame(),[Z,$]=A.useState(!1),X=s.useUpdateResource(s.ResourceType.DASHBOARD);A.useEffect(()=>{if(P&&P.length>0){const Q=m==null?void 0:m.id;if(Q){const U=P.find(H=>H.id===Q);U&&R(U)}}},[P,m==null?void 0:m.id,R]);const _=n.orgUserId||n.tenantId,G=h&&!N&&_&&O,se=()=>{M(!0)};async function re(){const Q=as(m);$(!0);const U={template:Q};X.mutate({resourceId:Q.id,data:U},{onSuccess:()=>{$(!1),s.ue.success("Dashboard saved!")},onError:()=>{$(!1),s.ue.error("Failed to save dashboard")}})}async function he(){if(g(!0),!d||!u)return;const Q=as(m),U=JSON.stringify(Q),H={...u,template:U,filterValues:T};await ys(n.apiServiceUrl,H,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),E==null||E(Q),g(!1)}const z=(u==null?void 0:u.name)||m.title,ne=P&&P.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),le=v&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-11 items-center justify-between gap-2 border-b px-4 py-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ne&&e.jsxs(e.Fragment,{children:[le&&!N&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>L(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:c?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>{c&&k(!y)},className:"h-7 p-2",buttonProps:{disabled:!c},children:e.jsx(Aa,{className:"h-4 w-4"})})]}),!N&&c&&e.jsx(s.Label,{children:z}),N&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm font-medium",children:(C==null?void 0:C.title)||(D==null?void 0:D.title)||"Untitled Visual"}),e.jsx(pt,{})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[N&&e.jsxs(e.Fragment,{children:[e.jsx(vt,{className:"mr-2"}),e.jsx(bt,{className:"h-7"})]}),r&&!N&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(Ua,{className:"h-4 w-4"})}),!N&&c&&e.jsx(sn,{}),!N&&c&&e.jsx(nt,{}),!N&&c&&J&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!N&&c&&((pe=V==null?void 0:V.permissions)==null?void 0:pe.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),h&&!N&&_&&r&&c&&e.jsx(Za,{}),!N&&_&&r&&c&&e.jsx(en,{}),h&&!N&&_&&u&&r&&c&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:x,onClick:he,size:"sm",children:[e.jsx(Ve,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),h&&!N&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!h,onClick:()=>q(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!N&&!h&&o.canEdit&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:se,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),h&&!N&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{M(!1),F(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),G&&c&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:Z,onClick:re,size:"sm",children:[Z?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ve,{className:"mr-2 h-4 w-4"}),Z?"Saving...":"Save"]}),!I&&!N&&h&&o.canUseFilters&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>w(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!N&&h&&r&&c&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>F(!B),size:"sm",variant:"ghost",children:e.jsx(ze,{className:"h-4 w-4"})})}),!N&&r&&e.jsx(Ka,{}),b&&K&&e.jsx(is,{resource:K,resourceType:s.ResourceType.DASHBOARD,onClose:()=>p(!1)}),e.jsx(Rn,{open:j,onOpenChange:f})]})]})}function qn({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:u=!1}){const m=Ee.useRef(null),[h,x]=Ee.useState(!1),[g,b]=Ee.useState("100%"),p=u?[...n||[],{id:"none",name:"None"}]:n;Ee.useLayoutEffect(()=>{m.current&&b(m.current.offsetWidth)},[]);function j(){var y;return l?"Loading...":o?"Error":a?(y=n==null?void 0:n.find(k=>k.id===a))==null?void 0:y.name:`Select ${t}`}function f(y,k){r(k),x(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:x,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:j()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:g},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(Zs,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:p==null?void 0:p.map(y=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:y.name,onSelect:k=>f(k,y.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===y.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:y.name,children:y.name})]})},y.id))})]})]})})]})}function Be({title:t,items:n,value:a,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":a;function x(){if(t==="Connection")return e.jsx(za,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Oa,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(ua,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:u,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(Zs,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((p,j)=>e.jsx(s.SelectItem,{value:p.id,children:p.name},j))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function b(){return e.jsx(qn,{icon:x(),items:n,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?g():b()})})}function Hn({column:t}){const[n,a]=A.useState(!1),r=s.useEditorStore(p=>p.selectedTableName),l=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedDatabaseName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(p=>p.actions.setSqlGen),h=s.useEditorStore(p=>p.actions.setCardSql),x=s.useEditorStore(p=>p.actions.setRunSql);function g(p,j){var T;const f=s.createSqlGenConfig(p,i,j),y=(T=d==null?void 0:d.find(N=>N.id===c))==null?void 0:T.name;m(f);const k=s.getSql(f,s.fmt(l||""),s.fmt(r),y||"",u,o||"");k&&(h(k),x(!0)),a(!1)}function b(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>g(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>g(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>g(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>g(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>g(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]})}function Wn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ze,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(qe,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ke,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function ms({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",n),children:[e.jsx(Wn,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Kn({id:t,children:n,type:a="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:a}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:n})}function Qn({onClick:t,column:n}){const a=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function u(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(n),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(ms,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(ms,{column:n})}),e.jsx(Kn,{id:n.column_name,type:"column",children:e.jsx(ms,{column:n})})]})}const hs={id:"__placeholder__",role:"groupby",type:"string"},xs={id:"__placeholder__",role:"groupby",type:"string"},ps={id:"__placeholder__",role:"metric",type:"number"},fs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},yt={id:"__placeholder__"},Ie="droppable-group-by",Ae="droppable-metrics",Me="droppable-pivot-by",rs="sortable-group-by",Ns="sortable-metrics",ls="sortable-pivot-by",Cs="droppable-filters",Ss="sortable-filters",Ts="sortable-order-by";function Jn(){const t=s.useDndStore(w=>w.insertIndex),n=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.groupByColumns)||[]}),a=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.metricColumns)||[]}),r=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.filterColumns)||[]}),l=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.orderBy)||[]}),o=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:x,setMetricColumns:g,setFilterColumns:b,setOrderByColumns:p,setPivotByColumns:j}=s.useEditorActions(),{columns:f}=s.useDataColumns(),{formattedTableName:y}=s.useEditorAside(),k=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),T=w=>{var R;const{active:M,over:F}=w;if(((R=M.data.current)==null?void 0:R.type)==="column"&&F){const L=F.id,P=f.find(K=>K.column_name===M.id);if(!P)return;const Y=s.isNumberDataType(P.data_type),J=s.isTextDataType(P.data_type),V=s.isDateDataType(P.data_type);if(J||V){if(n.some(q=>q.id===L)){const q=n.findIndex($=>$.id===L);c(q);const Z=n.filter($=>$.id!==hs.id);Z.splice(q,0,hs),d(Z)}else if(F.id===Ie){c(n.length);const q=[...n,hs];d(q),u(a),m(r)}}if(J||V){if(o.some(q=>q.id===L)){const q=o.findIndex($=>$.id===L);c(q);const Z=o.filter($=>$.id!==xs.id);Z.splice(q,0,xs),h(Z)}else if(F.id===Me){c(o.length);const q=[...o,xs];h(q),d(n),u(a),m(r)}}if(Y||J){if(a.some(q=>q.id===L)){console.log("isOverMetricSortable",L);const q=a.findIndex($=>$.id===L);c(q);const Z=a.filter($=>$.id!==ps.id);Z.splice(q,0,ps),u(Z)}else if(F.id===Ae){c(a.length);const q=[...a,ps];u(q),m(r),d(n),h(o)}}if(D(P)){if(r.some(q=>q.id===L)){const q=r.findIndex($=>$.id===L);c(q);const Z=r.filter($=>$.id!==fs.id);Z.splice(q,0,fs),m(Z)}else if(F.id===Cs){c(r.length);const q=[...r,fs];m(q),u(a),d(n),h(o)}}}else d(n),u(a),m(r),h(o)};function N(w){i(w.active.id),c(null),d(n),u(a),m(r),h(o)}function D(w){return!r.some(M=>M.name===w.column_name)}function v(w,M="SUM"){const{column_name:F,data_type:R}=w,L=[...a],P=t!==null?t:a.length,Y={...w,id:Ne(F),name:F,label:We(F,M),type:R,role:"metric",aggregate:M};L.splice(P,0,Y),g(L)}function S(w){const M=s.isTextDataType(w.data_type);s.isDateDataType(w.data_type);const F=[...o],R=t!==null?t:o.length;let L;M?L={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,role:"groupby"}:L={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,role:"groupby",label:Ue(w.column_name,"month"),granularity:"month"},F.splice(R,0,L),j(F)}function C(w){const M=s.isTextDataType(w.data_type);s.isDateDataType(w.data_type);const F=[...n],R=t!==null?t:n.length;let L;M?L={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,role:"groupby"}:L={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,role:"groupby",label:Ue(w.column_name,"month"),granularity:"month"},F.splice(R,0,L),x(F)}function O(w){const M=[...r],F=t!==null?t:r.length,R={...w,id:Ne(w.column_name),name:w.column_name,type:w.data_type,sql:s.getDefaultFilterSql(w.data_type,y,s.fmt(w.column_name)),role:"filter"};M.splice(F,0,R),b(M)}function I(w){var L,P,Y,J,V,K,q,Z;const{active:M,over:F}=w,R=M.data.current;if((R==null?void 0:R.type)==="column"&&F){const $=f.find(se=>se.column_name===M.id);if(!$)return;const X=s.isNumberDataType($.data_type),_=s.isTextDataType($.data_type),G=s.isDateDataType($.data_type);(_||G)&&(F.id===Ie||((L=F.data.current)==null?void 0:L.type)===rs)&&C($),(_||G)&&(F.id===Me||((P=F.data.current)==null?void 0:P.type)===ls)?S($):(X||_)&&(F.id===Ae||((Y=F.data.current)==null?void 0:Y.type)===Ns)?(X&&v($),_&&v($,"COUNT")):D($)&&(F.id===Cs||((J=F.data.current)==null?void 0:J.type)===Ss)&&O($)}if(F&&((V=F.data.current)==null?void 0:V.type)===rs&&n.some($=>$.id===M.id)){const $=n.findIndex(_=>_.id===M.id),X=n.findIndex(_=>_.id===F.id);if($!==-1&&X!==-1&&$!==X){const _=[...n],[G]=_.splice($,1);_.splice(X,0,G),x(_)}}if(F&&((K=F.data.current)==null?void 0:K.type)===ls&&o.some($=>$.id===M.id)){const $=o.findIndex(_=>_.id===M.id),X=o.findIndex(_=>_.id===F.id);if($!==-1&&X!==-1&&$!==X){const _=[...o],[G]=_.splice($,1);_.splice(X,0,G),j(_)}}if(F&&((q=F.data.current)==null?void 0:q.type)===Ns&&a.some($=>$.id===M.id)){const $=a.findIndex(_=>_.id===M.id),X=a.findIndex(_=>_.id===F.id);if($!==-1&&X!==-1&&$!==X){const _=[...a],[G]=_.splice($,1);_.splice(X,0,G),g(_)}}if(F&&((Z=F.data.current)==null?void 0:Z.type)===Ss&&r.some($=>$.id===M.id)){const $=r.findIndex(_=>_.id===M.id),X=r.findIndex(_=>_.id===F.id);if($!==-1&&X!==-1&&$!==X){const _=[...r],[G]=_.splice($,1);_.splice(X,0,G),b(_)}}B(w),i(null),c(null),d(n),u(a),m(r),h(o)}function B(w){const{active:M,over:F}=w,R=M.data.current;if((R==null?void 0:R.type)===Ts&&F){const L=l.findIndex(Y=>$e(Y.columnId)===M.id),P=l.findIndex(Y=>$e(Y.columnId)===F.id);if(L!==-1&&P!==-1&&L!==P){const Y=[...l],[J]=Y.splice(L,1);Y.splice(P,0,J),p(Y)}}}function E(){i(null),c(null),d(n),u(a),m(r)}return{handleDragOver:T,handleDragEnd:I,handleDragStart:N,handleDragCancel:E,sensors:k}}function Ne(t){return`${t}-${s.v4()}`}function We(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"SUM":return`Sum of ${a}`;case"COUNT":return`Count of ${a}`;case"DISTINCT":return`Unique ${a}`;case"AVG":return`Average of ${a}`;case"MIN":return`Min of ${a}`;case"MAX":return`Max of ${a}`;default:return a}}function $e(t){return`${Ts}-${t}`}function Ue(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function Xn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ze,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(qe,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ke,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function Zn({schemaName:t,tableName:n,columns:a,status:r}){const[l,o]=A.useState(""),[c,i]=A.useState("all"),d=s.useEditorStore(L=>L.sqlGen),u=s.useEditorStore(L=>L.isDevMode);s.useEditorStore(L=>L.selectedConnectionId);const m=s.useEditorStore(L=>{var P,Y;return(Y=(P=L.card)==null?void 0:P.queryConfig)==null?void 0:Y.metricColumns});s.useEditorStore(L=>{var P,Y;return(Y=(P=L.card)==null?void 0:P.queryConfig)==null?void 0:Y.groupByColumns});const h=s.useEditorStore(L=>L.selectedDatabaseName);s.useEditorStore(L=>L.selectedSchemaName),s.useEditorStore(L=>L.selectedTableName);const x=s.useEditorStore(L=>L.selectedDatamodelId);s.useDashboardStore(L=>L.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:b}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:j,setCardSql:f,setRunSql:y,setSqlGen:k,setIsShowingVisual:T}=s.useEditorActions(),{connectionType:N,modelItems:D,selectedDatamodelName:v}=s.useEditorAside();function S(L){var P;if(u){const Y=s.createSqlGenConfig(L,d);k(Y);const J=(P=D==null?void 0:D.find(K=>K.id===x))==null?void 0:P.name,V=s.getSql(Y,s.fmt(t),s.fmt(n),J||"",N,h||"");V&&(f(V),y(!0))}if(!u){if(s.isTextDataType(L.data_type))if(m&&m.length>0){const Y={...L,role:"groupby",id:Ne(L.column_name),name:L.column_name,type:L.data_type};j(Y)}else{const Y={...L,role:"metric",id:Ne(L.column_name),name:L.column_name,label:We(L.column_name,"COUNT"),type:L.data_type,aggregate:"COUNT"};p(Y)}if(s.isDateDataType(L.data_type)){const Y={...L,role:"groupby",id:Ne(L.column_name),name:L.column_name,type:L.data_type,label:Ue(L.column_name,"month"),granularity:"month"};j(Y)}if(s.isNumberDataType(L.data_type)){const Y={...L,role:"metric",id:Ne(L.column_name),name:L.column_name,label:We(L.column_name,"SUM"),type:L.data_type,aggregate:"SUM"};p(Y)}}}function C(){const L=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:N,databaseName:h||""});T(!1);const P=N==="MSSQL"?`SELECT top 10 * FROM ${L}`:`SELECT * FROM ${L} LIMIT 10`;f(P),y(!0)}function O(){const L=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:N,databaseName:h||""});f(`SELECT COUNT(*) as count FROM ${L}`),y(!0)}const I=(a==null?void 0:a.filter(L=>L.column_name.toLowerCase().includes(l.toLowerCase())))||[],B=L=>s.isNumberDataType(L.data_type)?"number":"text",E=c==="all"?I:I.filter(L=>B(L)===c),w=I.filter(L=>B(L)==="text").length,M=I.filter(L=>B(L)==="number").length;function F(L){return u?e.jsxs("div",{className:"group flex cursor-pointer items-center justify-between border border-dashed border-background px-2 py-[6px] text-sm transition-colors hover:bg-muted/50",onClick:()=>S(L),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xn,{dataType:L.data_type}),e.jsx("span",{children:L.column_name})]}),e.jsx("div",{onClick:P=>P.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(L.data_type)&&e.jsx(Hn,{column:L})})]}):e.jsx(Qn,{onClick:S,column:L})}function R(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:C,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Ia,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:O,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(et,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-4",children:Array.from({length:3}).map((L,P)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},P))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[u&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:R()}),a&&a.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:L=>o(L.target.value)})]}),I.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:L=>i(L),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:I.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:w})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:M})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[E.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),E.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:E==null?void 0:E.map(L=>e.jsx("div",{children:F(L)},L.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Nt({ColumnsComponent:t,type:n}){var Q;const[a,r]=A.useState(!1),{isConsoleMode:l}=s.useDashboardPreferences(),o=s.useEditorStore(U=>U.card),c=s.useEditorStore(U=>U.selectedConnectionId),i=s.useDashboardStore(U=>U.showFilters),d=s.useEditorStore(U=>U.selectedDatamodelId),u=s.useEditorStore(U=>U.selectedDatabaseName),m=s.useEditorStore(U=>U.selectedSchemaName),h=s.useEditorStore(U=>U.selectedTableName);s.useEditorStore(U=>U.isDevMode);const{setSelectedTableName:x,setIsDevMode:g,setCardSql:b}=s.useEditorActions(),{connectionItems:p,modelItems:j,schemaItems:f,databaseItems:y,tableItems:k,columns:T,isConnectionsLoading:N,isModelsLoading:D,isConnectionsError:v,isModelsError:S,isDatabasesLoadingOrFetching:C,isDatabaseError:O,isSchemaLoadingOrFetching:I,isSchemaError:B,isColumnsError:E,isColumnsLoadingOrFetching:w,isTableLoadingOrFetching:M,isTableError:F,connectionType:R,isNonDbConnection:L,refetchDatabases:P,refetchModels:Y,refetchSchemas:J,refetchTables:V,refetchColumns:K,refetchConnections:q,handleConnectionChange:Z,handleDatabaseChange:$,handleSchemaChange:X,handleDatamodelChange:_,handleTableChange:G,tableName:se,schemaName:re}=s.useEditorAside(),{data:he,refetch:z}=s.useDashboardCardQuery(o);function ee(){return t?t(re,se,T):e.jsx(Zn,{schemaName:re,tableName:se,columns:T,status:w?"Loading...":E?"Error":"Success"})}function ne(){if(!c||R==="S3"||R==="API")return null;if(!d||d==="none")return e.jsx(Be,{refetch:P,showNone:!0,onChange:$,isError:O,isLoading:C,items:y,value:u||"",title:"Database",type:"combobox"})}function le(){if(c&&!L&&(!u||u==="none")&&(!d||d==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function de(){if(!c||R==="S3"||R==="API")return null;if(!u||u==="none")return e.jsx(Be,{refetch:Y,showNone:!0,onChange:_,isError:S,isLoading:D,items:j,value:d||"",title:"Model",type:"combobox"})}function xe(){return!c||R==="S3"||R==="API"||!u||u==="none"?null:e.jsx(Be,{refetch:J,onChange:X,isError:B,isLoading:I,items:f,value:m||"",title:"Schema",type:"combobox"})}function pe(){function U(){let H=!1;return R==="API"?(H=!1,H):((R==="S3"||c&&u&&u!=="none"&&m)&&(H=!0),H)}return U()?e.jsx(Be,{refetch:V,onChange:G,isError:F,items:k,isLoading:M,value:h||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!i}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":a,"px-4 py-4":!a}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!a),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:a?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!a&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Be,{refetch:q,items:p,title:"Connection",value:c||"",onChange:Z,isLoading:N,isError:v,type:"combobox",connectionTooltip:((Q=p==null?void 0:p.find(U=>U.id===c))==null?void 0:Q.type)||""}),ne(),le(),de(),xe(),pe()]})]}),ee(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&l&&e.jsx(e.Fragment,{})})]})}function Ct({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:l=!0}){const[o,c]=A.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",r),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Query Error"}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),l&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(La,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function St({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){o(!l),c(t),setTimeout(()=>{i(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[n&&e.jsx(Ct,{error:n,errorSql:a,showFeedbackButton:!1}),!n&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!n&&e.jsxs(s.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(va,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&r&&e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(wa,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function wt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(pa,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(St,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function er(t){return s.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function Dt(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(p=>p.theme),r=s.useEditorStore(p=>p.frame),l=s.useEditorStore(p=>p.card),o=s.useEditorStore(p=>p.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=A.useRef(),h=A.useRef({}),x=r.cards.find(p=>p.id===o),g=A.useCallback(()=>{let p="";return t==="python"&&(p=(x==null?void 0:x.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(p=(x==null?void 0:x.sql)||""),p},[t,x]);A.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const p=m.current.getModel();p&&(h.current[l.id]=p);let j=h.current[o];if(!j){const f=g();j=c.editor.createModel(f,t),h.current[o]=j}m.current.setModel(j)}d(o,l),u(!0)}},[o,l,d,c,u,t,g]),A.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=a==="system"?p:a;c.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),A.useEffect(()=>{const p=m.current;p&&c&&l&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function b(p,j){if(m.current=p,!h.current[l.id]){const f=p.getModel(),y=g();h.current[l.id]=f||(j==null?void 0:j.editor.createModel(y,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:b}}function sr(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Dt("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function tr(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Dt("python");function r(l){n(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function ar({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function nr(){const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=A.useState(!1),[l,o]=A.useState(!1);s.useEditorStore(V=>V.frame);const c=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.isShowingVisual),s.useEditorStore(V=>V.selectedConnectionId),s.useEditorStore(V=>V.tempQueryData),s.useEditorStore(V=>V.selectedDatabaseName),s.useEditorStore(V=>V.selectedDatamodelId),s.useEditorStore(V=>V.selectedSchemaName);const i=s.useEditorStore(V=>V.showAIDialog);s.useEditorStore(V=>V.selectedTableName);const d=s.useEditorStore(V=>{var K;return(K=V==null?void 0:V.card)==null?void 0:K.sql}),u=s.useEditorStore(V=>{var K;return(K=V==null?void 0:V.card)==null?void 0:K.python}),{sheetFilterValues:m}=s.useSheetFilterValues(),{setCardCustomCfg:h,setQueryResultColumns:x,setCardSql:g,setTempQueryData:b,setPythonStdOut:p,setCardPreferences:j,setCardType:f,setCardPython:y,runAssistant:k,setShowAIDialog:T}=s.useEditorActions();s.useEditorStore(V=>V.onSave),s.useEditorStore(V=>V.onClose),s.useEditorStore(V=>V.actions.setSqlGen);const N=s.useEditorStore(V=>V.runSql),D=s.useEditorStore(V=>V.actions.setRunSql),v=s.useEditorStore(V=>V.actions.setIsSqlRunning),{data:S,isLoading:C,isFetching:O,isSuccess:I,isError:B,error:E,errorSql:w,queryKey:M,refetch:F,errorMessage:R}=s.useDashboardCardQuery(c);A.useEffect(()=>{if(S&&(S.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),p((S==null?void 0:S.output)||""),S.records.length>0)){const{dimensionKeys:V}=s.getKeys(S.records);x(V)}},[S,x,p]),A.useEffect(()=>{(C||O)&&v(!0),(B||I)&&v(!1),B&&(x([]),p(""))},[C,O,S,p,B,I,v,x,E]),A.useEffect(()=>{N&&(t.getQueryData(M)||F(),D(!1))},[N,F,D,M,t]);async function L(){const V=`Can you help me debug this query?
|
|
317
317
|
|
|
318
318
|
Error:
|
|
319
319
|
|
|
@@ -329,12 +329,12 @@
|
|
|
329
329
|
|
|
330
330
|
${u?`Python:
|
|
331
331
|
${u}`:""}
|
|
332
|
-
`;E(V)}function B(){return e.jsxs(e.Fragment,{children:[l&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(tr,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>o(!l),className:"absolute bottom-0 right-6 size-7 p-1",children:l?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function Y(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(er,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(sr,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function J(){return e.jsx("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:S||F,onClick:()=>{O()},className:"h-8 shrink-0",size:"sm",children:[S||F?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(wt,{errorSql:w,sql:C==null?void 0:C.sql,error:R,onDebugWithAssistant:L}),e.jsx(cs,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:V=>r(V),className:"h-8",size:"sm",variant:"outline",children:e.jsx(Zn,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:i,onClick:()=>{T(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:i?"":"Type your question..."})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[Y(),B()]}),J()]})}const nr=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:os}];function rr({className:t}){const n=s.useEditorStore(d=>d.card),{setCardType:a,setCard:r,updateCardInFrame:l}=s.useEditorActions(),o=["table","aggregateTable","pivotTable"].includes(n.type),c=s.hasValidCardConfig(n.config);if(!o||!c)return null;const i=d=>{var m;const u=d;if(u==="aggregateTable"&&((m=n.config)!=null&&m.pivotByColumns)&&n.config.pivotByColumns.length>0){const h={...n,type:u,config:{...n.config,pivotByColumns:[]}};r(h),l(h)}else{a(u);const h={...n,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:i,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:nr.map(d=>{const u=d.icon,m=n.type===d.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:d.value,id:`table-type-${d.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${d.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",m?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),d.label]})]},d.value)})})})}function lr({card:t}){var E,T,N,D,v,C,S,F,I,P,k;const[n,a]=A.useState(!1),[r,l]=A.useState([]),{authToken:o}=s.useSemaphorContext(),{theme:c}=s.useTheme(),i=s.getTokenParams(o==null?void 0:o.accessToken),d=s.useDashboardStore(w=>w.themeStyle),u={mode:c||"system",colors:((T=(E=d==null?void 0:d.chart)==null?void 0:E.dataset)==null?void 0:T.backgroundColor)||[]};(N=t.customCardPreferences)!=null&&N.inputData;const{getCard:m}=s.useCustomVisual(((D=t.customCardPreferences)==null?void 0:D.url)||""),h=((v=t.customCardPreferences)==null?void 0:v.visualType)||"single",x=s.useEditorStore(w=>w.frame),{setCustomCardPreferences:j}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(t),p=A.useCallback((w,M)=>{l(O=>({...O,[w]:M}))},[]);if(!((C=t.customCardPreferences)!=null&&C.componentName))return null;const g=m((S=t.customCardPreferences)==null?void 0:S.componentName);function f(w){a(w)}const y=Object.keys(((F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)||{}).map(w=>{var R,L,B;const M=(L=(R=t.customCardPreferences)==null?void 0:R.dataInputCardIds)==null?void 0:L[w].cardId,O=(B=x==null?void 0:x.cards)==null?void 0:B.find(Y=>Y.id===M);return O||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(A.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[g&&h==="single"&&e.jsx(g,{editing:!0,params:i,theme:u,settings:(I=t.customCardPreferences)==null?void 0:I.settings,onDataChange:p,data:(b==null?void 0:b.records)||[]}),g&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((P=t.customCardPreferences)==null?void 0:P.dataInputCardIds)||{}).map(w=>{var R,L,B;const M=(L=(R=t.customCardPreferences)==null?void 0:R.dataInputCardIds)==null?void 0:L[w].cardId,O=(B=x==null?void 0:x.cards)==null?void 0:B.find(Y=>Y.id===M);if(O)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:f,onDataChange:p,dataInputIndex:w,card:O},O.id+w)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(g,{theme:u,onDataChange:p,settings:y.map(w=>{var M;return(M=w==null?void 0:w.customCardPreferences)==null?void 0:M.settings}),data:y.map(w=>w!=null&&w.id?r==null?void 0:r[w.id]:[])})})]})]},(k=t.customCardPreferences)==null?void 0:k.componentName)})}function Tt({className:t,...n}){var C;const a=s.useEditorStore(S=>S.card),r=s.isExplorerCard(a),l=((C=a.customCardPreferences)==null?void 0:C.showCardHeader)??!0,o=s.useEditorStore(S=>S.frame),c=s.useDashboardStore(S=>S.dashboard.filters),i=s.useEditorStore(S=>S.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),u=c==null?void 0:c.find(S=>S.id===o.filterId),{data:m,isLoading:h,isFetching:x,errorMessage:j,pagination:b}=s.useDashboardCardQuery(a),{setCard:p,updateCardInFrame:g}=s.useEditorActions(),{data:f}=s.useTopoJson(a),y=A.useMemo(()=>{var S;return a.type!=="pivotTable"||!((S=m==null?void 0:m.records)!=null&&S.length)?null:{records:m.records,columnSubtotalMeta:m.columnSubtotalMeta,subtotalColumns:m.subtotalColumns||[],pivotSchema:m.pivotSchema||[],groupByColumns:m.groupByColumns}},[a.type,m==null?void 0:m.records,m==null?void 0:m.columnSubtotalMeta,m==null?void 0:m.subtotalColumns,m==null?void 0:m.pivotSchema,m==null?void 0:m.groupByColumns]),E=s.usePivotTableConfig(a,y),T=(S,F)=>{var P,k;const I={...a,paginationConfig:{page:S+1,pageSize:F}};p(I),g(I),a.sql&&((k=(P=a.preferences)==null?void 0:P.tablePrefs)!=null&&k.enableDevModePagination)&&i(!0)},N=A.useMemo(()=>!a.id||!(m!=null&&m.records)?null:s.createChartConfig({card:a,data:m==null?void 0:m.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:f}),[a.id,m==null?void 0:m.records,a.type,a.queryConfig,a.customCfg,a.preferences,f]);function D(S){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(lr,{card:S})})}function v(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!x)return j?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||x)&&a.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return D(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&N)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:h||x?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:N})});if(a.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:a,data:(m==null?void 0:m.records)||[],paginationMetadata:b,onPaginationChange:T,isLoading:h||x})});if(a.type==="pivotTable"&&E)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:a,data:E.data,options:E.options,onAggregationChange:S=>{const F=s.handleAggregationChange(S,a.config),I={...a,config:F};p(I),g(I)},onAggregationLabelChange:S=>{const F=s.handleAggregationLabelChange(S,a.config),I={...a,config:F};p(I),g(I)}})});if(a.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:a,data:(m==null?void 0:m.records)||[],groupByColumns:m==null?void 0:m.groupByColumns,pivotSchema:m==null?void 0:m.pivotSchema,paginationMetadata:b,onPaginationChange:T,onAggregationChange:S=>{const F=s.handleAggregationChange(S,a.config),I={...a,config:F};p(I),g(I)},isLoading:h||x})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-5",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:S=>p({...a,title:S}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(rr,{})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:S=>p({...a,description:S}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),u&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:u.title||u.column,onSave:S=>d({...u,title:S}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:u})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:v()})]})}const gs=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:n,onChange:a}),or=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),ir=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(gs,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(gs,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(gs,{language:"javascript",value:t,onChange:l})})]}),cr=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function dr(){const[t,n]=A.useState(!1),[a,r]=A.useState(""),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(""),m=s.useEditorStore(N=>N.card),h=s.useEditorStore(N=>N.card.customCfg),x=h?JSON.stringify(h,null,2):"",{data:j}=s.useDashboardCardQuery(m),{data:b}=s.useTopoJson(m),{setCardCustomCfg:p,setCustomVisualCode:g}=s.useEditorActions(),f=N=>{var D,v;return JSON.stringify({...N,data:{...N.data,datasets:(v=(D=N.data)==null?void 0:D.datasets)==null?void 0:v.map(C=>({...C,data:[]}))}},null,2)},y=()=>{var D,v;if(!((D=j==null?void 0:j.records)!=null&&D.length))return;const N=s.createChartConfig({card:m,data:j.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:b});if(N){r(f(N)),i(((v=m.preferences)==null?void 0:v.customVisualCode)||"");const C=s.merge(N,h);o(f(C))}},E=()=>{try{if(c&&g(c),l){const N=JSON.parse(l),D=s.getObjectDiff(JSON.parse(a),N);p(D),u("")}}catch{u("Invalid JSON configuration")}},T=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:y,className:T?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(or,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Tt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(ir,{customCode:c,cardCustomCfgString:x,mergedConfig:l,onConfigChange:N=>o(N??""),onCodeChange:N=>i(N??"")})]}),e.jsx(cr,{error:d,hasCardCustomConfig:!!h,onReset:()=>{o(a),p(null)},onApply:E,onClose:()=>n(!1)})]})]})}function ds(t){const[n,a]=A.useState(null);return n}function kt(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{data:a,isLoading:r,isFetching:l,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(n.apiServiceUrl,t==null?void 0:t.accessToken)});return{data:a,isLoading:r,isFetching:l,isError:o}}function Et(){const{data:t,isLoading:n,isError:a}=kt(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let o=n,c=a;return r.forEach((i,d)=>{var u;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const m=t.plugins[d],h=i.data.visuals.map(x=>({name:x.name,pluginName:m.label,componentType:x.componentType,pluginType:m.type,icon:x.icon,chartType:x.chartType,url:m.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function ur({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=Et(),d=A.useCallback((u,m)=>{n(null),a({}),r(u),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[n,a,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((u,m)=>e.jsx(mr,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const mr=({text:t,icon:n,onClick:a})=>{const r=ds(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:a,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function It({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(m,h){o(null),r({}),a(m),["custom","text","map"].includes(m)&&(l(!0),i(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(s.Table2,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnIncreasing,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(s.ChartLine,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnStacked,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(s.MdStackedLineChart,{className:s.cn("size-5",n),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(s.ChartScatter,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(s.TbChartBubble,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(s.ChartPie,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(s.Donut,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(s.TbChartFunnel,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(s.Radar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(s.PiChartPolar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(s.Tornado,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(s.ChartNoAxesGantt,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(s.TiSortNumerically,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(s.Map,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(He,{className:s.cn("size-5",n)})})]})}function hr({chartType:t,className:n,customIcon:a,componentName:r}){const l=ds();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:n});case"line":return e.jsx(s.ChartLine,{className:n});case"pie":return e.jsx(s.ChartPie,{className:n});case"radar":return e.jsx(s.Radar,{className:n});case"scatter":return e.jsx(s.ChartScatter,{className:n});case"bubble":return e.jsx(s.TbChartBubble,{className:n});case"doughnut":return e.jsx(s.Donut,{className:n});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:n});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:n});case"polarArea":return e.jsx(s.PiChartPolar,{className:n});case"funnel":return e.jsx(s.TbChartFunnel,{className:n});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:n});case"range":return e.jsx(s.ChartNoAxesGantt,{className:n});case"kpi":return e.jsx(s.TiSortNumerically,{className:n});case"text":return e.jsx(ve,{className:n});case"map":return e.jsx(s.Map,{className:n});case"custom":return a&&l?e.jsx(l,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(He,{className:n});default:return e.jsx(s.Table2,{className:n})}}function At({variant:t="ghost"}){var o,c;const[n,a]=A.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(hr,{className:"size-4",chartType:l,customIcon:(o=r.customCardPreferences)==null?void 0:o.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"z-[51] w-72 p-1",children:[e.jsx(It,{onChartTypeChange:()=>a(!1)}),e.jsx(ur,{onChartTypeChange:()=>a(!1)})]})]})}function xr({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,o]=A.useState(!1),c=A.useRef(null),i=A.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(x){(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d())}function m(){const x=window.getSelection();if(x&&x.toString().trim()!==""){const j=x.toString();navigator.clipboard.writeText(j),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function pr(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(zs,{className:"size-4"}):e.jsx(Bs,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(zs,{className:"size-4"}):e.jsx(Bs,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function fr({className:t}){var x,j,b,p,g,f,y,E;const n=s.useEditorStore(T=>T.card),{setCardPreferences:a,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[o,c]=A.useState(!1),i=((j=(x=n.preferences)==null?void 0:x.displayOptions)==null?void 0:j.showFilterInfo)??!0,d=((p=(b=n.preferences)==null?void 0:b.displayOptions)==null?void 0:p.showCardToolbar)??!0,u=((f=(g=n.preferences)==null?void 0:g.displayOptions)==null?void 0:f.showChrome)??!0,m=((E=(y=n.preferences)==null?void 0:y.displayOptions)==null?void 0:E.allowScroll)??!0,h=(T,N)=>{var C;const D={...n.preferences,displayOptions:{...(C=n.preferences)==null?void 0:C.displayOptions,[T]:N}};a(D);const v={...n,preferences:D};l(v),r(v)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:o,onOpenChange:c,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(st,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:T=>{h("showFilterInfo",T)},onSelect:T=>T.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:T=>{h("showCardToolbar",T)},onSelect:T=>T.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:T=>{h("showChrome",T)},onSelect:T=>T.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:T=>{h("allowScroll",T)},onSelect:T=>T.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]})]})]})})}function Mt(){const t=s.useEditorStore(o=>o.card);s.useEditorStore(o=>o.isShowingVisual);const n=s.useEditorStore(o=>{var c,i;return(i=(c=o.card)==null?void 0:c.preferences)==null?void 0:i.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function l(){const o=["xy","none","x","y"],i=(o.indexOf(a)+1)%o.length;r(o[i])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(pr,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(a==="xy"||!a)&&e.jsx(os,{className:"size-4"}),a==="x"&&e.jsx(fa,{className:"size-4"}),a==="y"&&e.jsx(Va,{className:"size-4"}),a==="none"&&e.jsx(Ya,{className:"size-4"})]}),e.jsx(fr,{})]})}function gr(){const t=s.useEditorStore(b=>b.frame),n=s.useEditorStore(b=>b.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(b,p)=>{b.dataTransfer.setData("tabIndex",p.toString())},i=b=>{b.preventDefault()},d=(b,p)=>{const g=b.dataTransfer.getData("tabIndex");if(g===p.toString())return;const f=Array.from(t.cards),[y]=f.splice(parseInt(g),1);f.splice(p,0,y),a({...t,cards:f})};function u(b){const p=t.cards.filter(y=>y.id!==b),g=p[0],f={...t,cards:p,activeCardId:g.id};a(f),r(g.id),l(g)}function m(b,p){const g={...t,cards:[...t.cards,p],activeCardId:b.id};a(g),r(p.id)}function h(){const b={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};m(n,b)}function x(b){const p={dataSource:b.dataSource,connectionId:b.connectionId,lastSelectedDatabase:b.lastSelectedDatabase,lastSelectedSchema:b.lastSelectedSchema,lastSelectedTable:b.lastSelectedTable,lastSelectedDatamodelId:b.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(b,p)}function j(b,p){return b.cards.length===1&&(p.displayTab===!0||p.displayTab===void 0)||b.activeCardId!==p.id&&(p.displayTab===!0||p.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const g=p.displayTab===void 0?!1:!p.displayTab;l({...p,displayTab:g}),o({...p,displayTab:g})},children:p.displayTab===!0||p.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(ba,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((b,p)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:g=>c(g,p),onDragOver:i,onDrop:g=>d(g,p),className:"",value:b.id,children:[j(t,b),e.jsx(s.Editable,{enabled:t.activeCardId===b.id,text:b.tabTitle||b.title,onSave:g=>{l({...n,tabTitle:g}),o({...n,tabTitle:g})},children:b.tabTitle||b.title},b.id),t.activeCardId===b.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(b.id)})]},b.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>x(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(s.CopyPlus,{className:"h-4 w-4"})})]})})}function Lt(){const t=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.isSqlRunning),r=s.useEditorStore(p=>p.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h}=s.useDashboardCardQuery(n);function x(p){const g=t.cards.find(f=>f.id===p);if(g!=null&&g.sql){r||i(!0),o(p);return}if(g!=null&&g.queryConfig){r&&i(!1),j(p),o(p);return}r||j(p),o(p)}function j(p){const g={...t,cards:t.cards.map(y=>y.id===n.id?n:y),activeCardId:p};l(g);const f=g.cards.find(y=>y.id===p);f.sql&&d(!0),c(f)}function b(){return n.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:u==null?void 0:u.records,isPending:m||h})})}):n.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Tt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:x,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(p=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:p.id,children:b()},p.id)),e.jsx(gr,{})]})}function Ze({children:t}){var T,N;s.useEditorStore(D=>D.frame);const n=s.useEditorStore(D=>D.card),a=s.useEditorStore(D=>D.isDevMode),r=s.useEditorStore(D=>D.isShowingVisual),l=s.useDashboardStore(D=>D.isVisualEditing),o=s.useEditorStore(D=>D.pythonStdOut);s.useEditorStore(D=>D.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:x,isLoading:j,isFetching:b,errorMessage:p,refetch:g}=s.useDashboardCardQuery(n);function f(){const D=JSON.stringify(x==null?void 0:x.records,null,2),v=new Blob([D],{type:"application/json"}),C=URL.createObjectURL(v),S=document.createElement("a");S.href=C,S.download=`${n.title}.json`,S.click()}function y(){const v=[Object.keys(x==null?void 0:x.records.reduce((I,P)=>({...I,...P}),{})).join(","),...((x==null?void 0:x.records)||[]).map(I=>Object.values(I).join(","))].join(`
|
|
333
|
-
`),C=new Blob([v],{type:"text/csv"}),S=URL.createObjectURL(C),F=document.createElement("a");F.href=S,F.download=`${n.title}.csv`,F.click()}function E(){const D=`Can you get the documentation for ${n.type} chart?`;u(D)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(At,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:E,children:e.jsx(da,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(dr,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:y,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:f,children:e.jsx(ya,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(x==null?void 0:x.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(Mt,{})]}),n.type==="table"&&n.sql&&!s.hasValidCardConfig(n.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((N=(T=n.preferences)==null?void 0:T.tablePrefs)==null?void 0:N.enableDevModePagination)??!1,onCheckedChange:D=>{var v;h({...n.preferences,tablePrefs:{...(v=n.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:D}}),g()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(br,{})]}),r?e.jsx(Lt,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:o&&e.jsx(jr,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":o}),children:[(x==null?void 0:x.records)&&(x==null?void 0:x.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(x==null?void 0:x.records)||[]}),p&&e.jsx(xr,{error:p})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function jr(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function br(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Ce({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function vr(){var p,g;const t=s.useEditorStore(f=>f.card.customCardPreferences),{data:n}=kt(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(f=>f.card),l=s.useEditorStore(f=>f.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(p=d==null?void 0:d.visuals)==null?void 0:p.find(f=>f.name===(t==null?void 0:t.componentName));function m(f,y){if(!t)return;const T={...(t==null?void 0:t.dataInputCardIds)||{},[f]:{cardId:y,hookRef:null}};c({...t,dataInputCardIds:T})}function h(f){var E,T;const y=(E=l==null?void 0:l.cards)==null?void 0:E.filter(N=>{var D;return((D=N==null?void 0:N.customCardPreferences)==null?void 0:D.visualType)!=="multiple"}).map(N=>({value:N.id,label:N.tabTitle||N.title}));return e.jsx("div",{className:"space-y-2",children:(T=f==null?void 0:f.dataInputs)==null?void 0:T.map((N,D)=>{var v,C;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:N}),e.jsx(Ce,{className:"col-span-6 h-8 w-full justify-between",label:"",options:y||[],value:((C=(v=t==null?void 0:t.dataInputCardIds)==null?void 0:v[D])==null?void 0:C.cardId)||"",onValueChange:S=>m(D,S)})]},D+Math.random())})})}function x(f,y,E=[],T=""){var N,D;return t?f==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((N=t==null?void 0:t.settings)==null?void 0:N[y])||T,onChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[y]:v.target.value}})}},y):f==="select"?e.jsx(Ce,{className:"h-8 w-full",label:"",options:E,value:((D=t==null?void 0:t.settings)==null?void 0:D[y])||T,onValueChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[y]:v}})}}):null:null}function j(f){const y=Object.entries((f==null?void 0:f.settings)||{});return e.jsx("div",{className:"space-y-3",children:y.map(([E,T])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:T.title}),x(T.ui,E,T.options,T.defaultValue)]},E))})}function b(f){t&&c({...t,visualType:f,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ce,{icon:e.jsx(ca,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:f=>c({...t||{url:"",componentName:""},url:f})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:b,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(Ce,{icon:e.jsx(ga,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(f=>f.type===o).map(f=>({value:f.name,label:f.name})))||[],value:t.componentName,onValueChange:f=>{console.log("changing value",f),c({...t,componentName:f})}})})]})})]}),((g=r==null?void 0:r.customCardPreferences)==null?void 0:g.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:j(u)})})]})]})]})}function Oe(){const[t,n]=A.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),o=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),A.useEffect(()=>{o&&n(new Array(o.length).fill(!1))},[o]);function c(u,m){var h,x;m?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):l({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...a,onClickFilter:(x=a==null?void 0:a.onClickFilter)==null?void 0:x.filter(j=>j.columnIndex!==u)}),n(j=>{const b=[...j];return b[u]=!1,b}))}function i(u,m){var x;const h=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.map(j=>j.columnIndex===u?{...j,expression:m.target.value}:j);l({...a,onClickFilter:h})}function d(u){var m,h,x,j;if(t!=null&&t[u]||(h=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(b=>b.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(j=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(b=>b.columnIndex===u))==null?void 0:j.expression,onChange:b=>i(u,b),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:o==null?void 0:o.map((u,m)=>{var h,x;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(j=>j.columnIndex===m)),onCheckedChange:j=>c(m,j)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(j=>j.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{n(j=>{const b=[...j];return b[m]=!j[m],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function yr({idx:t}){var i;const n=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),a=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=n==null?void 0:n.chartOptions)==null?void 0:i.indexAxis,o=a==null?void 0:a.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:m}]});else{const h={...o};h.datalabels=m;const x=a==null?void 0:a.map(j=>j.idx===u?h:j);r({...n,datasetOptions:x})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(tt,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ta,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ea,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ka,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function Nr(){const t=s.useEditorStore(o=>o.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function us({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Rt(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=Nr();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:o.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:Ot(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(Ft,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function Ot(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Ft({col:t,idx:n,className:a,iconClassName:r,children:l}){const o=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,x;return(x=(h=m.card)==null?void 0:h.preferences)==null?void 0:x.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===n),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...o,datasetOptions:[...c||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const x=c==null?void 0:c.map(j=>j.idx===n?h:j);d({...o,datasetOptions:x})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(us,{className:"max-w-[100px]",title:t,children:Ot(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(yr,{idx:n})]})]})}function ks(){const t=s.useEditorStore(j=>j.selectedConnectionId),n=s.useEditorStore(j=>j.selectedDatamodelId),a=s.useEditorStore(j=>j.selectedDatabaseName),r=s.useEditorStore(j=>j.selectedSchemaName),l=s.useEditorStore(j=>j.selectedTableName),o=s.useDashboardStore(j=>j.dashboard.filters)||[],c=s.useDashboardStore(j=>j.actions.addFilter),i=s.useDashboardStore(j=>j.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:h}=s.useEditorAside();function x(j,b="dashboard",p){var C;const g=s.fmt(j.column_name),f=s.fmt(a||""),y=s.fmt(r||""),E=s.fmt(m);let T=s.getQualifiedTableName({schemaName:y,tableName:E,connectionType:h,databaseName:f}),N=`${T}.${g}`;const D=(C=u==null?void 0:u.find(S=>S.id===n))==null?void 0:C.name;n&&n!=="none"&&(N=`${s.DATAMODEL_NAMESPCACE}.${D}.${g}`,T=`${s.DATAMODEL_NAMESPCACE}.${D}`),p!=null&&p.qualifiedFieldName&&(N=p.qualifiedFieldName),p!=null&&p.entityName&&(T=p.entityName);const v=o==null?void 0:o.find(S=>S.column===N&&S.table===E&&(S.database===f||S.database===a));if(v)d(v.id),i(v.id);else{const S=s.v4();return m==="api"&&t?(c({location:b,id:S,column:N,title:j.column_name,dataType:j.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(j.data_type,T,g)}),S):(c({id:S,location:b,column:N,title:j.column_name,dataType:j.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(j.data_type,T,g)}),S)}}return{assignFilter:x}}function Ue(){const t=s.useDashboardStore(i=>i.dashboard.filters),n=s.useEditorStore(i=>i.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=ks();function o(i){const d=l(i,"frame");a({...n,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(Cr,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function Cr({columns:t,onSelect:n}){var c;const[a,r]=Ee.useState(!1),[l,o]=Ee.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const u=d===l?"":d;o(u),r(!1),u&&n(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function Sr({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:n=>n.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Rt,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Oe,{}),e.jsx(Ue,{})]})]})]})})}function wr({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Oe,{}),e.jsx(Ue,{})]})]})]})})}function Pt(){const t=s.useEditorStore(i=>i.card.type),n=s.useEditorStore(i=>i.isDevMode),a=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(m=a==null?void 0:a.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function o(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?o():c()})}const Dr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Tr={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function kr(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Er(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Pt,{}),e.jsx(Oe,{}),e.jsx(Ue,{})]})]})}function Er(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(Dr,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(Tr,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function Ir({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(c,i,d){const u=[...t];u[c]={...u[c],[i]:d},n(u)}function l(c){const i=[...t];i.splice(c,1),n(i)}function o(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:o,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(i,"start",d.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:d=>r(i,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(i,"color",d.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function Ar(){var m,h,x,j,b;const t=s.useEditorStore(p=>p.card.preferences),n=s.useEditorStore(p=>p.actions.setCardPreferences),a=s.useEditorStore(p=>p.card),r=s.isExplorerCard(a),l=s.useEditorStore(p=>p.actions.setNumberFormat);s.useEditorStore(p=>{var g,f;return(f=(g=p.card.preferences)==null?void 0:g.formatNumber)==null?void 0:f.decimalPlaces});const o=s.useEditorStore(p=>{var g,f;return(f=(g=p.card.preferences)==null?void 0:g.formatNumber)==null?void 0:f.locale}),c=s.useEditorStore(p=>{var g,f;return(f=(g=p.card.preferences)==null?void 0:g.formatNumber)==null?void 0:f.currency});s.useEditorStore(p=>p.actions.setFilterOnClickField);const i=s.useEditorStore(p=>{var g,f;return(f=(g=p.card.preferences)==null?void 0:g.formatNumber)==null?void 0:f.colorRanges})||[],d=s.useEditorStore(p=>p.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(p=>p.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:p=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:p}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:p=>{var g,f,y;return l(((g=t==null?void 0:t.formatNumber)==null?void 0:g.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",p,((y=t==null?void 0:t.formatNumber)==null?void 0:y.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(p=>e.jsx(s.SelectItem,{value:p.locale,children:p.locale},p.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:p=>{var g,f,y;console.log("currency",p),l(((g=t==null?void 0:t.formatNumber)==null?void 0:g.decimalPlaces)||0,p==="none"?"":p,((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((j=(x=t==null?void 0:t.formatNumber)==null?void 0:x.decimalPlaces)==null?void 0:j.toString())||"0",onValueChange:p=>{var g,f,y;return l(Number(p),((g=t==null?void 0:t.formatNumber)==null?void 0:g.currency)||"",((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:p=>{var g,f,y;return l(((g=t==null?void 0:t.formatNumber)==null?void 0:g.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.locale)||"",p.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(Ir,{colorRanges:i,setColorRanges:d})]})]})}function Mr(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(Ar,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function js({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Lr=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],Rr=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],Or=Rr.map(t=>({label:t,value:t}));function Fr(){var d,u,m,h,x,j,b,p,g,f,y,E,T,N,D,v,C,S;const t=s.useEditorStore(F=>F.card),n=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=A.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(F=>({label:F,value:F}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(js,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(js,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Ce,{className:"h-9",options:i,onValueChange:F=>{console.log("value",F),l({...t.preferences,mapVisualOptions:{topoJsonUrl:F}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:F=>{r(F.target.value)},onBlur:()=>{var F;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(F=t.preferences)==null?void 0:F.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(Ce,{className:"h-9",options:c,value:((j=(x=t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:j.objectKey)||"",label:"Map Object",onValueChange:F=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,objectKey:F}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(Ce,{className:"h-9",options:Lr,value:((p=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:p.projection)||"",label:"Projection",onValueChange:F=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projection:F}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(Ce,{className:"h-9",options:Or,value:((f=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:f.colorScale)||"",label:"Select Color Scale",onValueChange:F=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,colorScale:F}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(js,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((E=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:E.projectionScale)||1,onChange:F=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projectionScale:Number(F.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((D=(N=(T=t.preferences)==null?void 0:T.mapVisualOptions)==null?void 0:N.projectionOffset)==null?void 0:D[0])||0,onChange:F=>{var I,P,k,w;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projectionOffset:[Number(F.target.value),((w=(k=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:w[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(C=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:C.projectionOffset)==null?void 0:S[1])||0,onChange:F=>{var I,P,k,w;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projectionOffset:[((w=(k=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:w[0])||0,Number(F.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Oe,{})]})}function Pr(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:n}=s.useEditorStore(l=>l.actions);function a(l){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function es({cardType:t,docContent:n,suffix:a="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${a}`}),e.jsx(s.AccordionContent,{children:n||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Pr,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Oe,{}),e.jsx(Ue,{})]})]})]})})}function Br(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(Ce,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{n(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[a(),e.jsx(Rt,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Oe,{}),e.jsx(Ue,{})]})]})]})})}function zr({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Oe,{}),e.jsx(Ue,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function Bt({color:t,onColorChange:n,onClose:a}){const[r,l]=A.useState(0),[o,c]=A.useState(100),[i,d]=A.useState(50),[u,m]=A.useState(t);A.useEffect(()=>{const g=Gs(t);if(g){const f=Ys(g.r,g.g,g.b);l(f.h),c(f.s),d(f.l),m(t)}},[t]);const h=g=>{l(g),j(g,o,i)},x=g=>{const f=g.currentTarget.getBoundingClientRect(),y=Math.max(0,Math.min(1,(g.clientX-f.left)/f.width)),E=Math.max(0,Math.min(1,(g.clientY-f.top)/f.height)),T=y*100,N=(1-E)*100;c(T),d(N),j(r,T,N)},j=(g,f,y)=>{const E=_r(g,f,y),T=Vr(E.r,E.g,E.b);m(T)},b=g=>{if(m(g),/^#[0-9A-Fa-f]{6}$/.test(g)){const f=Gs(g);if(f){const y=Ys(f.r,f.g,f.b);l(y.h),c(y.s),d(y.l)}}},p=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(n(u),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:x,onMouseMove:g=>{g.buttons===1&&x(g)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:g=>h(Number(g.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:u,onChange:g=>b(g.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:p,children:"OK"})]})]})}function Gs(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Vr(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function Ys(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let o=0,c=0;const i=(r+l)/2;if(r!==l){const d=r-l;switch(c=i>.5?d/(2-r-l):d/(r+l),r){case t:o=((n-a)/d+(n<a?6:0))/6;break;case n:o=((a-t)/d+2)/6;break;case a:o=((t-n)/d+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function _r(t,n,a){t/=360,n/=100,a/=100;let r,l,o;if(n===0)r=l=o=a;else{const c=(u,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(m-u)*6*h:h<.5?m:h<.6666666666666666?u+(m-u)*(.6666666666666666-h)*6:u),i=a<.5?a*(1+n):a+n-a*n,d=2*a-i;r=c(d,i,t+1/3),l=c(d,i,t),o=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const Ur=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function zt(){var E,T,N,D,v,C,S,F,I,P;const t=s.useEditorStore(k=>k.card),n=s.useEditorStore(k=>{var w;return(w=k.card)==null?void 0:w.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=A.useState({}),[i,d]=A.useState(null),[u,m]=A.useState(null),h=A.useMemo(()=>{var O,R,L,B,Y,J,V;if(!(l!=null&&l.records)||l.records.length===0)return[];const k=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",w=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",M=((O=t==null?void 0:t.config)==null?void 0:O.pivotByColumns)&&t.config.pivotByColumns.length>0;if((k||w)&&M){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const K=new Set;return l.pivotSchema.forEach(q=>{q.alias&&K.add(q.alias)}),Array.from(K)}if(l.records.length>0){const K=l.records[0],q=Object.keys(K),Z=new Set;(R=t==null?void 0:t.config)!=null&&R.groupByColumns&&t.config.groupByColumns.forEach(_=>{Z.add(_.label||_.name),Z.add(_.alias||_.name)});const $=new Set;return(L=t==null?void 0:t.config)!=null&&L.metricColumns&&t.config.metricColumns.forEach(_=>{const G=_.alias||_.name;$.add(G),$.add(`${G}_count`),$.add(`${G}_sum`),$.add(`${G}_avg`),$.add(`${G}_min`),$.add(`${G}_max`);const se=_.entityName||_.qualifiedEntityName;se&&($.add(`${se}_${G}`),$.add(`${se}_${G}_count`))}),q.filter(_=>!Z.has(_)&&!$.has(_))}}if((w||k)&&!M&&((Y=(B=t==null?void 0:t.config)==null?void 0:B.metricColumns)!=null&&Y.length))return t.config.metricColumns.map(K=>K.alias||K.label||K.name);if((V=(J=t==null?void 0:t.config)==null?void 0:J.groupByColumns)!=null&&V.length){const K=t.config.groupByColumns[0],q=K.label||K.name,Z=new Set;return l.records.forEach($=>{const X=$[q];X!=null&&Z.add(String(X))}),Array.from(Z)}return[]},[l,(E=t==null?void 0:t.config)==null?void 0:E.groupByColumns,(T=t==null?void 0:t.config)==null?void 0:T.pivotByColumns,(N=t==null?void 0:t.config)==null?void 0:N.metricColumns,t==null?void 0:t.type]),x=A.useMemo(()=>s.getDefaultChartColors(),[]);A.useEffect(()=>{const k={};h.forEach((w,M)=>{k[w]=s.getColorForValue(w,M,n==null?void 0:n.colorConfig)}),c(k)},[h,n==null?void 0:n.colorConfig,x]);const j=(k,w)=>{const M={...o,[k]:w};c(M);const O={...n||{},colorConfig:{segments:M}};a(O);const R={...t,preferences:O};r(R)},b=(k,w)=>{var Y;const M=x[w%x.length],{[k]:O,...R}=((Y=n==null?void 0:n.colorConfig)==null?void 0:Y.segments)||{},L={...n||{},colorConfig:{segments:R}};a(L);const B={...t,preferences:L};r(B),c(J=>({...J,[k]:M}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((v=(D=t==null?void 0:t.config)==null?void 0:D.groupByColumns)==null?void 0:v.length)||((S=(C=t==null?void 0:t.config)==null?void 0:C.pivotByColumns)==null?void 0:S.length):(I=(F=t==null?void 0:t.config)==null?void 0:F.groupByColumns)==null?void 0:I.length)||["table","kpi","text","custom"].includes(t.type))return null;const f=()=>{const k={...n||{},colorConfig:{segments:{}}};a(k);const w={...t,preferences:k};r(w);const M={};h.forEach((O,R)=>{M[O]=s.getColorForValue(O,R,void 0)}),c(M)},y=Object.keys(((P=n==null?void 0:n.colorConfig)==null?void 0:P.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:y&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:f,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((k,w)=>{const M=s.isDefaultColor(o[k],w),O=!M;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===k,onOpenChange:R=>d(R?k:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[k]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:x.slice(0,10).map((R,L)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[k]===R?"border-gray-900":"border-transparent"),style:{backgroundColor:R},onClick:()=>{j(k,R),d(null)},children:[L===w%x.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:R})]},`default-${L}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Ur.map((R,L)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[k]===R?"border-2 border-gray-900":R==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:R},onClick:()=>{j(k,R),d(null)},children:e.jsx("span",{className:"sr-only",children:R})},`preset-${L}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{m({value:k,color:o[k]}),d(null)},children:"Custom color"}),!M&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(k,w),d(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:k}),O&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},k)})}),u&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Bt,{color:u.color,onColorChange:k=>{j(u.value,k),m(null)},onClose:()=>m(null)})})]})]})})]})}function we({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[o,c]=A.useState(t??""),[i,d]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const u=()=>{n(o),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?u():h.key==="Escape"&&m()},"aria-label":a||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Gr=["auto","number","currency","percent","scientific","date"],Yr=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"GBP",label:"GBP - British Pound"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"DKK",label:"DKK - Danish Krone"},{value:"KRW",label:"KRW - South Korean Won"},{value:"INR",label:"INR - Indian Rupee"},{value:"RUB",label:"RUB - Russian Ruble"},{value:"BRL",label:"BRL - Brazilian Real"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"TRY",label:"TRY - Turkish Lira"},{value:"ZAR",label:"ZAR - South African Rand"},{value:"SAR",label:"SAR - Saudi Riyal"},{value:"AED",label:"AED - UAE Dirham"},{value:"ARS",label:"ARS - Argentine Peso"},{value:"CLP",label:"CLP - Chilean Peso"},{value:"COP",label:"COP - Colombian Peso"},{value:"THB",label:"THB - Thai Baht"},{value:"IDR",label:"IDR - Indonesian Rupiah"},{value:"MYR",label:"MYR - Malaysian Ringgit"},{value:"PHP",label:"PHP - Philippine Peso"},{value:"PLN",label:"PLN - Polish Zloty"},{value:"NGN",label:"NGN - Nigerian Naira"},{value:"KES",label:"KES - Kenyan Shilling"},{value:"GHS",label:"GHS - Ghanaian Cedi"},{value:"ZMW",label:"ZMW - Zambian Kwacha"},{value:"ZWL",label:"ZWL - Zimbabwean Dollar"},{value:"EGP",label:"EGP - Egyptian Pound"},{value:"MAD",label:"MAD - Moroccan Dirham"},{value:"UAH",label:"UAH - Ukrainian Hryvnia"},{value:"HUF",label:"HUF - Hungarian Forint"},{value:"CZK",label:"CZK - Czech Koruna"},{value:"RON",label:"RON - Romanian Leu"},{value:"PKR",label:"PKR - Pakistani Rupee"},{value:"BDT",label:"BDT - Bangladeshi Taka"},{value:"VND",label:"VND - Vietnamese Dong"},{value:"TWD",label:"TWD - New Taiwan Dollar"},{value:"ILS",label:"ILS - Israeli New Shekel"}],$r=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],qr=t=>t.charAt(0).toUpperCase()+t.slice(1);function Es({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,d)=>{n({...t,[i]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Gr.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":qr(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Yr.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:$r.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function $s({axis:t,label:n,type:a,config:r,onChange:l}){var h,x,j,b,p,g,f,y,E,T,N,D;const o=(v,C)=>{l({...r,[v]:C})},c=(v,C)=>{var S,F;l({...r,name:{enabled:v==="enabled"?C:((S=r==null?void 0:r.name)==null?void 0:S.enabled)??!1,text:v==="text"?C:(F=r==null?void 0:r.name)==null?void 0:F.text}})},i=(v,C)=>{var S,F;l({...r,labels:{enabled:v==="enabled"?C:((S=r==null?void 0:r.labels)==null?void 0:S.enabled)??!0,rotation:v==="rotation"?C:(F=r==null?void 0:r.labels)==null?void 0:F.rotation}})},d=(v,C)=>{l({...r,scale:{...r==null?void 0:r.scale,[v]:C===""?"auto":Number(C)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:v=>o("enabled",v),onClick:v=>v.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:v=>c("enabled",v)})]}),((x=r==null?void 0:r.name)==null?void 0:x.enabled)&&e.jsx(we,{placeholder:`${n} title`,value:((j=r==null?void 0:r.name)==null?void 0:j.text)||"",onSave:v=>c("text",v),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:v=>o("position",v),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":s.titleCase(v)},v))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((b=r==null?void 0:r.labels)==null?void 0:b.enabled)!==!1,onCheckedChange:v=>i("enabled",v)})]}),((p=r==null?void 0:r.labels)==null?void 0:p.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((g=r==null?void 0:r.labels)==null?void 0:g.rotation)||"auto"),onValueChange:v=>i("rotation",v==="auto"?"auto":Number(v)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":`${v}°`},v))})]})]})]}),a==="value"&&e.jsx(Es,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:v=>l({...r,formatOptions:v}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.min)==="auto"||((y=r==null?void 0:r.scale)==null?void 0:y.min)===void 0?"":String(r.scale.min),onSave:v=>d("min",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((E=r==null?void 0:r.scale)==null?void 0:E.max)==="auto"||((T=r==null?void 0:r.scale)==null?void 0:T.max)===void 0?"":String(r.scale.max),onSave:v=>d("max",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((N=r==null?void 0:r.scale)==null?void 0:N.stepSize)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.stepSize)===void 0?"":String(r.scale.stepSize),onSave:v=>d("stepSize",v),className:""})})]})]})]})]})]})}function Vt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const u={...n||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};a(u);const m={...t,preferences:u};r(m)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(st,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx($s,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx($s,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function _t(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var m,h,x,j;return(j=(x=(h=(m=u.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:x.plugins)==null?void 0:j.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(u,m)=>{const h={...n,[u]:m};a(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??o,onCheckedChange:u=>c("display",u)})]}),((n==null?void 0:n.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||r,onValueChange:u=>c("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||l,onValueChange:u=>c("align",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]})]})]})})]})}function Ut(){var C,S,F,I,P,k,w,M,O;const t=s.useEditorStore(R=>R.card),n=s.useEditorStore(R=>{var L,B;return(B=(L=R.card)==null?void 0:L.preferences)==null?void 0:B.dataLabelsConfig}),a=s.useEditorStore(R=>{var L;return(L=R.card)==null?void 0:L.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((C=a==null?void 0:a.chartOptions)==null?void 0:C.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!i,u=(F=(S=a==null?void 0:a.chartOptions)==null?void 0:S.plugins)==null?void 0:F.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),h=(n==null?void 0:n.enabled)!==void 0?n.enabled:m,x=(R,L)=>{const B={...n,[R]:L},Y={...t.preferences||{},dataLabelsConfig:B};r(Y);const J={...t,preferences:Y};l(J)},j=(R,L)=>{const B={...n,font:{...n==null?void 0:n.font,[R]:L}},Y={...t.preferences||{},dataLabelsConfig:B};r(Y);const J={...t,preferences:Y};l(J)},b=(R,L)=>{const B={...n,formatOptions:{...n==null?void 0:n.formatOptions,[R]:L}},Y={...t.preferences||{},dataLabelsConfig:B};r(Y);const J={...t,preferences:Y};l(J)},g=(()=>{const R=t.type;return R==="stackedBar"||R==="stackedLine"||R==="pie"||R==="doughnut"?"center":o?"right":"top"})();let f=[];c||i?f=["center"]:f=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(L=>L!==g),"custom"];const y=()=>s.titleCase(g),E=["center","start","end"],T=["center","start","end","top","bottom"],N=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],D=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],v=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:R=>x("enabled",R)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:R=>x("position",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:R==="auto"?y():R==="custom"?"Custom (Advanced)":s.titleCase(R)},R))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:R=>x("showTotal",R)})]}),(n==null?void 0:n.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(n==null?void 0:n.anchor)||"center",onValueChange:R=>x("anchor",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:E.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:s.titleCase(R)},R))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((n==null?void 0:n.align)||"center"),onValueChange:R=>x("align",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:T.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:s.titleCase(R)},R))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(d?"auto":"none"),onValueChange:R=>x("format",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:R==="auto"&&d?"Auto (Use Axis)":R==="none"?"None (Raw Value)":s.titleCase(R)},R))})]})]}),(n==null?void 0:n.format)&&!["auto","none"].includes(n.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(n.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"0",value:String(((I=n==null?void 0:n.formatOptions)==null?void 0:I.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:R=>b("decimalPlaces",Number(R)),className:""})})]}),n.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((P=n==null?void 0:n.formatOptions)==null?void 0:P.currency)||"USD",onValueChange:R=>b("currency",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:D.map(R=>e.jsx(s.SelectItem,{value:R.value,className:"text-xs",children:R.label},R.value))})]})]}),["number","currency"].includes(n.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((k=n==null?void 0:n.formatOptions)==null?void 0:k.useSuffix)??!1,onCheckedChange:R=>b("useSuffix",R)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((w=n==null?void 0:n.formatOptions)==null?void 0:w.locale)||"en-US",onValueChange:R=>b("locale",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(R=>e.jsx(s.SelectItem,{value:R.value,className:"text-xs",children:R.label},R.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"12",value:String(((M=n==null?void 0:n.font)==null?void 0:M.size)||12),onSave:R=>j("size",Number(R)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((O=n==null?void 0:n.font)==null?void 0:O.weight)||"normal",onValueChange:R=>j("weight",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(n==null?void 0:n.color)==="auto"||!(n!=null&&n.color)?"auto":"custom",onValueChange:R=>{R==="auto"&&x("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"0",value:String((n==null?void 0:n.rotation)||0),onSave:R=>x("rotation",Number(R)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Hr(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[e.jsx(zt,{}),e.jsx(Vt,{}),e.jsx(_t,{}),e.jsx(Ut,{})]})]})}const Wr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Kr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Qr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Jr(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=o=>r.includes(a)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(Hr,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(Br,{}));case"tornado":case"pyramid":return l(e.jsx(es,{docContent:Wr,cardType:a}));case"kpi":return e.jsx(Mr,{});case"line":case"bar":return l(e.jsx(Sr,{cardType:a}));case"range":return l(e.jsx(es,{docContent:Kr,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(es,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(wr,{cardType:a}));case"table":return e.jsx(zr,{cardType:a});case"text":return e.jsx(es,{docContent:Qr,cardType:a,suffix:"Visual"});case"map":return e.jsx(Fr,{});case"custom":return e.jsx(vr,{});default:return l(e.jsx(kr,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Gt({label:t,column:n,functions:a,onFunctionChange:r}){let l=a[0];"aggregate"in n?l=a.find(c=>c.value===n.aggregate)||a[0]:"granularity"in n&&(l=a.find(c=>c.value===n.granularity)||a[0]);function o(c){r(c)}return e.jsx(Ce,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:a,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const Xr=[{label:"Sum",value:"SUM",logo:e.jsx(et,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(De,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(Na,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(la,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function Zr({column:t}){const{updateMetricColumnOld:n}=s.useEditorActions();let a=Xr;s.isTextDataType(t.type)&&(a=a.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(a=a.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:We(t.name,l)};n(t.id,o)}return e.jsx(Gt,{column:t,functions:a,onFunctionChange:l=>r(l),label:"Aggregation"})}const el=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function sl({column:t}){const{updateGroupByColumnOld:n}=s.useEditorActions();function a(r){const l={...t,granularity:r,label:Ve(t.name,r)};n(t.id,l)}return e.jsx(Gt,{column:t,functions:el,onFunctionChange:r=>a(r),label:"Granularity"})}function tl({col:t,onChange:n,droppableId:a}){const{columns:r}=s.useDataColumns(),l=A.useMemo(()=>{let i=[];(a===Ie||a===Ae||a===Me)&&(i=r);const d=i==null?void 0:i.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,a,t.name]),o=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(u=>{var m;return u.column_name===((m=i[0])==null?void 0:m.id)});d&&n(d)}return l!=null&&l.length?e.jsx(s.ComboBox2,{multiple:!1,options:l,selectedOptions:o,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function Yt({column:t}){const n=s.useEditorStore(d=>d.card.type),a=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(a==null?void 0:a.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Ft,{idx:o,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Pt,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&i()]})}function al({column:t,type:n,onRemoveColumn:a,droppableId:r}){const[l,o]=A.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:m,setNodeRef:h,transform:x,transition:j,isDragging:b}=s.useSortable({id:t.id,data:{type:n}}),p=x?{opacity:b?.5:void 0,transform:s.CSS.Translate.toString(x),transition:j}:void 0,g=s.isTextDataType(t.type);function f(D){const v=s.isNumberDataType(D.data_type),C=s.isTextDataType(D.data_type),S=s.isDateDataType(D.data_type),F=v?"number":C?"string":S?"date":"string";if(r===Ie){if(C){const I={id:t.id,name:D.column_name,type:F,role:"groupby"};c(t.id,I)}if(S){const I={id:t.id,name:D.column_name,type:F,role:"groupby",label:Ve(D.column_name,"month"),granularity:"month"};c(t.id,I)}}if(r===Me){if(C){const I={id:t.id,name:D.column_name,type:F,role:"groupby"};d(t.id,I)}if(S){const I={id:t.id,name:D.column_name,type:F,label:Ve(D.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,I)}}if(r===Ae){const I={id:t.id,name:D.column_name,type:F,role:"metric",label:We(D.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};i(t.id,I)}}function y(){if(r===Ae)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(Yt,{column:t})})}function E(){const D=s.isDateDataType(t.type);if(r===Ae)return e.jsx(Zr,{column:t});if((r===Ie||r===Me)&&D)return e.jsx(sl,{column:t})}function T(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ie||r===Me)&&g}),children:e.jsx(tl,{col:t,onChange:f,droppableId:r})})}function N(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>o(!l),children:l?e.jsx(Ga,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Xs,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...u,ref:h,style:p,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[N(),E(),T()]}),l&&y()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>a(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function bs({id:t,label:n,columns:a,previewColumns:r,sortableType:l,onRemoveColumn:o}){var p,g;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),u=s.useDndStore(f=>f.activeId),m=s.useEditorStore(f=>{var y;return(y=f.card)==null?void 0:y.type}),h=i||((g=(p=d==null?void 0:d.data)==null?void 0:p.current)==null?void 0:g.type)===l,x=u?r:a,j=l===rs?"Rows":l===ls?"Pivot Columns":"Columns";function b(){if(!x||x.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(f=>f.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:n}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:j})]}),b(),e.jsx("div",{className:"space-y-2",children:x==null?void 0:x.map(f=>f.id===yt.id?e.jsx(nl,{},f.id):e.jsx(al,{droppableId:t,type:l,column:f,onRemoveColumn:o},f.id))})]})})}function nl(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function $t({children:t,id:n,type:a}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:d}=s.useSortable({id:n,data:{type:a}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...l,...r,ref:o,style:u,children:t})}function rl(){const t=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.orderBy})||[],n=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.groupByColumns})||[],a=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...n,...a];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(ia,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(ra,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(oa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(na,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(f=>!t.some(y=>y.columnId===f.id)).map(f=>({id:f.id,value:f.label||f.name}));function x(f,y){const E=j(f);return E?E.role==="metric"?y==="asc"?u:m:y==="asc"?i:d:null}function j(f){return c.find(y=>y.id===f)}function b(f){const y=t.find(E=>E.columnId===f);if(y){const E={...y,direction:y.direction==="asc"?"desc":"asc"};o(E)}}const p=f=>{r({columnId:f.id,direction:"asc"})};function g(f){const y=t.find(E=>E.columnId===f);y&&l(y)}return e.jsx(s.SortableContext,{items:t.map(f=>Ye(f.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:f=>p(f[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(f=>{var y,E;return e.jsx($t,{id:Ye(f.columnId),type:Ts,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Xs,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(us,{className:"w-[175px] text-sm",children:((y=j(f.columnId))==null?void 0:y.label)||((E=j(f.columnId))==null?void 0:E.name)})]}),e.jsx("button",{title:f.direction==="asc"?"Ascending":"Descending",onClick:()=>b(f.columnId),className:"rounded-sm p-0",children:x(f.columnId,f.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>g(f.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},f.columnId)},Ye(f.columnId))})]})})}function ll(){const t=s.useEditorStore(g=>{var f;return((f=g.card.queryConfig)==null?void 0:f.groupByColumns)||[]}),n=s.useEditorStore(g=>g.card.type),a=s.useDndStore(g=>g.previewGroupByColumns),r=s.useEditorStore(g=>{var f;return((f=g.card.queryConfig)==null?void 0:f.metricColumns)||[]}),l=s.useDndStore(g=>g.previewMetricColumns),o=s.useEditorStore(g=>{var f;return((f=g.card.queryConfig)==null?void 0:f.pivotColumns)||[]}),c=s.useDndStore(g=>g.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function m(g){i(g)}function h(g){d(g)}function x(g){u(g)}let j="Group By",b="Metrics",p="Stack By";return n==="table"&&(j="Rows",b="Metrics",p="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(It,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(bs,{onRemoveColumn:m,sortableType:rs,id:Ie,label:j,columns:t,previewColumns:a}),e.jsx(bs,{onRemoveColumn:x,sortableType:ls,id:Me,label:p,columns:o,previewColumns:c}),e.jsx(bs,{onRemoveColumn:h,sortableType:Ns,id:Ae,label:b,columns:r,previewColumns:l}),e.jsx(rl,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Is({children:t,column:n,id:a,sortableType:r,className:l}){const[o,c]=A.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(h=>{var x,j;return(j=(x=h.card.queryConfig)==null?void 0:x.filters)==null?void 0:j.some(b=>b.filterColumnName===n.name)});function m(h){i(h)}return e.jsx($t,{id:a,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":o}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:n.name}),u&&e.jsx("button",{onClick:()=>d(n),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>m(n),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!o&&"rounded-b-md",o&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",l),children:t})]})]})})}function ol({column:t,sortableType:n}){const a=s.useDashboardStore(E=>E.themeStyle),r=s.useEditorStore(E=>{var T,N;return(N=(T=E.card)==null?void 0:T.queryConfig)==null?void 0:N.filters}),l=s.useEditorStore(E=>{var T,N;return(N=(T=E.card.queryConfig)==null?void 0:T.filterColumns)==null?void 0:N.find(D=>D.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=A.useMemo(()=>{var E;return(E=r==null?void 0:r.find(T=>T.filterColumnName===t.name))==null?void 0:E.filterValue},[r,t.name]),u=A.useMemo(()=>Array.isArray(d)?d.map(E=>({id:E,value:E})):[],[d]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:x,isLoading:j,isFetching:b,isError:p}=s.useFilterQuery(h),g=A.useMemo(()=>{var T;return h.column?(T=x==null?void 0:x.records)==null?void 0:T.map(N=>{let D=h.column.split(".").slice(-1)[0].replace(/"/g,"");return N[D]===void 0&&(D=D.toLowerCase()),{id:N[D],value:N[D]}}):[]},[x,h.column]);function f(E){const T=E.map(N=>N.id);m(t.name,T)}function y(){return j||b?e.jsx(s.Skeleton,{style:{borderRadius:a==null?void 0:a.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):p?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(il,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:g,onChange:f,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Is,{className:"w-60",id:t.id,sortableType:n,column:t,children:y()})}function il({columnName:t}){const{setEditorFilterMode:n}=s.useEditorActions(),a=s.useEditorStore(l=>{var o,c;return(c=(o=l.card.queryConfig)==null?void 0:o.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(a==null?void 0:a.mode)==="exclude"?n(t,"include"):n(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((a==null?void 0:a.mode)==="exclude"?"exclude":"include")})}function cl({open:t,setOpen:n,dateRange:a,setDateRange:r,containerClassName:l,inputClassName:o,title:c,onApply:i,onClear:d}){const u=s.useDashboardStore(m=>m.themeStyle);return e.jsx("div",{className:s.cn("grid gap-2",l),children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{style:{borderRadius:u==null?void 0:u.controlInputRadius},asChild:!0,children:e.jsxs(s.Button,{size:"sm",id:"date",variant:"outline",className:s.cn("h-9 w-full justify-start rounded-sm text-left font-normal",!a&&"text-muted-foreground",o),children:[e.jsx(s.Calendar,{className:"mr-2 h-4 w-4"}),a!=null&&a.from?a.to?e.jsxs(e.Fragment,{children:[s.format(a.from,"LLL dd, y")," -"," ",s.format(a.to,"LLL dd, y")]}):s.format(a.from,"LLL dd, y"):e.jsx("span",{children:"Pick a date"})]})}),e.jsxs(s.PopoverContent,{style:{borderRadius:u==null?void 0:u.controlInputRadius},className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsx(s.Label,{children:c})}),e.jsx(s.Calendar$1,{initialFocus:!0,mode:"range",defaultMonth:a==null?void 0:a.from,selected:a,onSelect:r,numberOfMonths:2}),e.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3",children:[e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:m=>{m.stopPropagation(),i(a),n(!1)},children:"Apply"}),e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:d,children:"Clear"})]})]})]})})}function dl({column:t,sortableType:n}){const[a,r]=A.useState(!1),{selectedConnectionId:l,selectedDatabaseName:o,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:l,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:m,data:h}=s.useFilterQuery(i),x=h==null?void 0:h.records,{dateRange:j,setDateRange:b,initialDateRange:p}=s.useDateRangeFromRecords(x),{updateEditorFilterValue:g}=s.useEditorActions();function f(T){var D,v;const N={gte:(D=T==null?void 0:T.from)==null?void 0:D.toISOString(),lte:(v=T==null?void 0:T.to)==null?void 0:v.toISOString()};g(t.name,N)}function y(){g(t.name,null,!0),b(p)}function E(){return d||u?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):m?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):x?e.jsx(cl,{title:i.title,open:a,inputClassName:"h-8",setOpen:r,dateRange:j,setDateRange:b,onApply:f,onClear:y}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Is,{className:"w-72",id:t.id,sortableType:n,column:t,children:E()})}function ul({id:t,label:n,columns:a,previewColumns:r,sortableType:l}){var b,p;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(g=>g.activeId),u={},m=c||((p=(b=i==null?void 0:i.data)==null?void 0:b.current)==null?void 0:p.type)===l;function h(){if(!j||j.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function x(g){const f=s.isDateDataType(g.type);return g.id===yt.id?e.jsx(Is,{id:g.id,sortableType:l,column:g,children:e.jsx(ml,{})},g.id):f?e.jsx(dl,{droppableId:t,sortableType:l,column:g},g.id):e.jsx(ol,{droppableId:t,sortableType:l,column:g},g.id)}const j=d?r:a;return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(g=>g.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",m&&"border border-muted-foreground/20"),ref:o,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:n}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:j==null?void 0:j.map(g=>x(g))})]})})}function ml(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function hl(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),n=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:a}=s.useEditorActions();function r(l){a(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(ul,{onRemoveColumn:r,sortableType:Ss,id:Cs,label:"Filters",columns:t,previewColumns:n})})}function xl(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.showAIDialog),{setShowAIDialog:a}=s.useEditorActions(),{data:r,errorMessage:l,errorSql:o}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(cs,{}),!n&&e.jsxs(s.Button,{onClick:()=>a(!0),variant:"secondary",size:"sm",children:[e.jsx(Ma,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(wt,{sql:r==null?void 0:r.sql,error:l,errorSql:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(jt,{}),e.jsx(gt,{variant:"default"})]})]})}function pl(){const t=A.useRef(null),n=A.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);A.useEffect(()=>{var i,d,u,m;r?((i=t.current)==null||i.resize(0),(d=n.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(m=n.current)==null||m.resize(25))},[r]);function o(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(ar,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Jr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Ze,{})})]}):e.jsx(Ze,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:a?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:n,defaultSize:25,maxSize:30,children:e.jsx(ll,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(xl,{}),e.jsx(hl,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Ze,{})})]})})]}):e.jsx(Ze,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function fl(t){s.useAIInteractionStore(z=>z.currentAIContext);const[n,a]=A.useState(""),[r,l]=A.useState(null),{authToken:o,tokenProps:c}=s.useSemaphorContext(),i=s.useEditorStore(z=>{var ee;return(ee=z==null?void 0:z.card)==null?void 0:ee.sql}),d=s.useEditorStore(z=>z.isDevMode),u=s.useEditorStore(z=>{var ee;return(ee=z==null?void 0:z.card)==null?void 0:ee.python}),{setCardPython:m,setCardSql:h,setRunSql:x,switchCardType:j,setQueryConfig:b}=s.useEditorActions(),p=s.useEditorStore(z=>z.currentAssitantScope)||[],g=s.useEditorStore(z=>z.userInputForAI),f=s.useEditorStore(z=>z.triggerAIRun),y=s.useEditorStore(z=>z.card),E=s.useEditorStore(z=>z.selectedDatabaseName),T=s.useEditorStore(z=>z.selectedTableName),N=s.useEditorStore(z=>z.selectedConnectionId),D=s.useEditorStore(z=>z.selectedSchemaName),v=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:C,refetch:S,data:F}=s.useDashboardCardQuery(y),{setTriggerAIRun:I,setCurrentAssitantScope:P,setCardConfig:k}=s.useEditorActions(),{selectedDatamodelName:w,connectionType:M,selectedDatamodelId:O}=s.useEditorAside(),{messages:R,setMessages:L,regenerate:B,error:Y,sendMessage:J,status:V,addToolResult:K,stop:q,clearError:Z}=s.useChat({transport:new s.DefaultChatTransport({api:`${c.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const z=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:z.currentAIContext,reasoningEffort:z.reasoningEffort,showReasoning:z.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:z,body:ee})=>({body:{...ee,messages:s.cleanupIncompleteMessages(z)}})}),onError:z=>{console.log("on error",z)},onToolCall:$,onFinish(){a("")}});A.useEffect(()=>{f&&g&&(J({role:"user",parts:[{type:"text",text:g}]}),I(!1))},[f,g,J,I]);async function $({toolCall:z}){var ee,ne,le,de,xe,pe,Q,U,H,te,oe,ae,je,me,Qe,Je;if(["createChartFromSql","createForecast"].includes(z.toolName)){const Ge=((ee=z.input)==null?void 0:ee.sql)??((ne=z.args)==null?void 0:ne.sql),Te=((le=z.input)==null?void 0:le.python)??((de=z.args)==null?void 0:de.python),ue=((xe=z.input)==null?void 0:xe.chartType)??((pe=z.args)==null?void 0:pe.chartType);j(ue),h(Ge),m(Te),x(!0),K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(z.toolName==="getUserSql"){if(!i){K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",message:"No SQL found"}});return}K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",sql:i,python:u||""}})}else if(z.toolName==="generateQueryConfig"){a("Generating query config...");const Ge=((Q=z.input)==null?void 0:Q.chartType)??((U=z.args)==null?void 0:U.chartType),Te=((H=z.input)==null?void 0:H.queryConfig)??((te=z.args)==null?void 0:te.queryConfig);((oe=z.input)==null?void 0:oe.cardConfig)??((ae=z.args)==null||ae.cardConfig),j(Ge),k(Te),h(void 0),m(void 0);const ue=await S();if((je=ue==null?void 0:ue.data)!=null&&je.error){K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",queryConfig:Te,message:(me=ue==null?void 0:ue.data)==null?void 0:me.error.message}});return}if((Qe=ue==null?void 0:ue.data)!=null&&Qe.records){K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:Te,message:"The data has been visualized"}});return}K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:Te,message:"The data has been visualized",records:(Je=ue==null?void 0:ue.data)==null?void 0:Je.records}})}else a("Analyzing...")}function X(z){const ee=s.removeFromScopeArray(p,z);_(ee)}function _(z){const ee=s.sanitizeAIScope(z);P(ee),L(ne=>[...ne,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(ee)}`}]}])}function G(){const z={databaseName:E||"",schemaName:D||"",tableName:T||"",datamodelId:O||"",datamodelName:s.resolveDatamodelName(w),connectionId:N||"",connectionType:M||""},ee=s.dedup([...p,z]);_(ee)}function se(){const z={databaseName:E||"",schemaName:D||"",tableName:T||"",datamodelName:s.resolveDatamodelName(w),connectionId:N||"",connectionType:M||"",datamodelId:O||""};if(!s.isInAiScopeArray([...v||[],...p],z)||p.length===0){const ne=s.dedup([...v||[],...p,z]).filter(le=>le.connectionId===z.connectionId);_(ne)}}const re=!["ready","error"].includes(V),he=s.getErrorMessage(Y);return{messages:R,setMessages:L,sendMessage:J,regenerate:B,isLoading:re,handleSetAIScope:se,handleAddCurrentTableToScope:G,removeFromCurrentSelections:X,currentAssitantScope:p,setCurrentAssitantScope:P,stop:q,status:V,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:he,clearError:Z}}const gl=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function qs(){const t=A.useRef(null),[n,a]=A.useState(!1),[r,l]=A.useState(s.isDevEnv),[o,c]=A.useState(!1),[i,d]=A.useState(!1),u=s.useCurrentAIContext(),{setCurrentAIContext:m}=s.useAIActions(),{clearQueue:h}=s.useQueueActions(),{clearFileAttachments:x}=s.useFileActions(),j=s.useFileAttachments("editor"),b=s.useDashboardStore(H=>H.dashboard.aiContext),p=s.useEditorStore(H=>H.card.dataSource),g=s.useEditorStore(H=>H.actions.setCardSql),f=s.useEditorStore(H=>H.actions.setRunSql),y=s.useEditorStore(H=>H.showAIDialog),E=s.useDashboardStore(H=>H.handleOpenAssistantProfile),{setShowAIDialog:T,setCardPython:N}=s.useEditorActions(),{setDataSource:D}=s.useEditorActions(),{assistantProfile:v}=s.useAssistantProfile(),{messages:C,setMessages:S,sendMessage:F,isLoading:I,stop:P,status:k,llmUsage:w,errorMessage:M,clearError:O}=fl(),[R,L]=A.useState(""),B=H=>{L(H.target.value)},Y=H=>{H.preventDefault();const te=R.trim();if(!te&&j.length===0)return;const oe=[];te&&oe.push({type:"text",text:te}),j.forEach(ae=>{ae.data&&oe.push({type:"file",mediaType:ae.type,filename:ae.name,url:`data:${ae.type};base64,${ae.data}`})}),F({role:"user",parts:oe}),L(""),x("editor"),se({force:!0})},{visibleMessages:J,hasMoreMessages:V,totalMessageCount:K,loadMoreMessages:q,resetMessageWindow:Z}=s.useMessageWindow(C,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:$,isAtBottom:X,hasNewMessages:_,newMessageCount:G,scrollToBottom:se,handleScroll:re,resetNewMessageCount:he}=s.useAutoScroll(J,{threshold:50,delay:0,dependencies:[k,C.length]});A.useEffect(()=>{var H;y&&((H=t.current)==null||H.focus(),m({selectedEntities:(p==null?void 0:p.selectedEntities)||[]}))},[y,p,m]),s.useAutoSubmitQueue({assistantType:"editor",status:k,isLoading:I,sendMessage:F});const{hasActiveTools:z}=s.useActiveToolStatus(C);function ee(H,te){te==="sql"?(g(H),f(!0)):te==="python"&&(N(H),f(!0))}function ne(){var H;(H=b==null?void 0:b.selectedEntities)==null||H[0],d(!0)}function le(){u.selectedEntities.length===0&&m({selectedEntities:(b==null?void 0:b.selectedEntities)||[]})}function de(H){le();const te={role:"user",parts:[{type:"text",text:H.title+" "+H.subtitle}]};F(te)}function xe(H){le(),F({role:"user",parts:[{type:"text",text:H}]})}function pe(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:a,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:r,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:c,children:"System Message"})]})]})}function Q(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const U=(R==null?void 0:R.length)===0&&(C==null?void 0:C.filter(H=>H.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Q(),E&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:E,children:(v==null?void 0:v.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[pe(),s.isDevEnv,e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:ne,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:"New Chat",onClick:()=>{S([]),h("editor"),O(),Z()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",onClick:()=>{T(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:$,className:"mt-2 flex w-full grow basis-0",onScroll:re,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[V&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:q,className:"text-xs",children:["Load ",Math.min(5,K-J.length)," ","more messages (",K-J.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:J,showTools:r,handleRun:ee,showSystemMessage:o}),!z&&e.jsx(s.AssistantStatus,{status:k,errorMessage:M})]})}),!X&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{se({force:!0}),he()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),_&&G>0&&e.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:G>9?"9+":G})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[U&&!v&&e.jsx(s.Placeholders,{onClick:de,placeholders:gl}),e.jsx("div",{children:U&&v&&e.jsx(s.SeedQuestions,{seedQuestions:v.seedQuestions||[],handleSeedQuestionClick:xe})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:t,setInput:L,stop:P,input:R,handleInputChange:B,handleSubmit:H=>{le(),Y(H),se({force:!0})},isLoading:I,status:k,assistantType:"editor",onFocus:()=>{}})]}),w&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",w.inputTokens," prompt tokens, ",w.outputTokens," ","completion tokens, ",w.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(p==null?void 0:p.selectedEntities)||[],open:i,onOpenChange:d,dataSource:p||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}const As=t=>{var I;const{updateCardConfig:n,updateGroupByColumn:a,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(P=>P.card.type),h=t==null?void 0:t.id,x=A.useCallback(P=>{if(!(t!=null&&t.config))return[];switch(P){case"groupBy":return(t.config.groupByColumns||[]).map(k=>({id:k.id,name:k.name,dataType:k.dataType,label:k.label!==void 0?k.label:k.name,qualifiedEntityName:k.qualifiedEntityName,entityId:k.entityId,entityName:k.entityName,entityType:k.entityType,dateFormat:k.dateFormat,customFormat:k.customFormat,granularity:k.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(k=>({id:k.id,name:k.name,dataType:k.dataType,label:k.label!==void 0?k.label:k.name,qualifiedEntityName:k.qualifiedEntityName,entityId:k.entityId,entityName:k.entityName,entityType:k.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(k=>({id:k.id,name:k.name,dataType:k.dataType,label:k.label!==void 0?k.label:k.name,qualifiedEntityName:k.qualifiedEntityName,entityId:k.entityId,entityName:k.entityName,entityType:k.entityType,direction:k.direction}));case"source":return[];default:return[]}},[t]),j=A.useCallback((P,k)=>{if(h)switch(P){case"groupBy":{n(h,{groupByColumns:k});break}case"metrics":{n(h,{metricColumns:k});break}case"pivotBy":{n(h,{pivotByColumns:k});break}case"sortBy":{n(h,{sortByColumns:k});break}}},[h,n]),b=A.useCallback((P,k,w)=>{if(!h)return;const O=x(P)[k];if(O)switch(P){case"groupBy":a(h,O.id,{label:w});break;case"metrics":r(h,O.id,{label:w});break;case"pivotBy":l(h,O.id,{label:w});break;case"sortBy":o(h,O.id,{label:w});break}},[h,x,a,r,l,o]),p=A.useCallback((P,k)=>{if(!h)return;const M=x("metrics")[P];M&&r(h,M.id,{aggregate:k,label:s.getAggregationLabel(M.name,k)})},[h,x,r]),g=A.useCallback((P,k,w)=>{if(!h)return;const O=x("groupBy")[P];if(!O)return;const R={dateFormat:k};k==="custom"&&w?R.customFormat=w:R.customFormat=void 0,a(h,O.id,R)},[h,x,a]),f=A.useCallback((P,k)=>{if(!h)return;const M=x("groupBy")[P];M&&a(h,M.id,{granularity:k})},[h,x,a]),y=A.useCallback((P,k)=>{if(!h)return;const M=x("metrics")[P];M&&r(h,M.id,{aliasTemplate:k})},[h,x,r]),E=A.useCallback((P,k)=>{if(console.log("handleValueAliasesChange",P,k),!h)return;console.log("handleValueAliasesChange",P,k);const M=x("metrics")[P];M&&(console.log("handleValueAliasesChange",k),r(h,M.id,{valueAliases:k}))},[h,x,r]),T=A.useCallback(P=>{h&&n(h,{comparisonType:P})},[h,n]),N=A.useCallback(P=>{h&&n(h,{showTrendline:P})},[h,n]),D=A.useCallback(P=>{h&&n(h,{trendlineWindow:P})},[h,n]),v=A.useCallback(P=>{h&&n(h,{trendlineGranularity:P})},[h,n]),C=A.useCallback(P=>{h&&n(h,{targetValue:P})},[h,n]),S=A.useCallback(P=>{var B;if(!h)return;const k=[...x("groupBy"),...x("pivotBy"),...x("metrics"),...x("sortBy")],w=(B=t==null?void 0:t.config)==null?void 0:B.joinPlan,M=s.validateEntityConsistency(P,k,w);if(!M.isValid){M.showError&&s.showJoinRequiredNotification();return}const O=s.getSmartContainerForField(P,k),R=x(O);if(s.fieldAlreadyExists(P,R))return;const L=s.getNewField(P,O,R);L&&j(O,[...R,L])},[h,(I=t==null?void 0:t.config)==null?void 0:I.joinPlan,x,j]),F=A.useCallback((P,k)=>{if(!h)return;const M=x(P)[k];if(M){if(P!=="sortBy"){const O=x("sortBy"),R=O.filter(L=>!(L.name===M.name&&L.qualifiedEntityName===M.qualifiedEntityName));R.length!==O.length&&n(h,{sortByColumns:R})}switch(P){case"groupBy":c(h,M.id);break;case"metrics":i(h,M.id);break;case"pivotBy":d(h,M.id);break;case"sortBy":u(h,M.id);break}}},[h,x,c,i,d,u,n]);return{getFieldsForContainer:x,setFieldsForContainer:j,updateLabel:b,handleAggregationChange:p,handleDateFormatChange:g,handleGranularityChange:f,handleAliasTemplateChange:y,handleValueAliasesChange:E,removeField:F,handleFieldClick:S,handleKpiComparisonTypeChange:T,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:C,cardType:m}};function jl({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function bl({field:t}){const{attributes:n,listeners:a,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,d]=A.useState(!1),u=s.useEditorStore(b=>b.card),{handleFieldClick:m}=As(u),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const x=b=>{const p=(b||"").toLowerCase();switch(s.getDataType(p)){case"number":return De;case"date":return s.Calendar;case"boolean":return Le;case"json":return Be;case"geo":return $e;default:return ve}},j=b=>{const p=(b||"").toLowerCase(),g=s.getDataType(p);return g==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):g==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):g==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):g==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):g==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):g==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx($e,{className:"h-3 w-3"})}):g==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ke,{className:"h-3 w-3"})}):null};return x(t.dataType),e.jsxs("div",{ref:r,style:h,...n,...a,className:`group/container max-w-[265px] overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>m(t),children:[j(t.dataType),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-xs text-foreground/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(jl,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.name})]}),e.jsx(s.Badge,{variant:"outline",className:"mt-2 text-xs",children:t.dataType})]})})})]})}function vl(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useEditorStore(E=>E.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),u=o.filter(E=>E.name.toLowerCase().includes(t.toLowerCase())||E.dataType.toLowerCase().includes(t.toLowerCase())||E.qualifiedEntityName&&E.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=E=>{if(E.dataType==="number"||E.dataType==="integer"||E.dataType==="float"||E.dataType==="decimal"||E.dataType==="currency")return"metrics";const T=s.getDataType(E.dataType);return["date","string","boolean"].includes(T)?"dimensions":T==="number"?"metrics":"dimensions"},x=(a==="all"?u:u.filter(E=>m(E)===a)).reduce((E,T)=>{const N=T.qualifiedEntityName||"Other Fields";return E[N]||(E[N]={label:s.toLabel(T.entityName),fields:[]}),E[N].fields.push(T),E},{}),b=Object.keys(x),p=u.filter(E=>m(E)==="dimensions").length,g=u.filter(E=>m(E)==="metrics").length,f=u.filter(E=>m(E)==="calculated").length,y=u.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[o.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:t,onChange:E=>n(E.target.value)}),t&&e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:e.jsx(s.X,{className:"size-3.5"})})]}),y&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:E=>r(E),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:u.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Ke,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:b,className:"space-y-2",children:Object.entries(x).map(([E,T])=>{const N=c.find(D=>D.entityName===E)||{entityName:E,label:T.label};return e.jsxs(s.AccordionItem,{value:E,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{title:N.label||N.entityName,className:"flex items-center gap-2",children:[e.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:N.label||N.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:T.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:T.fields.map(D=>e.jsx(bl,{field:D},D.id))})})]},E)})}),Object.keys(x).length===0&&o.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(x).length===0&&o.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function yl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(vl,{})," "]})}function Nl({initialJoinPlan:t,availableDataSources:n}){const[a,r]=A.useState(t),[l,o]=A.useState(new Set),c=()=>{const D=a.joins.length>0?Math.max(...a.joins.map(C=>C.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:D,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,v]}),o(new Set([...l,v.id]))},i=D=>{r({...a,joins:a.joins.filter(v=>v.id!==D)}),o(new Set([...l].filter(v=>v!==D)))},d=(D,v)=>{var I,P;const C=a.joins.find(k=>k.id===D);if(!C)return;const S={...C,...v},F=a.joins.map(k=>k.id===D?S:k);if((I=S.source)!=null&&I.name&&((P=S.target)!=null&&P.name)&&S.joinKeyGroups[0].keys.length===0){const k=n.find(R=>{var L;return R.name===((L=S.source)==null?void 0:L.name)}),w=n.find(R=>{var L;return R.name===((L=S.target)==null?void 0:L.name)}),M={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(k==null?void 0:k.name)||"",entityName:(k==null?void 0:k.name)||"",entityType:(k==null?void 0:k.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},operator:"="},O=[...S.joinKeyGroups];O[0]={...O[0],keys:[M]},S.joinKeyGroups=O,F[F.findIndex(R=>R.id===D)]=S}r({...a,joins:F})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:D=>{const v=a.joins.findIndex(C=>C.id===D);if(v>0){const C=[...a.joins],S={...C[v]},F={...C[v-1]};C[v]=F,C[v-1]=S,C.forEach((P,k)=>{P.sequence=k+1});const I={...a,joins:C};r(I)}},moveJoinDown:D=>{const v=a.joins.findIndex(C=>C.id===D);if(v<a.joins.length-1){const C=[...a.joins],S={...C[v]},F={...C[v+1]};C[v]=F,C[v+1]=S,C.forEach((P,k)=>{P.sequence=k+1});const I={...a,joins:C};r(I)}},toggleJoinExpansion:D=>{const v=new Set(l);v.has(D)?v.delete(D):v.add(D),o(v)},getAvailableSourceEntities:D=>{if(a.joins.length===0)return n;const v=a.joins.findIndex(S=>S.id===D);if(v===0)return n;const C=new Set;return a.baseEntity.name&&C.add(a.baseEntity.name),a.joins.slice(0,v).forEach(S=>{C.add(S.source.name),C.add(S.target.name)}),n.filter(S=>C.has(S.name))},getAvailableTargetEntities:D=>n.filter(v=>v.name!==D),addJoinKeyGroup:D=>{const v=a.joins.find(S=>S.id===D);if(!v)return;const C=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(D,{joinKeyGroups:C})},updateGroupOperator:(D,v,C)=>{const S=a.joins.find(I=>I.id===D);if(!S)return;const F=[...S.joinKeyGroups];F[v]={...F[v],operator:C},d(D,{joinKeyGroups:F})},removeJoinKeyGroup:(D,v)=>{const C=a.joins.find(F=>F.id===D);if(!C)return;const S=[...C.joinKeyGroups];S.splice(v,1),d(D,{joinKeyGroups:S})},addJoinKey:(D,v)=>{const C=a.joins.find(k=>k.id===D);if(!C)return;const S=n.find(k=>k.name===C.source.name),F=n.find(k=>k.name===C.target.name),I=[...C.joinKeyGroups],P={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(S==null?void 0:S.name)||"",entityName:(S==null?void 0:S.name)||"",entityType:(S==null?void 0:S.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(F==null?void 0:F.name)||"",entityName:(F==null?void 0:F.name)||"",entityType:(F==null?void 0:F.type)||"table"},operator:"="};I[v]={...I[v],keys:[...I[v].keys,P]},d(D,{joinKeyGroups:I})},updateJoinKey:(D,v,C,S,F)=>{const I=a.joins.find(O=>O.id===D);if(!I)return;const P=n.find(O=>O.name===I.source.name),k=n.find(O=>O.name===I.target.name),w=[...I.joinKeyGroups],M=w[v].keys[C];S==="sourceColumnName"&&P?w[v].keys[C]={...M,source:{...M.source,name:F}}:S==="targetColumnName"&&k?w[v].keys[C]={...M,target:{...M.target,name:F}}:S==="operator"&&(w[v].keys[C]={...M,operator:F}),d(D,{joinKeyGroups:w})},removeJoinKey:(D,v,C)=>{const S=a.joins.find(I=>I.id===D);if(!S)return;const F=[...S.joinKeyGroups];F[v].keys.splice(C,1),d(D,{joinKeyGroups:F})},generateSQLPreview:()=>{const D=[...a.joins].sort((S,F)=>S.sequence-F.sequence),v=a.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let C=`SELECT *
|
|
334
|
-
FROM ${v.name}`;return D.forEach(
|
|
335
|
-
${
|
|
336
|
-
ON ${P}`}),C},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(S=>!S.source.name||!S.target.name)||a.joins.some(S=>S.joinKeyGroups.some(F=>F.keys.length===0))||a.joins.some(S=>S.joinKeyGroups.some(F=>F.keys.some(I=>!I.source.name||!I.target.name||!I.operator))))}}function Cl({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(I=>I.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:x,moveJoinUp:j,moveJoinDown:b,toggleJoinExpansion:p,getAvailableSourceEntities:g,getAvailableTargetEntities:f,addJoinKeyGroup:y,updateGroupOperator:E,removeJoinKeyGroup:T,addJoinKey:N,updateJoinKey:D,removeJoinKey:v,generateSQLPreview:C,isValidConfiguration:S}=Nl({initialJoinPlan:t,availableDataSources:n}),F=I=>{const P=c.find(k=>k.entityName===I);return(P==null?void 0:P.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:I=>{const P=n.find(k=>k.name===I);u({...i,baseEntity:{connectionId:(P==null?void 0:P.connectionId)||"",connectionType:(P==null?void 0:P.connectionType)||"none",type:(P==null?void 0:P.type)||"table",name:I,database:P==null?void 0:P.database,schema:P==null?void 0:P.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(I=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:I.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:I.type}),I.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},I.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:C()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(I=>{const P=n.find(M=>M.name===I.source.name),k=n.find(M=>M.name===I.target.name),w=d.has(I.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:I.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",I.sequence,P&&k&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",P.name," → ",k.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(I.id),disabled:I.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(I.id),disabled:I.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(I.id),children:w?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(I.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),w&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:I.source.name,onValueChange:M=>{const O=n.find(R=>R.name===M);x(I.id,{source:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:M,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:g(I.id).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name]})},M.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:I.joinType,onValueChange:M=>x(I.id,{joinType:M}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:I.target.name,onValueChange:M=>{const O=n.find(R=>R.name===M);x(I.id,{target:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:M,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},disabled:!I.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:I.source.name?f(I.source.name).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name,M.name===I.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},M.name)):[]})]})]})]}),I.source.name&&I.target.name&&P&&k&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>y(I.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),I.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:I.joinKeyGroups.map((M,O)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",O+1]}),O>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:M.operator,onValueChange:R=>E(I.id,O,R),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>T(I.id,O),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[M.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:M.keys.map((R,L)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[L>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:M.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:R.source.name,onValueChange:B=>D(I.id,O,L,"sourceColumnName",B),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:F(I.source.name).map(B=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:B.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:B.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:B.dataType})]})},B.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:R.operator,onValueChange:B=>D(I.id,O,L,"operator",B),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:R.target.name,onValueChange:B=>D(I.id,O,L,"targetColumnName",B),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:F(I.target.name).map(B=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:B.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:B.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:B.dataType})]})},B.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>v(I.id,O,L),children:e.jsx(s.X,{className:"size-3.5"})})]},R.id||L))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>N(I.id,O),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},M.id))})]})]})]},I.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(i),disabled:!S(),children:"Save"})]})]})}function Hs({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Cl,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function Sl({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=a.find(c=>c.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=a.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=a.find(d=>d.name===l.source.name),i=a.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function wl(){var m,h;const t=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>x.actions.updateCardConfig),a=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=A.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=x=>{n(t.id,{...t==null?void 0:t.config,joinPlan:x}),l(!1)},i=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},u=()=>{const x=[...a.joins].sort((p,g)=>p.sequence-g.sequence),j=a.baseEntity;if(!j.name)return"SELECT * FROM table -- Please select a base entity";let b=`SELECT *
|
|
337
|
-
FROM ${
|
|
338
|
-
${p.joinType} JOIN ${
|
|
339
|
-
ON ${y}`}),b};return o.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[a.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>l(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":a.joins.length>0,"text-gray-500":a.joins.length===0})}),"Join",a.joins.length>1?"s":""," (",a.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(Sl,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:o,generateSQLPreview:u})})]})}),e.jsx(Hs,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(Hs,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function Dl({open:t,onOpenChange:n}){const[a,r]=A.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(p=>p.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];A.useEffect(()=>{t&&r([])},[t]);const i=p=>{r(g=>g.some(y=>y.name===p.name&&y.type===p.type)?g.filter(y=>!(y.name===p.name&&y.type===p.type)):[...g,p])},d=()=>{r([...c])},u=()=>{r([])},m=()=>{if(a.length===0)return;const p=a[0],g=p.connectionId||"",f=p.connectionType||"",E=a.some(N=>N.type==="dataset")?"semanticDomain":"database";l({connectionId:g,connectionType:f,mode:E,selectedEntities:a}),n(!1)},h=p=>{switch(p.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Wa,{className:"h-4 w-4"});case"model":return e.jsx(ja,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},x=p=>"label"in p&&p.label?p.label:p.name,j=p=>{if("description"in p&&p.description)return p.description;const g=[];return p.database&&g.push(p.database),p.schema&&g.push(p.schema),p.name&&g.push(p.name),g.join(".")},b=p=>a.some(g=>g.name===p.name&&g.type===p.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:a.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((p,g)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",b(p)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:b(p),onCheckedChange:()=>i(p)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(p)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:x(p)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:j(p)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p.type})]},`${p.type}-${p.name}-${g}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function Tl({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function kl({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((n,a)=>{const r=s.getEntityDetails(n),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function El({isVisible:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(!1),[o,c]=A.useState(!0),i=s.useEditorStore(h=>h.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:d}=s.useEditorActions(),u={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},m={...u,...i,selectedEntities:(i==null?void 0:i.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:"p-4 px-6 pb-2",children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>a(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Add Data"]})}),e.jsxs("div",{className:"relative px-6",children:[e.jsx("div",{className:"absolute inset-0 flex items-center px-6",children:e.jsx("div",{className:"w-full border-t border-border"})}),e.jsx("div",{className:"relative flex justify-center",children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>c(!o),className:"size-6 bg-background p-1 py-1 hover:bg-accent",children:o?e.jsx(s.ChevronUp,{className:"h-3.5 w-3.5"}):e.jsx(s.ChevronDown,{className:"h-3.5 w-3.5"})})})]}),e.jsxs("div",{className:`overflow-hidden px-6 ${o?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[m.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[m.selectedEntities.slice(0,3).map((h,x)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{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:[s.getDisplayName(h),e.jsx("button",{onClick:j=>{j.stopPropagation();const b=m.selectedEntities.filter(p=>!(p.name===h.name&&p.type===h.type));d({...u,...i,selectedEntities:b})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(Tl,{entity:h})]},`${h.type}-${h.name}-${x}`)),m.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",m.selectedEntities.length-3," more"]})}),e.jsx(kl,{entities:m.selectedEntities.slice(3)})]})]})}),e.jsx(wl,{})]})]}),e.jsx(yl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(i==null?void 0:i.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:a,dataSource:m,fallbackDataSource:u}),e.jsx(Dl,{open:r,onOpenChange:l})]})}const Il="chart-selector-standard-first";function Al(){const[t,n]=s.useLocalStorageState(Il,!0);return{standardFirst:t,updatePreference:n}}const Ws=({pluginVisual:t,index:n,onSelect:a})=>{const r=ds(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},Ks=["default","standardPlugin","customPlugin"];function Ml({selectedChart:t,onChartChange:n}){var T;const[a,r]=A.useState(!1),{data:l}=Et();Al();const c=((T=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:T.url)||"";Ds(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:x}=s.useEditorActions(),[j,b]=s.useLocalStorageState("chart-section-active",null),p=A.useMemo(()=>j?[j,...Ks.filter(N=>N!==j)]:Ks,[j]);function g(N){m(null),d({}),i(N),["custom","map"].includes(N)&&(u(!0),x(void 0)),n(N),r(!1)}function f(N){m(null),d({}),i("custom"),h({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),x(void 0),n("custom"),r(!1)}const y=()=>{var D;if(t==="custom"){const v=s.useEditorStore.getState().card;return((D=v==null?void 0:v.customCardPreferences)==null?void 0:D.componentName)||"Custom Visual"}const N=s.chartTypes.find(v=>v.id===t);return(N==null?void 0:N.label)||"Select chart type"},E=()=>{var D,v;if(t==="custom"){const C=s.useEditorStore.getState().card,S=(D=C==null?void 0:C.customCardPreferences)==null?void 0:D.icon,F=(v=C==null?void 0:C.customCardPreferences)==null?void 0:v.componentName;if(S&&F)return e.jsx(Ll,{icon:S,componentName:F});if(F){const I=s.getAutoDetectedChartIcon(F);if(I)return I}return e.jsx(He,{className:"h-4 w-4"})}const N=s.chartTypes.find(C=>C.id===t);if(N){const C=N.icon;return e.jsx(C,{className:"h-4 w-4"})}return e.jsx(He,{className:"h-4 w-4"})};return e.jsx("div",{className:"",children:e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[E(),e.jsx("span",{children:y()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),p.map(N=>{if(N==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:j==="default",onCheckedChange:D=>b(D?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:s.chartTypes.map(D=>{const v=D.icon;return e.jsx(s.CommandItem,{value:`${D.label} ${D.id} chart graph visualization`,onSelect:()=>g(D.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{className:"h-4 w-4"}),e.jsx("span",{children:D.label})]})},D.id)})},"default");if(N==="standardPlugin"){const D=l.filter(v=>v.pluginType==="standard");return D.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:j==="standardPlugin",onCheckedChange:v=>b(v?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.filter(v=>v.componentType==="chart").map((v,C)=>e.jsx(Ws,{pluginVisual:v,index:C,onSelect:()=>f(v)},`${v.url}-${v.name}-${C}`))},"standardPlugin"):null}if(N==="customPlugin"){const D=l.filter(v=>v.pluginType==="custom");return D.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:j==="customPlugin",onCheckedChange:v=>b(v?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.map((v,C)=>e.jsx(Ws,{pluginVisual:v,index:C,onSelect:()=>f(v)},`${v.url}-${v.name}-${C}`))},"customPlugin"):null}return null})]})]})})]})})}const Ll=({icon:t,componentName:n})=>{const a=ds(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(He,{className:"h-4 w-4"})},Rl=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!0},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"}];function Ol({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(o=>o.card),r=((l=a==null?void 0:a.config)==null?void 0:l.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center justify-center gap-1",children:Rl.map(o=>{if(o.requiresPivot&&!r)return null;const c=o.icon,i=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(o.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o.label})})]},o.id)})})}const Ms=({dataType:t})=>{const n=s.getDataType(t);return n==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})};function Fl({aliasTemplate:t,onAliasTemplateChange:n}){var d;const[a,r]=A.useState(t),[l,o]=A.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?a:t,onChange:u=>{r(u.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&a!==t?(n(a),o(!1)):u.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Pl({valueAliases:t,onValueAliasesChange:n}){const[a,r]=A.useState(null),[l,o]=A.useState(""),[c,i]=A.useState(""),d=()=>{n({...t,"":""})},u=h=>{const x={...t};delete x[h],n(x)},m=h=>{const x={...t};delete x[h],x[l]=c,n(x),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,x],j)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:b=>i(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(x)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(x)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+j)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Bl({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),o=s.useEditorStore(u=>u.card),c=o==null?void 0:o.dataSource,i=["attribute-values",t.entityName,t.name,n,a],d=s.useQuery({queryKey:i,queryFn:async()=>{if(!(c!=null&&c.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},m={connection_id:c.connectionId,cardConfig:u,cardDataSource:c,cache_config:s.getCacheConfig({card:o})};console.log("requestBody",m);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const x=t.name;return((h==null?void 0:h.records)||[]).map(b=>{const p=b[x]||b[t.alias||x]||b[t.label];return{id:p||"",value:p||"",label:String(p||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(c!=null&&c.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:d.data||[],isLoading:d.isLoading,isFetching:d.isFetching,isError:d.isError,error:d.error,refetch:d.refetch}}function zl({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:o}){var E,T;const c=!!l,[i,d]=A.useState(c?"values":"fields"),[u,m]=A.useState(""),[h,x]=A.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),j=a.filter(N=>{var v;return c?!1:!((v=r==null?void 0:r.conditions)==null?void 0:v.some(C=>C.field.id===N.id))&&N.label.toLowerCase().includes(u.toLowerCase())}),b=N=>{x({...h,field:N}),d("values")},p=()=>{if(h.field&&h.selectedValues.length>0){const N={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let D;if(c){const v=((r==null?void 0:r.conditions)||[]).map(C=>C.id===l.id?N:C);D={...r,conditions:v}}else{const v=(r==null?void 0:r.conditions)||[];D={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...v,N],groups:[]}}o(D),n(!1)}},g=()=>{if(!c||!l)return;const N=((r==null?void 0:r.conditions)||[]).filter(D=>D.id!==l.id);if(N.length>0){const D={...r,conditions:N};o(D)}else o(void 0);n(!1)},f=N=>{x({...h,selectedValues:N})},y=()=>{c&&l?(x({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(x({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return A.useEffect(()=>{t&&y()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(E=h.field)==null?void 0:E.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(T=h.field)==null?void 0:T.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(N=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[N.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(N.value)?`${N.value.length} values`:String(N.value)})]},N.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:u,onChange:N=>m(N.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:j.map(N=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(N),children:[e.jsx(Ms,{dataType:s.getDataType(N.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:N.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[N.entityName,".",N.name]})]})]},N.id))}),j.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),j.length===0&&!u&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Vl,{field:h.field,selectedValues:h.selectedValues,onValuesChange:f,onBack:c?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:g,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:y,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:p,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Vl({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,o]=A.useState(""),{values:c,isLoading:i,isFetching:d}=Bl({field:t,searchQuery:l,limit:500}),u=l?c.filter(x=>String(x.value).toLowerCase().includes(l.toLowerCase())):c,m=x=>{const j=n.includes(x);a(j?n.filter(b=>b!==x):[...n,x])},h=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(x=>x.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:x=>o(x.target.value),className:"pl-10"})]}),i||d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(x=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(x.value),children:[e.jsx(s.Checkbox,{checked:n.includes(x.value),onCheckedChange:()=>m(x.value)}),e.jsx(us,{className:"text-sm",children:x.label})]},x.id))})]})]})}function _l({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Rs,Os,Fs;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:x}=s.useSortable({id:t.id}),j=s.useEditorStore(W=>W.card),{updateLabel:b,handleAggregationChange:p,handleDateFormatChange:g,handleGranularityChange:f,handleAliasTemplateChange:y,handleValueAliasesChange:E,removeField:T,handleKpiComparisonTypeChange:N,handleKpiShowTrendlineChange:D,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:C,handleKpiTargetValueChange:S}=As(j),[F,I]=A.useState(!1),[P,k]=A.useState(!1),[w,M]=A.useState(null),[O,R]=A.useState(t.dateFormat||"YYYY-MM-DD"),[L,B]=A.useState(t.customFormat||""),[Y,J]=A.useState(!!t.customFormat),[V,K]=A.useState(t.granularity||"day"),[q,Z]=A.useState(t.aliasTemplate||""),[$,X]=A.useState(t.valueAliases||{}),[_,G]=A.useState((Rs=t.parameters)==null?void 0:Rs.filters),se=W=>{W==="custom"?J(!0):(J(!1),R(W),n==="groupBy"&&g(a,W,""))},re=W=>{B(W),n==="groupBy"&&g(a,"custom",W)},he=W=>{var fe;K(W);const ce=(fe=H(W)[0])==null?void 0:fe.value;ce&&!Y&&(R(ce),n==="groupBy"&&g(a,ce,"")),n==="groupBy"&&f(a,W)},z=W=>{Z(W),n==="metrics"&&y(a,W)},ee=W=>{X(W),n==="metrics"&&E(a,W)},ne=W=>{b(n,a,W)},le=W=>{var ie;if(G(W),n==="metrics"){const ce={...t,parameters:{...t.parameters,filters:W}},fe=[...((ie=j.config)==null?void 0:ie.metricColumns)||[]];fe[a]=ce,s.useEditorStore.getState().actions.updateCardConfig(j.id,{metricColumns:fe})}k(!1)},de=()=>{T(n,a)},xe={transform:s.CSS.Transform.toString(m),transition:h},pe=s.getDataType(t.dataType),Q=pe==="date",U=c==="kpi",H=W=>{switch(W){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},te=H(V),oe=n!=="pivotBy",ae=Q&&n==="groupBy",je=!U&&Q&&n==="groupBy",me=U&&Q&&n==="groupBy",Qe=U&&n==="metrics"&&((Os=j.config)==null?void 0:Os.comparisonType)==="target",Je=n==="metrics",Ge=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:W=>{W.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),Te=()=>oe?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(we,{value:t.label??"",onSave:ne,placeholder:"Display label...",type:"text"})]}):null,ue=()=>ae?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:V,onValueChange:he,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(W=>e.jsx(s.SelectItem,{className:"text-xs",value:W,children:s.toTitleCase(W)},W))})]})]}):null,Qt=()=>je?e.jsxs(e.Fragment,{children:[ue(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:Y?"custom":O,onValueChange:se,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:te.map(W=>e.jsx(s.SelectItem,{className:"text-xs",value:W.value,children:W.label},W.value))})]}),Y&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:L,onChange:W=>{W.stopPropagation(),re(W.target.value)},onClick:W=>W.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,Jt=()=>{var W,ie,ce,fe,ke;return me?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((W=j.config)==null?void 0:W.comparisonType)||"none",onValueChange:N,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ie=j.config)==null?void 0:ie.showTrendline)||!1,onCheckedChange:D})]})}),((ce=j.config)==null?void 0:ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((fe=j.config)==null?void 0:fe.trendlineWindow)||30,onChange:Xe=>{const ta=parseInt(Xe.target.value)||30;v(ta)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((ke=j.config)==null?void 0:ke.trendlineGranularity)||"day",onValueChange:C,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},Xt=()=>{var W,ie;return Qe?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(we,{value:((W=j.config)==null?void 0:W.targetValue)!==void 0&&((ie=j.config)==null?void 0:ie.targetValue)!==null?String(j.config.targetValue):"",onSave:ce=>{!isNaN(Number(ce))&&ce!==null?S(Number(ce)):S(0)},placeholder:"Enter target value...",type:"text"})]}):null},Zt=()=>Je?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:W=>{p(a,W)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(_==null?void 0:_.conditions)&&_.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:_.conditions.map(W=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{M(W),k(!0)},children:[e.jsxs("span",{className:"font-medium",children:[W.field.label,":"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(W.value)?W.value.length===1?String(W.value[0]):W.value.length<=2?W.value.join(", "):`${W.value.slice(0,2).join(", ")} +${W.value.length-2}`:String(W.value)})}),Array.isArray(W.value)&&W.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",W.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:W.value.map((ie,ce)=>e.jsx("div",{children:String(ie)},ce))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ie=>{var fe;ie.stopPropagation();const ce=_.conditions.filter(ke=>ke.id!==W.id);if(ce.length>0){const ke={..._,conditions:ce};le(ke)}else if(G(void 0),n==="metrics"){const ke={...t,parameters:{...t.parameters,filters:void 0}},Xe=[...((fe=j.config)==null?void 0:fe.metricColumns)||[]];Xe[a]=ke,s.useEditorStore.getState().actions.updateCardConfig(j.id,{metricColumns:Xe})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},W.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{M(null),k(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Yt,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(Fl,{aliasTemplate:q,onAliasTemplateChange:z}),e.jsx(Pl,{valueAliases:$,onValueAliasesChange:ee})]})]}):null,{columns:ea=[]}=s.useColumns(),sa=(_==null?void 0:_.conditions)&&_.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:xe,...i,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${x?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Ms,{dataType:pe}),e.jsx(us,{className:s.cn("w-[140px] flex-1 text-xs",sa&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Fs=_==null?void 0:_.conditions)==null?void 0:Fs.length)&&!F&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:_.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:_.conditions.map(W=>e.jsxs("div",{children:[W.field.label,":"," ",Array.isArray(W.value)?`${W.value.length} values`:String(W.value)]},W.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:W=>{W.stopPropagation(),I(!F)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${F?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:W=>{W.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ie=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ie),l(ie)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:W=>{W.stopPropagation(),de()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),F&&e.jsxs("div",{className:"space-y-3",children:[Ge(),Te(),c==="kpi"&&ue(),Qt(),Jt(),Xt(),Zt()]})]}),P&&e.jsx(zl,{open:P,onOpenChange:W=>{k(W),W||M(null)},availableFields:ea,existingFilters:_,editingCondition:w,onSave:W=>{var ie;if(W)le(W);else if(G(void 0),n==="metrics"){const ce={...t,parameters:{...t.parameters,filters:void 0}},fe=[...((ie=j.config)==null?void 0:ie.metricColumns)||[]];fe[a]=ce,s.useEditorStore.getState().actions.updateCardConfig(j.id,{metricColumns:fe})}M(null)}})]})}function Ul({concept:t}){const n=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}function ss({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(b=>b.card),m=s.useEditorStore(b=>b.card.type),h=n.length>0,x=(b,p)=>{var f;!((f=u.config)!=null&&f.sortByColumns)||u.config.sortByColumns.findIndex(y=>y.id===b)===-1||d(u.id,b,{direction:p})};if(t==="sortBy"&&l===!1)return null;const j=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),j&&e.jsx(Ul,{concept:t})]}),e.jsx("div",{ref:i,className:`rounded-lg border-2 border-dashed p-1 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"min-h-[60px] border-muted-foreground/20 bg-background"}`,children:n.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:n.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((b,p)=>{const f=b.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(_l,{field:b,zone:t,index:p,sortDirection:f,onSortDirectionChange:y=>x(b.id,y),hasPivotColumns:o,cardType:m})})},b.id)})})})})]})}const Qs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Gl=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function vs({value:t,onChange:n,label:a}){const[r,l]=A.useState(!1),[o,c]=A.useState(!1),i=()=>{const d=Qs.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Qs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:Gl.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{n(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Bt,{color:i(),onColorChange:d=>{n(d),c(!1)},onClose:()=>c(!1)})})]})]})}const ts={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
|
|
340
|
-
Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function Yl(){var i,d,u,m,h,x,j,b,p,g;const t=s.useEditorStore(f=>f.card),{setCardPreferences:n}=s.useEditorActions(),a=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(a.length>=2&&r.length===0||a.length>=1&&r.length>0)))return null;const o=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=f=>{var E;const y={...t.preferences,kpiVisualOptions:{...(E=t.preferences)==null?void 0:E.kpiVisualOptions,metricComparison:{...o,...f}}};n(y)};return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ca,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:f=>c({enabled:f,...f&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:f=>c({calculationType:f}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(ts).map(([f,y])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:y.label},f))})]}),(()=>{var y,E,T;const f=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(y=ts[f])==null?void 0:y.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(E=ts[f])==null?void 0:E.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(T=ts[f])==null?void 0:T.example]})]})})()]}),e.jsx(Es,{formatOptions:o.formatOptions||{},onFormatOptionsChange:f=>c({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"left",onValueChange:f=>c({position:f}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:f=>c({showArrow:f})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:f=>c({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(vs,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:f=>c({colorConfig:{...o.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(vs,{value:((x=o.colorConfig)==null?void 0:x.decrease)||"red",onChange:f=>c({colorConfig:{...o.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(vs,{value:((j=o.colorConfig)==null?void 0:j.noChange)||"neutral",onChange:f=>c({colorConfig:{...o.colorConfig,noChange:f}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:f=>c({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((b=o.conditionalLabels)==null?void 0:b.increase)??"Increase",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,increase:f.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((p=o.conditionalLabels)==null?void 0:p.decrease)??"Decrease",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,decrease:f.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((g=o.conditionalLabels)==null?void 0:g.noChange)??"No change",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,noChange:f.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:f=>c({labelName:f.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function $l(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var d;const i={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};n(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(Es,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function ql({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const l=s.useEditorStore(b=>{var p;return((p=b.card.customCardPreferences)==null?void 0:p.url)&&b.card.type==="custom"}),o=s.useEditorStore(b=>b.card),c=o==null?void 0:o.type,i=t.length>0||a.length>0,d=c!=="kpi",u=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel","aggregateTable"].includes(c),h=d&&!m,x=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},j=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(ss,{zone:"groupBy",fields:t,label:x().label,placeholder:x().placeholder}),h&&e.jsx(ss,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(ss,{zone:"metrics",fields:a,label:j().label,placeholder:j().placeholder,hasPivotColumns:n.length>0}),u&&e.jsx(ss,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx($l,{}),e.jsx(Yl,{}),e.jsx(zt,{}),e.jsx(Vt,{}),e.jsx(_t,{}),e.jsx(Ut,{})]})})]})]})}function Hl({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}){const[c,i]=A.useState(!1);s.useEditorStore(p=>p.showAIDialog);const d=s.useEditorStore(p=>p.card),{isLoading:u,isFetching:m,refetch:h}=s.useDashboardCardQuery(d),x=a.length>0||r.length>0||l.length>0,{setShowAIDialog:j}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(d);return A.useEffect(()=>{m||i(!1)},[m]),e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx(Ol,{selectedChart:t,onChartChange:n}),e.jsx(Ml,{selectedChart:t,onChartChange:n})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsxs("div",{className:s.cn("invisible flex gap-2",{visible:x||b}),children:[e.jsx(cs,{}),e.jsx(s.Button,{disabled:u||m,onClick:()=>{i(!0),h()},className:"h-8 shrink-0",size:"sm",variant:"secondary",children:c?e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}):e.jsx(s.RefreshCcw,{className:"h-4 w-4"})})]})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(ql,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Wl({initialFilters:t,availableFields:n}={}){const[a,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(N=>N.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=n||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=N=>{const D=v=>{if(v.id===N){const C=i[0]||d,S=s.getDataType(C.dataType)==="date";return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:C,operator:S?"between":"=",value:S?[]:""}]}}return{...v,groups:v.groups.map(D)}};r(D(a))},m=N=>{const D=v=>{if(v.id===N){const C=i[0]||d,S=s.getDataType(C.dataType)==="date";return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:C,operator:S?"between":"=",value:S?[]:""}],groups:[]}]}}return{...v,groups:v.groups.map(D)}};r(D(a))},h=(N,D)=>{const v=C=>C.id===N?{...C,conditions:C.conditions.filter(S=>S.id!==D)}:{...C,groups:C.groups.map(v)};r(v(a))},x=(N,D)=>{const v=C=>C.id===N?{...C,groups:C.groups.filter(S=>S.id!==D)}:{...C,groups:C.groups.map(v)};r(v(a))},j=(N,D,v,C)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const S=F=>F.id===N?{...F,conditions:F.conditions.map(I=>I.id===D?{...I,[v]:C}:I)}:{...F,groups:F.groups.map(S)};r(S(a))},b=(N,D,v)=>{const C=S=>S.id===N?{...S,conditions:S.conditions.map(F=>F.id===D?{...F,...v}:F)}:{...S,groups:S.groups.map(C)};r(C(a))},p=(N,D)=>{const v=C=>C.id===N?{...C,logicalOperator:D}:{...C,groups:C.groups.map(v)};r(v(a))},g=(N,D)=>{const v=C=>C.id===N?{...C,negate:D}:{...C,groups:C.groups.map(v)};r(v(a))},f=(N,D,v)=>{const C=S=>S.id===N?{...S,conditions:s.arrayMove(S.conditions,D,v)}:{...S,groups:S.groups.map(C)};r(C(a))},y=(N,D,v)=>{const C=S=>S.id===N?{...S,groups:s.arrayMove(S.groups,D,v)}:{...S,groups:S.groups.map(C)};r(C(a))},E=N=>{if(!N||N.conditions.length===0&&N.groups.length===0)return"-- No filters defined";const D=C=>{let S="";typeof C.field=="object"?S=C.field.entityName?`${C.field.entityName}.${C.field.name}`:C.field.name:S=String(C.field);const F=C.operator;let I=C.value;if(C.field.dataType==="string"&&!["in","not in"].includes(C.operator))typeof I=="string"?I=`'${I}'`:Array.isArray(I)&&(I=`'${I.join(", ")}'`);else if(C.field.dataType==="date"||C.field.dataType==="datetime"||C.field.dataType==="timestamp")if(C.operator==="between"&&Array.isArray(I)&&I.length===2){const P=I[0]?`'${I[0]}'`:"NULL",k=I[1]?`'${I[1]}'`:"NULL";return`${S} BETWEEN ${P} AND ${k}`}else if((C.operator==="in"||C.operator==="not in")&&Array.isArray(I)){const P=I.map(k=>k?`'${k}'`:"NULL").join(", ");return`${S} ${F} (${P})`}else typeof I=="string"||I instanceof Date?I=`'${I}'`:Array.isArray(I)&&I.length>0&&(I=`'${I[0]}'`);else if(["in","not in"].includes(C.operator)){let P=[];Array.isArray(I)?P=I.map(k=>typeof k=="string"?`'${k}'`:String(k)):typeof I=="string"?P=I.split(",").map(k=>{const w=k.trim();return C.field.dataType==="string"?`'${w}'`:w}):typeof I=="number"&&(P=[String(I)]),I=`(${P.join(", ")})`}switch(F){case"contains":return typeof I=="string"?`${S} LIKE '%${I.replace(/'/g,"")}'`:`${S} LIKE '%${String(I)}'`;case"startsWith":return typeof I=="string"?`${S} LIKE '${I.replace(/'/g,"")}%'`:`${S} LIKE '${String(I)}%'`;case"endsWith":return typeof I=="string"?`${S} LIKE '%${I.replace(/'/g,"")}'`:`${S} LIKE '%${String(I)}'`;case"isNull":return`${S} IS NULL`;case"isNotNull":return`${S} IS NOT NULL`;default:return`${S} ${F} ${I}`}},v=C=>{const S=C.conditions.map(D),F=C.groups.map(w=>v(w)),I=[...S,...F].filter(Boolean);if(I.length===0)return"";const P=I.join(` ${C.logicalOperator} `),k=I.length>1?`(${P})`:P;return C.negate?`NOT ${k}`:k};return v(N)},T=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:u,addGroup:m,removeCondition:h,removeGroup:x,updateCondition:j,updateConditionFields:b,updateGroupOperator:p,updateGroupNegate:g,reorderConditions:f,reorderGroups:y,generateSQLPreview:E,hasAnyFilters:T}}function Kl({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Ql=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(s.File,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Jl=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function Xl({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[o,c]=A.useState(!1),i=A.useMemo(()=>{const d={};return a.forEach(u=>{const m=Jl(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[a]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Kl,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Ql(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((x,j)=>e.jsxs(s.CommandItem,{value:x.id,onSelect:()=>{n(x),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===x.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:x.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:x.description&&e.jsx("span",{children:x.description})})]})]},x.id+j))]},`${d}-${m}`))},d))})]})})]})}function Ls(t){var p;const n=s.useEditorStore(g=>g.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(g=>g.card.config),o=l==null?void 0:l.joinPlan,c={...t,alias:t.name,label:"value",role:"groupby"},i={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...c,role:"sortby",direction:"asc"},u={joinPlan:o,groupByColumns:[c],metricColumns:[i],sortByColumns:[d]},m=((p=n.dataSource)==null?void 0:p.connectionId)||n.connectionId,{data:h,isPending:x,error:j}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:m,cardConfig:u,cardDataSource:n.dataSource})}catch(g){console.log(t),console.error("error",g)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(g=>({label:g.value||"BLANK",value:g.value||"BLANK",count:(g==null?void 0:g.count)||0})),isPending:x,error:j}}function Zl({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[o,c]=Ee.useState(!1),{filterValues:i}=Ls(t),d=m=>{a(n.filter(h=>h!==m))},u=m=>{n.includes(m)?a(n.filter(h=>h!==m)):a([...n,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(m=>{const h=i.find(x=>x.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:x=>{x.key==="Enter"&&d(m)},onMouseDown:x=>{x.preventDefault(),x.stopPropagation()},onClick:x=>{x.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function eo({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=Ls(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:o.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function so({value:t,operator:n,onChange:a,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),o=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=A.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(u&&m)return{from:u,to:m}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:m}}}},[t,n]),i=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),a([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),a([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const to=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ao=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],no=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],ro=["=","!=","isNull","isNotNull"],lo=["between","isNull","isNotNull"],oo={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null"};function Js(t){return oo[t]||s.titleCase(t)}function io(t){switch(t){case"string":return ao;case"number":return no;case"boolean":return ro;case"date":return lo;default:return to}}function qt({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:x,transition:j,isDragging:b}=s.useSortable({id:t.id}),{isPending:p,error:g}=Ls(t.field),f={transform:s.CSS.Transform.toString(x),transition:j};return e.jsxs("div",{ref:h,style:f,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:y=>c(a,y),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(Xl,{value:t.field,onValueChange:y=>{const E=y,T=s.getDataType(E.dataType)==="date";d(a,t.id,{field:E,value:"",operator:T?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:y=>{y==="in"||y==="not in"?d(a,t.id,{operator:y,value:[]}):y==="isNull"||y==="isNotNull"?d(a,t.id,{operator:y,value:null}):d(a,t.id,{operator:y,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Js(t.operator):""})}),e.jsx(s.SelectContent,{children:io(s.getDataType(t.field.dataType)).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y,children:Js(y)},y))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?p?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):g?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Zl,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(y=>typeof y=="string")?t.value:[],onChange:y=>d(a,t.id,{value:y}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:y=>d(a,t.id,{value:y.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(eo,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:y=>d(a,t.id,{value:y}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:y=>d(a,t.id,{value:y==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(so,{value:t.value,operator:t.operator,onChange:y=>d(a,t.id,{value:y}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:y=>l(a,t.id,"value",y.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function co({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:x,availableFields:j,renderFilterGroup:b,updateConditionFields:p}){const{attributes:g,listeners:f,setNodeRef:y,transform:E,transition:T,isDragging:N}=s.useSortable({id:t.id}),D={transform:s.CSS.Transform.toString(E),transition:T},v=S=>{const{active:F,over:I}=S;if(I&&F.id!==I.id){const P=t.conditions.findIndex(w=>w.id===F.id),k=t.conditions.findIndex(w=>w.id===I.id);P!==-1&&k!==-1&&u(t.id,P,k)}},C=S=>{const{active:F,over:I}=S;if(I&&F.id!==I.id&&a){const P=t.groups.findIndex(w=>w.id===F.id),k=t.groups.findIndex(w=>w.id===I.id);P!==-1&&k!==-1&&m(a,P,k)}};return e.jsxs("div",{ref:y,style:D,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${N?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...g,...f,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:S=>r(t.id,S),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&o(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:v,children:e.jsx(s.SortableContext,{items:t.conditions.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((S,F)=>e.jsx(qt,{condition:S,index:F,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:j,updateConditionFields:p},S.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:C,children:e.jsx(s.SortableContext,{items:t.groups.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(S=>b(S,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function uo({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:x,updateConditionFields:j,updateGroupOperator:b,updateGroupNegate:p,reorderConditions:g,reorderGroups:f,generateSQLPreview:y,hasAnyFilters:E,setCurrentFilters:T}=Wl({initialFilters:t,availableFields:n}),N=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[D,v]=A.useState(!1),C=(I,P,k)=>{const w=M=>M.id===I?{...M,conditions:M.conditions.map(O=>O.id===P?{...O,field:k,dataType:k.dataType}:O)}:{...M,groups:M.groups.map(w)};T(w(o))},S=(I,P=0,k)=>P===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:N,collisionDetection:s.closestCenter,onDragEnd:w=>{const{active:M,over:O}=w;if(O&&M.id!==O.id){const R=I.conditions.findIndex(B=>B.id===M.id),L=I.conditions.findIndex(B=>B.id===O.id);R!==-1&&L!==-1&&g(I.id,R,L)}},children:e.jsx(s.SortableContext,{items:I.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:I.conditions.map((w,M)=>e.jsx(qt,{condition:w,index:M,groupId:I.id,groupLogicalOperator:I.logicalOperator,onUpdateCondition:x,onUpdateField:C,onRemoveCondition:m,onUpdateGroupOperator:b,availableFields:c,updateConditionFields:j},w.id))})}),e.jsx(s.DndContext,{sensors:N,collisionDetection:s.closestCenter,onDragEnd:w=>{const{active:M,over:O}=w;if(O&&M.id!==O.id){const R=I.groups.findIndex(B=>B.id===M.id),L=I.groups.findIndex(B=>B.id===O.id);R!==-1&&L!==-1&&f(I.id,R,L)}},children:e.jsx(s.SortableContext,{items:I.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:I.groups.map(w=>S(w,P+1,I.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(I.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),D&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(I.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},I.id):e.jsx(co,{group:I,depth:P,parentGroupId:k,onUpdateGroupOperator:b,onUpdateGroupNegate:p,onRemoveGroup:h,onUpdateCondition:x,onUpdateField:C,onRemoveCondition:m,onReorderConditions:g,onReorderGroups:f,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:S,updateConditionFields:j},I.id),F=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):S(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{id:"advanced-mode",checked:D,onCheckedChange:I=>v(I)}),e.jsx(s.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),E&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:y(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),F>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(E?o:null),children:"Apply Filters"})]})]})}function mo({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=u=>{a(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(uo,{filters:n,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function ho({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var j;const[l,o]=A.useState(null),c=s.useEditorStore(b=>b.card),i=(j=c==null?void 0:c.config)==null?void 0:j.joinPlan,d=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],u=A.useCallback(b=>b.startsWith("card-")?null:b.startsWith("source-")||n.find(p=>p.id===b)?"source":a("groupBy").find(p=>p.id===b)?"groupBy":a("metrics").find(p=>p.id===b)?"metrics":a("pivotBy").find(p=>p.id===b)?"pivotBy":a("sortBy").find(p=>p.id===b)?"sortBy":null,[n,a]),m=A.useCallback(b=>{o(b.active.id)},[]),h=A.useCallback(b=>{const{active:p,over:g}=b;if(!g||!t){o(null);return}const f=p.id,y=g.id,E=u(f),T=u(y)||y;if(T==="sortBy"){if(E==="source"){const N=n.find(v=>v.id===f);if(!N){o(null);return}if(!(a("groupBy").some(v=>v.name===N.name&&v.qualifiedEntityName===N.qualifiedEntityName)||a("metrics").some(v=>v.name===N.name&&v.qualifiedEntityName===N.qualifiedEntityName))){o(null);return}}else if(E==="pivotBy"){o(null);return}else if(E!=="groupBy"&&E!=="metrics"&&E!=="sortBy"){o(null);return}}if(E==="source"&&T==="sortBy"){const N=[...n].find(C=>C.id===f);if(!N){o(null);return}const D=a("sortBy");if(s.fieldAlreadyExists(N,D)){o(null);return}const v=s.getNewField(N,"sortBy",D);o(null),r("sortBy",[...D,v]);return}if(E==="source"&&T!=="source"&&T!=="sortBy"){const N=[...n].find(S=>S.id===f);if(!N){o(null);return}const D=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(D.length>0){const S=D[0].qualifiedEntityName;if(!S){o(null);return}if(S!==N.qualifiedEntityName&&N.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(S,N.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const v=a(T);if(s.fieldAlreadyExists(N,v)){o(null);return}const C=s.getNewField(N,T,v);o(null),r(T,[...v,C]);return}if(E&&T&&E!=="source"&&T!=="source"&&E!==T){const N=a(E),D=a(T),v=N.find(F=>F.id===f);if(!v){o(null);return}const C=s.getNewField(v,T,D);if(o(null),T==="sortBy"){s.fieldAlreadyExists(v,D)||r(T,[...D,C]);return}const S=N.filter(F=>F.id!==f);r(E,S),r(T,[...D,C]);return}if(E&&T&&E===T&&E!=="source"){const N=a(E),D=N.findIndex(C=>C.id===f),v=N.findIndex(C=>C.id===y);if(D!==v){const C=s.arrayMove(N,D,v);r(E,C)}}o(null)},[t,n,a,r,u,i]),x=l?d.find(b=>b.id===l):null;return{activeId:l,activeField:x,handleDragStart:m,handleDragEnd:h}}function xo({dashboardFilterCount:t=0,cardFilterCount:n=0,clickFilterCount:a=0,onClick:r,className:l,showIcon:o=!0}){const c=t+n+a,i=c>0,d=t>0,u=n>0,m=a>0,h=e.jsxs(e.Fragment,{children:[o&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),x=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",l),children:h});return i?e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:x}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"p-2 text-xs",children:e.jsxs("div",{className:"space-y-1.5",children:[d&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-purple-500"}),e.jsxs("span",{children:[t," Dashboard filter",t!==1?"s":""]})]}),u&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),e.jsxs("span",{children:[n," Card filter",n!==1?"s":""]})]}),m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-gray-500"}),e.jsxs("span",{children:[a," Click filter",a!==1?"s":""]})]})]})})]})}):x}function po({activeView:t,onViewChange:n}){const a=s.useEditorStore(c=>c.card),{config:r}=A.useContext(s.SemaphorContext).tokenProps,l=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:o}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:c=>n(c),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),a.type!=="kpi"&&l&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",o&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:o?"Error":"Info"})]})})}const fo=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function go(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=A.useState(!1),[l,o]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:fo.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function jo({isOpen:t,onClose:n}){const a=it(n,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=A.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function bo(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{currentUser:a}=s.useCurrentUserInfo(),r=s.useMutation({mutationFn:async l=>{if(!(t!=null&&t.accessToken))throw new Error("No authentication token available");const c=`${n.apiServiceUrl||""}/v1/feedback`,i={...l,user:a,tokenContext:n},d=await s.postRequestRegular(c,t.accessToken,i,"POST");if(!d||!d.success)throw new Error((d==null?void 0:d.error)||"Failed to send feedback");return d},onSuccess:l=>{s.ue.success(`Feedback sent successfully! Issue: ${l.issueNumber}`,{duration:5e3})},onError:l=>{console.error("Feedback submission error:",l),s.ue.error("Failed to send feedback. Please try again later.",{duration:5e3})}});return{sendFeedback:r.mutate,sendFeedbackAsync:r.mutateAsync,isLoading:r.isPending,isSuccess:r.isSuccess,isError:r.isError,error:r.error,data:r.data,reset:r.reset}}function vo(t,n,a){return{category:t,userMessage:a,systemState:n,metadata:{url:window.location.href,userAgent:navigator.userAgent,timestamp:new Date().toISOString(),viewport:`${window.innerWidth}x${window.innerHeight}`}}}function yo({open:t,onOpenChange:n,feedbackData:a}){var p,g,f,y,E,T;const[r,l]=A.useState(""),[o,c]=A.useState(!1),{sendFeedback:i,isLoading:d,isSuccess:u,data:m,reset:h}=bo(),x=()=>{const N={...a,userMessage:r.trim()||void 0};i(N)},j=()=>{l(""),c(!1),h(),n(!1)},b={category:a.category,error:{message:(p=a.systemState)==null?void 0:p.errorMessage,sql:(g=a.systemState)==null?void 0:g.generatedSql,errorSql:(f=a.systemState)==null?void 0:f.errorSql},cardConfig:(y=a.systemState)==null?void 0:y.cardConfig,dataSource:(E=a.systemState)==null?void 0:E.dataSource,filters:(T=a.systemState)==null?void 0:T.dashboardFilters,metadata:a.metadata};return e.jsx(s.Dialog,{open:t,onOpenChange:j,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:u?"Feedback Sent Successfully":"Report Query Generation Issue"}),e.jsx(s.DialogDescription,{children:u?`Your feedback has been submitted with issue number: ${m==null?void 0:m.issueNumber}`:"Help us improve by reporting this query generation issue. Your feedback will be sent to our support team."})]}),!u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"message",children:"Additional Information (Optional)"}),e.jsx(s.Textarea,{id:"message",placeholder:"Please describe what you were trying to do when this error occurred...",value:r,onChange:N=>l(N.target.value),className:"min-h-[100px] resize-none ring-inset focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",disabled:d})]}),e.jsxs(s.Collapsible,{open:o,onOpenChange:c,children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"flex w-full items-center justify-between p-2 hover:bg-muted",children:[e.jsx("span",{className:"text-sm font-medium",children:"View data to be sent"}),o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx(s.ScrollArea,{className:"h-[300px] w-full rounded-md border bg-muted/50 p-4",children:e.jsx("div",{className:"text-xs",children:e.jsx(s.CodeHighlighter,{code:JSON.stringify(b,null,2),language:"json"})})})})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:j,disabled:d,children:"Cancel"}),e.jsx(s.Button,{onClick:x,disabled:d,className:"min-w-[100px]",children:d?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Sending..."]}):"Send Feedback"})]})]}),u&&e.jsxs("div",{className:"flex flex-col items-center space-y-4 py-6",children:[e.jsx(ha,{className:"h-12 w-12 text-green-600"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-medium",children:"Thank you for your feedback!"}),e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Issue Number:"," ",e.jsx("span",{className:"font-mono font-medium",children:m==null?void 0:m.issueNumber})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Our support team will review your feedback and take appropriate action."})]}),e.jsx(s.Button,{onClick:j,className:"mt-4",children:"Close"})]})]})})}var Ht=(t=>(t.QUERY_GENERATION="query-generation",t))(Ht||{});function No({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:l,filterCount:o,activeCard:c,columns:i,columnsLoading:d,columnsError:u}){var $;const m=s.useEditorStore(X=>X.card),h=s.useDashboardStore(X=>X.filterValues),x=(h==null?void 0:h.length)||0,{updateCardConfig:j,setCard:b,updateCardInFrame:p,setCardId:g,setShowAIDialog:f}=s.useEditorActions(),{updateCardId:y}=s.useDashboardActions(),[E,T]=A.useState(null),N=s.useEditorStore(X=>X.showAIDialog),[D,v]=A.useState(!1),[C,S]=A.useState(!1),[F,I]=A.useState(null),{isConsoleMode:P}=s.useDashboardPreferences(),{config:k}=A.useContext(s.SemaphorContext).tokenProps,w=(k==null?void 0:k.showInfoTab)!==!1,M=s.useEditorStore(X=>{var _;return((_=X.card.customCardPreferences)==null?void 0:_.url)&&X.card.type==="custom"}),{data:O,errorMessage:R,isLoading:L,isFetching:B,errorSql:Y,pagination:J}=s.useDashboardCardQuery(c),V=(X,_)=>{const G={...c,paginationConfig:{page:X+1,pageSize:_}};b(G),p(G)};function K(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(m.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(h||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(c.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",i.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:d?"Loading...":u?"Error loading columns":JSON.stringify(i.slice(0,5),null,2)})]})]})]})}const q=X=>{if(!m.config)return;if(!X.length){j(m.id,{...m.config,sortByColumns:[]});return}const _=m.config,G=X.map(({id:se,desc:re})=>{var ne,le;const he=(ne=_.metricColumns)==null?void 0:ne.find(de=>de.label===se),z=(le=_.groupByColumns)==null?void 0:le.find(de=>de.label===se),ee=he||z;return ee?{id:s.getFieldId("sortBy",ee),name:ee.name,dataType:ee.dataType,label:ee.label,qualifiedEntityName:ee.qualifiedEntityName,entityId:ee.entityId,entityName:ee.entityName,entityType:ee.entityType,role:"sortby",direction:re?"desc":"asc"}:null}).filter(se=>se!==null);j(m.id,{..._,sortByColumns:G})},Z=A.useMemo(()=>{var X,_;return(_=(X=m.config)==null?void 0:X.sortByColumns)==null?void 0:_.map(G=>({id:G.label,desc:G.direction==="desc"}))},[($=m.config)==null?void 0:$.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[a&&K(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&N&&e.jsx(At,{variant:"outline"}),e.jsx(po,{activeView:t,onViewChange:n}),l&&e.jsx(xo,{dashboardFilterCount:x,cardFilterCount:o,onClick:l,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(go,{})}),N&&e.jsx(cs,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end"),children:[t==="chart"&&e.jsx(Mt,{}),!N&&e.jsx(s.IconButton,{onClick:()=>f(!N),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!D&&M&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>v(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(Lt,{})}),t==="table"&&(O==null?void 0:O.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:c,data:(O==null?void 0:O.records)||[],paginationMetadata:J,onPaginationChange:V,isLoading:L||B,onSortChange:q,sortState:Z})}),t==="info"&&w&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[P&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:m.id,onSave:X=>{const _=s.sanitizeCardId(X);if(!_){T("Card ID cannot be empty");return}const G=y(m.id,_);if(G.success){g(_);const se={...m,id:_};b(se),p(se),T(null),s.ue.success("Card ID updated successfully")}else T(G.error||"Failed to update Card ID"),s.ue.error(G.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:m.id,className:"h-5 w-5"})]}),E&&e.jsx("p",{className:"text-xs text-destructive",children:E})]}),R||Y?e.jsx(Ct,{error:R,errorSql:Y,onSendFeedback:()=>{const X=vo(Ht.QUERY_GENERATION,{cardConfig:m.config,dataSource:c.dataSource,dashboardFilters:h,errorMessage:R,errorSql:Y,generatedSql:O==null?void 0:O.sql});I(X),S(!0)}}):e.jsxs(e.Fragment,{children:[(O==null?void 0:O.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(St,{sql:O==null?void 0:O.sql,error:R,errorSql:Y})]})]})})]}),e.jsx(jo,{isOpen:D,onClose:()=>v(!1)}),F&&e.jsx(yo,{open:C,onOpenChange:S,feedbackData:F})]})]})}function Co({activeField:t}){const[n,a]=A.useState(!0);return A.useEffect(()=>{t&&a(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Ms,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const So=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const n=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},a=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function wo(){var Y,J;const[t,n]=A.useState("chart"),[a,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(V=>V.showAIDialog),u=s.useDashboardStore(V=>V.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(V=>V.card.type);A.useEffect(()=>So(),[]);const x=()=>{o(!0)},j=V=>{m(V)},b=s.useEditorStore(V=>V.frame),p=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.activeTabCardId),s.useEditorStore(V=>V.actions.getAvailableFields);const{addCard:g,removeCard:f,updateCard:y,setActiveCard:E,updateFilters:T}=s.useEditorActions(),{columns:N=[],isLoading:D,error:v}=s.useColumns(),C=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),S=p,{getFieldsForContainer:F,setFieldsForContainer:I}=As(S),{activeField:P,handleDragStart:k,handleDragEnd:w}=ho({activeCardId:b.activeCardId,sourceFields:N,getFieldsForContainer:F,setFieldsForContainer:I}),M=(V,K)=>{K&&T(V,K)},O=V=>{var K;y(V,{config:{...(K=b.cards.find(q=>q.id===V))==null?void 0:K.config,filters:void 0}})},R=N,L=V=>{if(!V)return 0;let K=V.conditions.length;return V.groups.forEach(q=>{K+=L(q)}),K},B=L(((Y=S==null?void 0:S.config)==null?void 0:Y.filters)||null);return e.jsxs(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragStart:k,onDragEnd:w,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(El,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Hl,{selectedChart:h,onChartChange:j,groupByFields:F("groupBy"),pivotByFields:F("pivotBy"),metricsFields:F("metrics"),sortByFields:F("sortBy")}),e.jsx(No,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:x,filterCount:B,activeCard:S,dataSourceState:p.dataSource||s.EMPTY_DATA_SOURCE,columns:N,columnsLoading:D,columnsError:v,getFieldsForContainer:F,cards:b.cards,activeCardId:b.activeCardId,addCard:g,setActiveCard:E})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),S&&e.jsx(mo,{cardId:S.id,filters:((J=S.config)==null?void 0:J.filters)||null,onFiltersChange:M,onClearFilters:O,availableFields:R,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Co,{activeField:P||null})})]})}function Do({authToken:t,onSave:n,onClose:a}){const r=A.useRef(null),l=s.useEditorStore(y=>y.showAIDialog),o=s.useEditorStore(y=>y.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:x,handleDragCancel:j,sensors:b}=Qn();A.useEffect(()=>{n&&d(n),a&&u(a)},[n,d,a,u]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var y,E;l?((y=r.current)==null||y.resize(40),i(!0)):(i(!1),(E=r.current)==null||E.resize(0))},[l,i]);function p(y){y<1?i(!1):l||i(!0)}function g(){return e.jsxs(e.Fragment,{children:[e.jsx(Nt,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(pl,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(qs,{})})]})]})}function f(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(wo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(qs,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:b,onDragStart:x,onDragEnd:h,onDragOver:m,onDragCancel:j,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:g()})}):f()})}function To(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(c=>c.actions),a=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),n(!1))}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(Do,{onSave:l,onClose:o})})}function ko({column:t}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{className:"shrink-0",asChild:!0,children:s.isTextDataType(t.data_type)?e.jsx(s.TextIcon,{className:"size-3 text-muted-foreground"}):s.isNumberDataType(t.data_type)?e.jsx(De,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(Le,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(ma,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})})}function Eo(){const t=s.useEditorStore(o=>o.selectedDatabaseName),n=s.useEditorStore(o=>o.selectedTableName),a=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=ks();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(o.column_name)&&i.table===n&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ko,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function Io({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx($e,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ke,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function Ao(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useDashboardStore(f=>f.dashboard.filters)||[],{assignFilter:o}=ks(),c=s.useEditorStore(f=>f.card.dataSource),{columns:i=[],isLoading:d,error:u}=s.useColumns(),m=i.filter(f=>f.name.toLowerCase().includes(t.toLowerCase())||f.dataType.toLowerCase().includes(t.toLowerCase())||f.label&&f.label.toLowerCase().includes(t.toLowerCase())),h=f=>{const y=s.getDataType(f.dataType);return y==="number"?"metrics":(["date","string","boolean"].includes(y),"dimensions")},x=a==="all"?m:m.filter(f=>h(f)===a),j=m.filter(f=>h(f)==="dimensions").length,b=m.filter(f=>h(f)==="metrics").length,p=f=>{const y={column_name:f.name,data_type:f.dataType,label:f.label,description:f.description};o(y,"dashboard",f)};if(d)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(u)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:u.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const g=m.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:f=>n(f.target.value)})]}),g&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:f=>r(f),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:b})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[x.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),x.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),x.map(f=>{const y=l==null?void 0:l.some(E=>{var T;return E.title===f.name||((T=E.column)==null?void 0:T.includes(f.name))});return e.jsx("div",{onClick:()=>p(f),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":y}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Io,{dataType:f.dataType}),e.jsx("span",{children:f.label||f.name})]})},f.id)})]})]})}function Mo(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),n=s.useCurrentActiveCard(),a=n&&((r=n.dataSource)==null?void 0:r.selectedEntities)&&n.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:a?e.jsx(Ao,{}):e.jsx(Nt,{type:"filter",ColumnsComponent:()=>e.jsx(Eo,{})})})]})}function Lo(){const t=s.useDashboardStore(r=>r.dashboard.filters),n=s.useDashboardStore(r=>r.theme),a=t==null?void 0:t.filter(r=>r.hide);return a!=null&&a.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":n==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":n==="dark"}),children:a==null?void 0:a.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Ro(){const t=s.useDashboardStore(r=>r.showFilters),n=s.useDashboardStore(r=>r.isVisualEditing),a=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":n,"flex grow overflow-auto":!n}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[a&&e.jsx(Lo,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Mo,{})})]})}function Oo(){const t=s.useDashboardStore(l=>l.dashboard),n=s.useDashboardStore(l=>l.actions.setDashboard),a=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!a}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),n(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function Wt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,n)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},n))})]})})}function Fo({visual:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var N,D,v;const{selectVisual:x}=s.useManagementActions(),j=s.useIsVisualSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences();s.useDashboardStore(C=>C.actions.setIsDashboardPanelOpen);const[p,g]=A.useState(!1),[f,y]=A.useState(!1);A.useEffect(()=>{a?(g(!0),y(!0)):f&&(g(!1),y(!1))},[a,f]);const E=()=>e.jsx(os,{className:"h-4 w-4"}),T=()=>{x(t),c==null||c(t)};return e.jsx(s.Card,{className:s.cn("group cursor-pointer border-border/50 p-3 transition-colors hover:bg-accent/50",j&&"ring-1 ring-primary"),onClick:T,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children:E()}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:C=>i==null?void 0:i(t.id,{title:C}),isEditable:t.ownership.isOwner&&j,isPending:r,placeholder:"Untitled Visual",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"mr-1 h-2.5 w-2.5"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:C=>i==null?void 0:i(t.id,{description:C}),isEditable:t.ownership.isOwner&&j,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2"})]}),e.jsxs("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex flex-shrink-0 items-center gap-1"),onClick:C=>C.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:C=>{C.stopPropagation(),o(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:p,onOpenChange:g,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),console.log("Edit visual",t),c==null||c(t)},children:[e.jsx(Ba,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),m(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),d(t)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((N=t.ownership.createdBy)==null?void 0:N.type)==="tenant"||((D=t.ownership.createdBy)==null?void 0:D.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((v=t.ownership.createdBy)==null?void 0:v.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:h(t.lastModified)})]})]})]})]})]})]})},t.id)}function Po(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(!1),[m,h]=A.useState(null),[x,j]=A.useState(!1),[b,p]=A.useState(null),[g,f]=A.useState(null),{setIsDashboardEditing:y,setIsVisualEditing:E}=s.useDashboardActions(),{handleEditLibraryVisual:T,handleAddLibraryVisual:N}=_e(),{resources:D,isLoading:v,isError:C,createResource:S,updateResource:F,deleteResource:I,duplicateResource:P,isCreating:k,isDeleting:w}=s.useVisualManagement(()=>{j(!1),p(null)},()=>{r(!1),o(""),i("")});s.useCurrentUserInfo();const M=D.filter(G=>{var se,re;return((se=G==null?void 0:G.title)==null?void 0:se.toLowerCase().includes(t.toLowerCase()))||((re=G==null?void 0:G.description)==null?void 0:re.toLowerCase().includes(t.toLowerCase()))}),O=G=>new Date(G).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),R=()=>{l.trim()&&S({title:l,description:c,isPrivate:!1})},L=G=>{p(G),j(!0)},B=()=>{b&&I(b.id)},{startUpdating:Y,stopUpdating:J,isUpdating:V}=s.useResourceUpdateState(),K=(G,se)=>{const re=se.title!==void 0?"title":"description";Y(G,re),F({resourceId:G,data:se},{onSuccess:()=>{J(G,re)},onError:()=>{J(G,re)}})},q=G=>{f(G),P(G,{onSettled:()=>f(null)})},Z=G=>{T(G)},$=G=>{N(G)},X=G=>{const se=D.find(re=>re.id===G);se&&F({resourceId:G,data:{isPrivate:!se.isPrivate}})},_=G=>{h(G),u(!0)};return v?e.jsx(Wt,{}):C?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:a?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:G=>o(G.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:G=>i(G.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:R,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||k,children:k?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:k,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"w-full bg-primary text-primary-foreground hover:bg-primary/90",disabled:k,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),k?"Creating...":"Create New Visual"]})}),D&&D.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:G=>n(G.target.value),className:"h-9"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:M.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(os,{className:"mx-auto h-12 w-12 text-muted-foreground/50"})}),e.jsx("h3",{className:"mb-1 font-medium text-foreground",children:t?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:t?"Try adjusting your search":"Create your first visual component to get started"}),!t&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Visual"]})]}):M.map(G=>e.jsx(Fo,{visual:G,onAddVisual:$,onEditVisual:Z,onUpdateVisual:K,onDeleteClick:L,onDuplicateVisual:q,onTogglePrivacy:X,onShareVisual:_,isDeleting:w,isDuplicating:g===G.id,isTitleUpdating:V(G.id,"title"),isDescriptionUpdating:V(G.id,"description"),formatDate:O},G.id))})}),d&&m&&e.jsx(is,{resource:m,resourceType:s.ResourceType.VISUAL,onClose:()=>{u(!1),h(null)}}),e.jsx(s.AlertDialog,{open:x,onOpenChange:G=>{!G&&w||(j(G),G||p(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',b==null?void 0:b.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:w,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:G=>{G.preventDefault(),G.stopPropagation(),B()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:w,children:[w?e.jsx(s.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):e.jsx(s.Trash2,{className:"mr-2 h-3.5 w-3.5"}),w?"Deleting...":"Delete"]})]})]})})]})}function Bo({dashboard:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var N,D,v;const{selectDashboard:x}=s.useManagementActions(),j=s.useIsDashboardSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences(),[p,g]=A.useState(!1),[f,y]=A.useState(!1);s.useDashboardStore(C=>C.actions.setIsDashboardPanelOpen),A.useEffect(()=>{a?(g(!0),y(!0)):f&&(g(!1),y(!1))},[a,f]);const E=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),T=()=>{x(t),o(t.id),h==null||h(t.id)};return e.jsx(s.Card,{className:s.cn("group cursor-pointer border-border/50 p-3 transition-colors hover:bg-accent/50",j&&"ring-1 ring-primary"),onClick:T,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children:E()}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:C=>c==null?void 0:c(t.id,{title:C}),isEditable:t.permissions.canEdit&&j,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"mr-1 h-2.5 w-2.5"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:C=>c==null?void 0:c(t.id,{description:C}),isEditable:t.permissions.canEdit&&j,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2"})]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0"),onClick:C=>C.stopPropagation(),children:e.jsxs(s.DropdownMenu,{modal:!1,open:p,onOpenChange:g,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.preventDefault(),C.stopPropagation(),d(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),u(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),i(t)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((N=t.ownership.createdBy)==null?void 0:N.type)==="tenant"||((D=t.ownership.createdBy)==null?void 0:D.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((v=t.ownership.createdBy)==null?void 0:v.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:m(t.lastModified)})]})]})]})]})})]})},t.id)}function zo({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function Vo(t){const[n,a]=A.useState(""),[r,l]=A.useState(!1),[o,c]=A.useState(""),[i,d]=A.useState(""),[u,m]=A.useState(!1),[h,x]=A.useState(null),[j,b]=A.useState(!1),[p,g]=A.useState(null),[f,y]=A.useState(null),E=s.useManagementStore(z=>z.lastSelectedDashboard),T=s.useManagementStore(z=>z.selectedDashboard),N=s.useManagementStore(z=>z.actions.selectDashboard),D=s.useManagementStore(z=>z.actions.clearSelectedDashboard),{tokenProps:v,id:C}=s.useSemaphorContext(),{permissions:S}=s.useRoleAwareDisplayPreferences(),{resources:F,isLoading:I,isError:P,createResource:k,updateResource:w,deleteResource:M,duplicateResource:O,isCreating:R,isDeleting:L}=s.useDashboardManagement(()=>{b(!1);const z=p==null?void 0:p.id;g(null),(T==null?void 0:T.id)===z&&(!(v!=null&&v.dashboard_id)&&!C?D():E&&E.id!==z&&N(E))},()=>{l(!1),c(""),d("")}),{currentUser:B}=s.useCurrentUserInfo(),Y=F.filter(z=>{var ee,ne;return((ee=z==null?void 0:z.title)==null?void 0:ee.toLowerCase().includes(n.toLowerCase()))||((ne=z==null?void 0:z.description)==null?void 0:ne.toLowerCase().includes(n.toLowerCase()))}),J=z=>new Date(z).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),V=()=>{o.trim()&&k({title:o,description:i,isPrivate:!1})},K=z=>{var ee;(ee=t.onLoadDashboard)==null||ee.call(t,z)},q=z=>{g(z),b(!0)},Z=()=>{p&&M(p.id)},$=z=>{y(z),O(z,{onSettled:()=>y(null)})},{startUpdating:X,stopUpdating:_,isUpdating:G}=s.useResourceUpdateState(),se=(z,ee)=>{const ne=ee.title!==void 0?"title":"description";X(z,ne),w({resourceId:z,data:ee},{onSuccess:()=>{_(z,ne)},onError:()=>{_(z,ne)}})},re=z=>{const ee=F.find(ne=>ne.id===z);ee&&w({resourceId:z,data:{isPrivate:!ee.isPrivate}})},he=z=>{x(z),B==null||B.type,m(!0)};return I?e.jsx(Wt,{}):P?e.jsx(zo,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[S.canCreateDashboards&&e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:o,onChange:z=>c(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:z=>d(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:V,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||R,children:R?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:R,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"w-full bg-primary text-primary-foreground hover:bg-primary/90",disabled:R,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),R?"Creating...":"Create New Dashboard"]})}),F&&F.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:n,onChange:z=>a(z.target.value),className:"h-9"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:Y.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.ChartColumn,{className:"mx-auto h-12 w-12 text-muted-foreground/50"})}),e.jsx("h3",{className:"mb-1 font-medium text-foreground",children:n?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:n?"Try adjusting your search":S.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),S.canCreateDashboards&&!n&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>l(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Dashboard"]})]}):Y.map(z=>e.jsx(Bo,{dashboard:z,isDeleting:L,isDuplicating:f===z.id,isTitleUpdating:G(z.id,"title"),isDescriptionUpdating:G(z.id,"description"),onLoadDashboard:K,onEditDashboard:t.onEditDashboard,onUpdateDashboard:se,onDeleteClick:q,onDuplicateDashboard:$,onTogglePrivacy:re,onShareDashboard:he,formatDate:J,onDashboardItemClick:t.onDashboardItemClick},z.id))})}),u&&h&&e.jsx(is,{resource:h,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{m(!1),x(null)}}),e.jsx(s.AlertDialog,{open:j,onOpenChange:z=>{!z&&L||(b(z),z||g(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',p==null?void 0:p.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:L,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:z=>{z.preventDefault(),z.stopPropagation(),Z()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:L,children:[L?e.jsx(s.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):e.jsx(s.Trash2,{className:"mr-2 h-3.5 w-3.5"}),L?"Deleting...":"Delete"]})]})]})})]})}function Kt({isOpen:t,onClose:n,className:a,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(E=>E.dashboard);const{setDashboard:o,addSheet:c}=s.useDashboardStore(E=>E.actions),{currentUser:i}=s.useCurrentUserInfo(),d=i,{permissions:u}=s.useRoleAwareDisplayPreferences(),m=(u.canAccessVisuals,"dashboards"),[h,x]=s.useLocalStorageState("resource-management-active-tab",m),j=u.canAccessVisuals?h:"dashboards",b=l==="overlay",p=it(n,{enabled:t&&b}),g=s.cn("flex h-full flex-col border-r bg-background",b?s.cn("absolute inset-y-0 left-0 z-[51] w-96 shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"pointer-events-none -translate-x-full"):"w-full max-w-[28rem] min-w-[18rem] overflow-hidden shadow-sm",a),f=E=>{},y=E=>{console.log("Editing dashboard:",E)};return e.jsx(s.TooltipProvider,{children:(!b||t)&&e.jsxs("div",{ref:p,className:g,children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border p-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:d&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-full bg-primary/10",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:d.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:d.name}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:u.canCreateDashboards?"default":"secondary",className:"cursor-help text-xs",children:u.canCreateDashboards?e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-1 h-3 w-3"}),"Power User"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Viewer"]})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email}),d.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(d.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",d.id]})]})})]})})]})]})}),e.jsx(s.IconButton,{className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",onClick:n,tooltip:"Close Sidebar",children:e.jsx(Pa,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:j,onValueChange:u.canAccessVisuals?x:void 0,className:"flex h-9 grow flex-col",children:[u.canAccessVisuals?e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}):e.jsx("div",{className:"px-4 pb-0 pt-4",children:e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Dashboards"})}),e.jsx(s.TabsContent,{value:"dashboards",className:"mt-4 flex-1",children:e.jsx(Vo,{onLoadDashboard:f,onEditDashboard:y,onDashboardItemClick:r})}),u.canAccessVisuals&&e.jsx(s.TabsContent,{value:"visuals",className:"mt-4 flex-1",children:e.jsx(Po,{})})]})})]})})}function _o({showControls:t=!1,showFooter:n=!0,...a}){const r=s.useDashboardStore(x=>x.isDashboardPanelOpen);s.useDashboardStore(x=>x.isVisualEditing);const l=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),o=20,c=20,i=30,d=r,u=A.useRef(null),m=A.useRef(null);A.useEffect(()=>{u.current&&m.current&&(r?(u.current.resize(o),m.current.resize(100-o)):(u.current.resize(0),m.current.resize(100)))},[r]);const{preferences:h}=a;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:h,children:[e.jsx(Oo,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Yn,{}),e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",className:"flex grow overflow-hidden",children:[e.jsx(s.ResizablePanel,{ref:u,className:s.cn("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?o:0,minSize:d?c:0,maxSize:d?i:0,children:e.jsx(Kt,{isOpen:r,onClose:()=>l(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{withHandle:d,className:s.cn("w-1",{"w-0":!d})}),e.jsx(s.ResizablePanel,{ref:m,className:"flex min-w-0 flex-1",defaultSize:d?100-o:100,minSize:d?40:100,children:e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(To,{}),e.jsx(Ro,{})]})})]})]})]})})]})})}exports.AdvancedModeToggle=vt;exports.DashboardPlus=_o;exports.ResourceManagementPanel=Kt;exports.ScheduleDashboard=nt;exports.SelectComponent=Fe;exports.ShareDialog=is;exports.VisualBadge=pt;exports.VisualEditingControls=bt;exports.cleanCard=at;exports.getDashbaordStateWithoutData=as;
|
|
332
|
+
`;k(V)}function P(){return e.jsxs(e.Fragment,{children:[l&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(ar,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>o(!l),className:"absolute bottom-0 right-6 size-7 p-1",children:l?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function Y(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(sr,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(tr,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function J(){return e.jsx("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:C||O,onClick:()=>{F()},className:"h-8 shrink-0",size:"sm",children:[C||O?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(wt,{errorSql:w,sql:S==null?void 0:S.sql,error:R,onDebugWithAssistant:L}),e.jsx(cs,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:V=>r(V),className:"h-8",size:"sm",variant:"outline",children:e.jsx(er,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:i,onClick:()=>{T(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:i?"":"Type your question..."})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[Y(),P()]}),J()]})}const rr=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:os}];function lr({className:t}){const n=s.useEditorStore(d=>d.card),{setCardType:a,setCard:r,updateCardInFrame:l}=s.useEditorActions(),o=["table","aggregateTable","pivotTable"].includes(n.type),c=s.hasValidCardConfig(n.config);if(!o||!c)return null;const i=d=>{var m;const u=d;if(u==="aggregateTable"&&((m=n.config)!=null&&m.pivotByColumns)&&n.config.pivotByColumns.length>0){const h={...n,type:u,config:{...n.config,pivotByColumns:[]}};r(h),l(h)}else{a(u);const h={...n,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:i,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:rr.map(d=>{const u=d.icon,m=n.type===d.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:d.value,id:`table-type-${d.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${d.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",m?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),d.label]})]},d.value)})})})}function or({card:t}){var k,T,N,D,v,S,C,O,I,B,E;const[n,a]=A.useState(!1),[r,l]=A.useState([]),{authToken:o}=s.useSemaphorContext(),{theme:c}=s.useTheme(),i=s.getTokenParams(o==null?void 0:o.accessToken),d=s.useDashboardStore(w=>w.themeStyle),u={mode:c||"system",colors:((T=(k=d==null?void 0:d.chart)==null?void 0:k.dataset)==null?void 0:T.backgroundColor)||[]};(N=t.customCardPreferences)!=null&&N.inputData;const{getCard:m}=s.useCustomVisual(((D=t.customCardPreferences)==null?void 0:D.url)||""),h=((v=t.customCardPreferences)==null?void 0:v.visualType)||"single",x=s.useEditorStore(w=>w.frame),{setCustomCardPreferences:g}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(t),p=A.useCallback((w,M)=>{l(F=>({...F,[w]:M}))},[]);if(!((S=t.customCardPreferences)!=null&&S.componentName))return null;const j=m((C=t.customCardPreferences)==null?void 0:C.componentName);function f(w){a(w)}const y=Object.keys(((O=t.customCardPreferences)==null?void 0:O.dataInputCardIds)||{}).map(w=>{var R,L,P;const M=(L=(R=t.customCardPreferences)==null?void 0:R.dataInputCardIds)==null?void 0:L[w].cardId,F=(P=x==null?void 0:x.cards)==null?void 0:P.find(Y=>Y.id===M);return F||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(A.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[j&&h==="single"&&e.jsx(j,{editing:!0,params:i,theme:u,settings:(I=t.customCardPreferences)==null?void 0:I.settings,onDataChange:p,data:(b==null?void 0:b.records)||[]}),j&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((B=t.customCardPreferences)==null?void 0:B.dataInputCardIds)||{}).map(w=>{var R,L,P;const M=(L=(R=t.customCardPreferences)==null?void 0:R.dataInputCardIds)==null?void 0:L[w].cardId,F=(P=x==null?void 0:x.cards)==null?void 0:P.find(Y=>Y.id===M);if(F)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:f,onDataChange:p,dataInputIndex:w,card:F},F.id+w)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(j,{theme:u,onDataChange:p,settings:y.map(w=>{var M;return(M=w==null?void 0:w.customCardPreferences)==null?void 0:M.settings}),data:y.map(w=>w!=null&&w.id?r==null?void 0:r[w.id]:[])})})]})]},(E=t.customCardPreferences)==null?void 0:E.componentName)})}function Tt({className:t,...n}){var S;const a=s.useEditorStore(C=>C.card),r=s.isExplorerCard(a),l=((S=a.customCardPreferences)==null?void 0:S.showCardHeader)??!0,o=s.useEditorStore(C=>C.frame),c=s.useDashboardStore(C=>C.dashboard.filters),i=s.useEditorStore(C=>C.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),u=c==null?void 0:c.find(C=>C.id===o.filterId),{data:m,isLoading:h,isFetching:x,errorMessage:g,pagination:b}=s.useDashboardCardQuery(a),{setCard:p,updateCardInFrame:j}=s.useEditorActions(),{data:f}=s.useTopoJson(a),y=A.useMemo(()=>{var C;return a.type!=="pivotTable"||!((C=m==null?void 0:m.records)!=null&&C.length)?null:{records:m.records,columnSubtotalMeta:m.columnSubtotalMeta,subtotalColumns:m.subtotalColumns||[],pivotSchema:m.pivotSchema||[],groupByColumns:m.groupByColumns}},[a.type,m==null?void 0:m.records,m==null?void 0:m.columnSubtotalMeta,m==null?void 0:m.subtotalColumns,m==null?void 0:m.pivotSchema,m==null?void 0:m.groupByColumns]),k=s.usePivotTableConfig(a,y),T=(C,O)=>{var B,E;const I={...a,paginationConfig:{page:C+1,pageSize:O}};p(I),j(I),a.sql&&((E=(B=a.preferences)==null?void 0:B.tablePrefs)!=null&&E.enableDevModePagination)&&i(!0)},N=A.useMemo(()=>!a.id||!(m!=null&&m.records)?null:s.createChartConfig({card:a,data:m==null?void 0:m.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:f}),[a.id,m==null?void 0:m.records,a.type,a.queryConfig,a.customCfg,a.preferences,f]);function D(C){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(or,{card:C})})}function v(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!x)return g?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||x)&&a.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return D(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&N)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:h||x?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:N})});if(a.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:a,data:(m==null?void 0:m.records)||[],paginationMetadata:b,onPaginationChange:T,isLoading:h||x})});if(a.type==="pivotTable"&&k)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:a,data:k.data,options:k.options,onAggregationChange:C=>{const O=s.handleAggregationChange(C,a.config),I={...a,config:O};p(I),j(I)},onAggregationLabelChange:C=>{const O=s.handleAggregationLabelChange(C,a.config),I={...a,config:O};p(I),j(I)}})});if(a.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:a,data:(m==null?void 0:m.records)||[],groupByColumns:m==null?void 0:m.groupByColumns,pivotSchema:m==null?void 0:m.pivotSchema,paginationMetadata:b,onPaginationChange:T,onAggregationChange:C=>{const O=s.handleAggregationChange(C,a.config),I={...a,config:O};p(I),j(I)},isLoading:h||x})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-5",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:C=>p({...a,title:C}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(lr,{})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:C=>p({...a,description:C}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),u&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:u.title||u.column,onSave:C=>d({...u,title:C}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:u})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:v()})]})}const gs=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:n,onChange:a}),ir=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),cr=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(gs,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(gs,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(gs,{language:"javascript",value:t,onChange:l})})]}),dr=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function ur(){const[t,n]=A.useState(!1),[a,r]=A.useState(""),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(""),m=s.useEditorStore(N=>N.card),h=s.useEditorStore(N=>N.card.customCfg),x=h?JSON.stringify(h,null,2):"",{data:g}=s.useDashboardCardQuery(m),{data:b}=s.useTopoJson(m),{setCardCustomCfg:p,setCustomVisualCode:j}=s.useEditorActions(),f=N=>{var D,v;return JSON.stringify({...N,data:{...N.data,datasets:(v=(D=N.data)==null?void 0:D.datasets)==null?void 0:v.map(S=>({...S,data:[]}))}},null,2)},y=()=>{var D,v;if(!((D=g==null?void 0:g.records)!=null&&D.length))return;const N=s.createChartConfig({card:m,data:g.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:b});if(N){r(f(N)),i(((v=m.preferences)==null?void 0:v.customVisualCode)||"");const S=s.merge(N,h);o(f(S))}},k=()=>{try{if(c&&j(c),l){const N=JSON.parse(l),D=s.getObjectDiff(JSON.parse(a),N);p(D),u("")}}catch{u("Invalid JSON configuration")}},T=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:y,className:T?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(ir,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Tt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(cr,{customCode:c,cardCustomCfgString:x,mergedConfig:l,onConfigChange:N=>o(N??""),onCodeChange:N=>i(N??"")})]}),e.jsx(dr,{error:d,hasCardCustomConfig:!!h,onReset:()=>{o(a),p(null)},onApply:k,onClose:()=>n(!1)})]})]})}function ds(t){const[n,a]=A.useState(null);return n}function kt(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{data:a,isLoading:r,isFetching:l,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(n.apiServiceUrl,t==null?void 0:t.accessToken)});return{data:a,isLoading:r,isFetching:l,isError:o}}function Et(){const{data:t,isLoading:n,isError:a}=kt(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let o=n,c=a;return r.forEach((i,d)=>{var u;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const m=t.plugins[d],h=i.data.visuals.map(x=>({name:x.name,pluginName:m.label,componentType:x.componentType,pluginType:m.type,icon:x.icon,chartType:x.chartType,url:m.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function mr({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=Et(),d=A.useCallback((u,m)=>{n(null),a({}),r(u),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[n,a,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((u,m)=>e.jsx(hr,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const hr=({text:t,icon:n,onClick:a})=>{const r=ds(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:a,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function It({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(m,h){o(null),r({}),a(m),["custom","text","map"].includes(m)&&(l(!0),i(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(s.Table2,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnIncreasing,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(s.ChartLine,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnStacked,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(s.MdStackedLineChart,{className:s.cn("size-5",n),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(s.ChartScatter,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(s.TbChartBubble,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(s.ChartPie,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(s.Donut,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(s.TbChartFunnel,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(s.Radar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(s.PiChartPolar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(s.Tornado,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(s.ChartNoAxesGantt,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(s.TiSortNumerically,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(s.Map,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(He,{className:s.cn("size-5",n)})})]})}function xr({chartType:t,className:n,customIcon:a,componentName:r}){const l=ds();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:n});case"line":return e.jsx(s.ChartLine,{className:n});case"pie":return e.jsx(s.ChartPie,{className:n});case"radar":return e.jsx(s.Radar,{className:n});case"scatter":return e.jsx(s.ChartScatter,{className:n});case"bubble":return e.jsx(s.TbChartBubble,{className:n});case"doughnut":return e.jsx(s.Donut,{className:n});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:n});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:n});case"polarArea":return e.jsx(s.PiChartPolar,{className:n});case"funnel":return e.jsx(s.TbChartFunnel,{className:n});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:n});case"range":return e.jsx(s.ChartNoAxesGantt,{className:n});case"kpi":return e.jsx(s.TiSortNumerically,{className:n});case"text":return e.jsx(ve,{className:n});case"map":return e.jsx(s.Map,{className:n});case"custom":return a&&l?e.jsx(l,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(He,{className:n});default:return e.jsx(s.Table2,{className:n})}}function At({variant:t="ghost"}){var o,c;const[n,a]=A.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(xr,{className:"size-4",chartType:l,customIcon:(o=r.customCardPreferences)==null?void 0:o.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"z-[51] w-72 p-1",children:[e.jsx(It,{onChartTypeChange:()=>a(!1)}),e.jsx(mr,{onChartTypeChange:()=>a(!1)})]})]})}function pr({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,o]=A.useState(!1),c=A.useRef(null),i=A.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(x){(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d())}function m(){const x=window.getSelection();if(x&&x.toString().trim()!==""){const g=x.toString();navigator.clipboard.writeText(g),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function fr(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(zs,{className:"size-4"}):e.jsx(Ps,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(zs,{className:"size-4"}):e.jsx(Ps,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function gr({className:t}){var x,g,b,p,j,f,y,k;const n=s.useEditorStore(T=>T.card),{setCardPreferences:a,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[o,c]=A.useState(!1),i=((g=(x=n.preferences)==null?void 0:x.displayOptions)==null?void 0:g.showFilterInfo)??!0,d=((p=(b=n.preferences)==null?void 0:b.displayOptions)==null?void 0:p.showCardToolbar)??!0,u=((f=(j=n.preferences)==null?void 0:j.displayOptions)==null?void 0:f.showChrome)??!0,m=((k=(y=n.preferences)==null?void 0:y.displayOptions)==null?void 0:k.allowScroll)??!0,h=(T,N)=>{var S;const D={...n.preferences,displayOptions:{...(S=n.preferences)==null?void 0:S.displayOptions,[T]:N}};a(D);const v={...n,preferences:D};l(v),r(v)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:o,onOpenChange:c,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(st,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:T=>{h("showFilterInfo",T)},onSelect:T=>T.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:T=>{h("showCardToolbar",T)},onSelect:T=>T.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:T=>{h("showChrome",T)},onSelect:T=>T.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:T=>{h("allowScroll",T)},onSelect:T=>T.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]})]})]})})}function Mt(){const t=s.useEditorStore(o=>o.card);s.useEditorStore(o=>o.isShowingVisual);const n=s.useEditorStore(o=>{var c,i;return(i=(c=o.card)==null?void 0:c.preferences)==null?void 0:i.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function l(){const o=["xy","none","x","y"],i=(o.indexOf(a)+1)%o.length;r(o[i])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(fr,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(a==="xy"||!a)&&e.jsx(os,{className:"size-4"}),a==="x"&&e.jsx(fa,{className:"size-4"}),a==="y"&&e.jsx(Va,{className:"size-4"}),a==="none"&&e.jsx(Ya,{className:"size-4"})]}),e.jsx(gr,{})]})}function jr(){const t=s.useEditorStore(b=>b.frame),n=s.useEditorStore(b=>b.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(b,p)=>{b.dataTransfer.setData("tabIndex",p.toString())},i=b=>{b.preventDefault()},d=(b,p)=>{const j=b.dataTransfer.getData("tabIndex");if(j===p.toString())return;const f=Array.from(t.cards),[y]=f.splice(parseInt(j),1);f.splice(p,0,y),a({...t,cards:f})};function u(b){const p=t.cards.filter(y=>y.id!==b),j=p[0],f={...t,cards:p,activeCardId:j.id};a(f),r(j.id),l(j)}function m(b,p){const j={...t,cards:[...t.cards,p],activeCardId:b.id};a(j),r(p.id)}function h(){const b={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};m(n,b)}function x(b){const p={dataSource:b.dataSource,connectionId:b.connectionId,lastSelectedDatabase:b.lastSelectedDatabase,lastSelectedSchema:b.lastSelectedSchema,lastSelectedTable:b.lastSelectedTable,lastSelectedDatamodelId:b.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(b,p)}function g(b,p){return b.cards.length===1&&(p.displayTab===!0||p.displayTab===void 0)||b.activeCardId!==p.id&&(p.displayTab===!0||p.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const j=p.displayTab===void 0?!1:!p.displayTab;l({...p,displayTab:j}),o({...p,displayTab:j})},children:p.displayTab===!0||p.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(ba,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((b,p)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:j=>c(j,p),onDragOver:i,onDrop:j=>d(j,p),className:"",value:b.id,children:[g(t,b),e.jsx(s.Editable,{enabled:t.activeCardId===b.id,text:b.tabTitle||b.title,onSave:j=>{l({...n,tabTitle:j}),o({...n,tabTitle:j})},children:b.tabTitle||b.title},b.id),t.activeCardId===b.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(b.id)})]},b.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>x(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(s.CopyPlus,{className:"h-4 w-4"})})]})})}function Lt(){const t=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.isSqlRunning),r=s.useEditorStore(p=>p.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h}=s.useDashboardCardQuery(n);function x(p){const j=t.cards.find(f=>f.id===p);if(j!=null&&j.sql){r||i(!0),o(p);return}if(j!=null&&j.queryConfig){r&&i(!1),g(p),o(p);return}r||g(p),o(p)}function g(p){const j={...t,cards:t.cards.map(y=>y.id===n.id?n:y),activeCardId:p};l(j);const f=j.cards.find(y=>y.id===p);f.sql&&d(!0),c(f)}function b(){return n.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:u==null?void 0:u.records,isPending:m||h})})}):n.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Tt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:x,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(p=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:p.id,children:b()},p.id)),e.jsx(jr,{})]})}function Ze({children:t}){var T,N;s.useEditorStore(D=>D.frame);const n=s.useEditorStore(D=>D.card),a=s.useEditorStore(D=>D.isDevMode),r=s.useEditorStore(D=>D.isShowingVisual),l=s.useDashboardStore(D=>D.isVisualEditing),o=s.useEditorStore(D=>D.pythonStdOut);s.useEditorStore(D=>D.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:x,isLoading:g,isFetching:b,errorMessage:p,refetch:j}=s.useDashboardCardQuery(n);function f(){const D=JSON.stringify(x==null?void 0:x.records,null,2),v=new Blob([D],{type:"application/json"}),S=URL.createObjectURL(v),C=document.createElement("a");C.href=S,C.download=`${n.title}.json`,C.click()}function y(){const v=[Object.keys(x==null?void 0:x.records.reduce((I,B)=>({...I,...B}),{})).join(","),...((x==null?void 0:x.records)||[]).map(I=>Object.values(I).join(","))].join(`
|
|
333
|
+
`),S=new Blob([v],{type:"text/csv"}),C=URL.createObjectURL(S),O=document.createElement("a");O.href=C,O.download=`${n.title}.csv`,O.click()}function k(){const D=`Can you get the documentation for ${n.type} chart?`;u(D)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(At,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:k,children:e.jsx(da,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(ur,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:y,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:f,children:e.jsx(ya,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(x==null?void 0:x.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(Mt,{})]}),n.type==="table"&&n.sql&&!s.hasValidCardConfig(n.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((N=(T=n.preferences)==null?void 0:T.tablePrefs)==null?void 0:N.enableDevModePagination)??!1,onCheckedChange:D=>{var v;h({...n.preferences,tablePrefs:{...(v=n.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:D}}),j()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(vr,{})]}),r?e.jsx(Lt,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:o&&e.jsx(br,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":o}),children:[(x==null?void 0:x.records)&&(x==null?void 0:x.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(x==null?void 0:x.records)||[]}),p&&e.jsx(pr,{error:p})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function br(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function vr(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Ce({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function yr(){var p,j;const t=s.useEditorStore(f=>f.card.customCardPreferences),{data:n}=kt(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(f=>f.card),l=s.useEditorStore(f=>f.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(p=d==null?void 0:d.visuals)==null?void 0:p.find(f=>f.name===(t==null?void 0:t.componentName));function m(f,y){if(!t)return;const T={...(t==null?void 0:t.dataInputCardIds)||{},[f]:{cardId:y,hookRef:null}};c({...t,dataInputCardIds:T})}function h(f){var k,T;const y=(k=l==null?void 0:l.cards)==null?void 0:k.filter(N=>{var D;return((D=N==null?void 0:N.customCardPreferences)==null?void 0:D.visualType)!=="multiple"}).map(N=>({value:N.id,label:N.tabTitle||N.title}));return e.jsx("div",{className:"space-y-2",children:(T=f==null?void 0:f.dataInputs)==null?void 0:T.map((N,D)=>{var v,S;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:N}),e.jsx(Ce,{className:"col-span-6 h-8 w-full justify-between",label:"",options:y||[],value:((S=(v=t==null?void 0:t.dataInputCardIds)==null?void 0:v[D])==null?void 0:S.cardId)||"",onValueChange:C=>m(D,C)})]},D+Math.random())})})}function x(f,y,k=[],T=""){var N,D;return t?f==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((N=t==null?void 0:t.settings)==null?void 0:N[y])||T,onChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[y]:v.target.value}})}},y):f==="select"?e.jsx(Ce,{className:"h-8 w-full",label:"",options:k,value:((D=t==null?void 0:t.settings)==null?void 0:D[y])||T,onValueChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[y]:v}})}}):null:null}function g(f){const y=Object.entries((f==null?void 0:f.settings)||{});return e.jsx("div",{className:"space-y-3",children:y.map(([k,T])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:T.title}),x(T.ui,k,T.options,T.defaultValue)]},k))})}function b(f){t&&c({...t,visualType:f,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ce,{icon:e.jsx(ca,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:f=>c({...t||{url:"",componentName:""},url:f})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:b,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(Ce,{icon:e.jsx(ga,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(f=>f.type===o).map(f=>({value:f.name,label:f.name})))||[],value:t.componentName,onValueChange:f=>{console.log("changing value",f),c({...t,componentName:f})}})})]})})]}),((j=r==null?void 0:r.customCardPreferences)==null?void 0:j.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(u)})})]})]})]})}function Fe(){const[t,n]=A.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),o=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),A.useEffect(()=>{o&&n(new Array(o.length).fill(!1))},[o]);function c(u,m){var h,x;m?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):l({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...a,onClickFilter:(x=a==null?void 0:a.onClickFilter)==null?void 0:x.filter(g=>g.columnIndex!==u)}),n(g=>{const b=[...g];return b[u]=!1,b}))}function i(u,m){var x;const h=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.map(g=>g.columnIndex===u?{...g,expression:m.target.value}:g);l({...a,onClickFilter:h})}function d(u){var m,h,x,g;if(t!=null&&t[u]||(h=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(b=>b.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(b=>b.columnIndex===u))==null?void 0:g.expression,onChange:b=>i(u,b),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:o==null?void 0:o.map((u,m)=>{var h,x;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(g=>g.columnIndex===m)),onCheckedChange:g=>c(m,g)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(g=>g.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{n(g=>{const b=[...g];return b[m]=!g[m],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function Nr({idx:t}){var i;const n=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),a=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=n==null?void 0:n.chartOptions)==null?void 0:i.indexAxis,o=a==null?void 0:a.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:m}]});else{const h={...o};h.datalabels=m;const x=a==null?void 0:a.map(g=>g.idx===u?h:g);r({...n,datasetOptions:x})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(tt,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ta,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ea,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ka,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function Cr(){const t=s.useEditorStore(o=>o.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function us({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Rt(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=Cr();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:o.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:Ot(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(Ft,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function Ot(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Ft({col:t,idx:n,className:a,iconClassName:r,children:l}){const o=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,x;return(x=(h=m.card)==null?void 0:h.preferences)==null?void 0:x.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===n),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...o,datasetOptions:[...c||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const x=c==null?void 0:c.map(g=>g.idx===n?h:g);d({...o,datasetOptions:x})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(us,{className:"max-w-[100px]",title:t,children:Ot(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Nr,{idx:n})]})]})}function ks(){const t=s.useEditorStore(g=>g.selectedConnectionId),n=s.useEditorStore(g=>g.selectedDatamodelId),a=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),l=s.useEditorStore(g=>g.selectedTableName),o=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:h}=s.useEditorAside();function x(g,b="dashboard",p){var S;const j=s.fmt(g.column_name),f=s.fmt(a||""),y=s.fmt(r||""),k=s.fmt(m);let T=s.getQualifiedTableName({schemaName:y,tableName:k,connectionType:h,databaseName:f}),N=`${T}.${j}`;const D=(S=u==null?void 0:u.find(C=>C.id===n))==null?void 0:S.name;n&&n!=="none"&&(N=`${s.DATAMODEL_NAMESPCACE}.${D}.${j}`,T=`${s.DATAMODEL_NAMESPCACE}.${D}`),p!=null&&p.qualifiedFieldName&&(N=p.qualifiedFieldName),p!=null&&p.entityName&&(T=p.entityName);const v=o==null?void 0:o.find(C=>C.column===N&&C.table===k&&(C.database===f||C.database===a));if(v)d(v.id),i(v.id);else{const C=s.v4();return m==="api"&&t?(c({location:b,id:C,column:N,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,T,j)}),C):(c({id:C,location:b,column:N,title:g.column_name,dataType:g.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,T,j)}),C)}}return{assignFilter:x}}function Ge(){const t=s.useDashboardStore(i=>i.dashboard.filters),n=s.useEditorStore(i=>i.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=ks();function o(i){const d=l(i,"frame");a({...n,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(Sr,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function Sr({columns:t,onSelect:n}){var c;const[a,r]=Ee.useState(!1),[l,o]=Ee.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const u=d===l?"":d;o(u),r(!1),u&&n(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function wr({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:n=>n.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Rt,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ge,{})]})]})]})})}function Dr({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ge,{})]})]})]})})}function Bt(){const t=s.useEditorStore(i=>i.card.type),n=s.useEditorStore(i=>i.isDevMode),a=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(m=a==null?void 0:a.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function o(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?o():c()})}const Tr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},kr={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Er(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Ir(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Bt,{}),e.jsx(Fe,{}),e.jsx(Ge,{})]})]})}function Ir(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(Tr,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(kr,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function Ar({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(c,i,d){const u=[...t];u[c]={...u[c],[i]:d},n(u)}function l(c){const i=[...t];i.splice(c,1),n(i)}function o(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:o,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(i,"start",d.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:d=>r(i,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(i,"color",d.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function Mr(){var m,h,x,g,b;const t=s.useEditorStore(p=>p.card.preferences),n=s.useEditorStore(p=>p.actions.setCardPreferences),a=s.useEditorStore(p=>p.card),r=s.isExplorerCard(a),l=s.useEditorStore(p=>p.actions.setNumberFormat);s.useEditorStore(p=>{var j,f;return(f=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.decimalPlaces});const o=s.useEditorStore(p=>{var j,f;return(f=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.locale}),c=s.useEditorStore(p=>{var j,f;return(f=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.currency});s.useEditorStore(p=>p.actions.setFilterOnClickField);const i=s.useEditorStore(p=>{var j,f;return(f=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.colorRanges})||[],d=s.useEditorStore(p=>p.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(p=>p.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:p=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:p}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:p=>{var j,f,y;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",p,((y=t==null?void 0:t.formatNumber)==null?void 0:y.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(p=>e.jsx(s.SelectItem,{value:p.locale,children:p.locale},p.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:p=>{var j,f,y;console.log("currency",p),l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,p==="none"?"":p,((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((g=(x=t==null?void 0:t.formatNumber)==null?void 0:x.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:p=>{var j,f,y;return l(Number(p),((j=t==null?void 0:t.formatNumber)==null?void 0:j.currency)||"",((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:p=>{var j,f,y;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.locale)||"",p.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(Ar,{colorRanges:i,setColorRanges:d})]})]})}function Lr(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(Mr,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function js({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Rr=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],Or=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],Fr=Or.map(t=>({label:t,value:t}));function Br(){var d,u,m,h,x,g,b,p,j,f,y,k,T,N,D,v,S,C;const t=s.useEditorStore(O=>O.card),n=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=A.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(O=>({label:O,value:O}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(js,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(js,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Ce,{className:"h-9",options:i,onValueChange:O=>{console.log("value",O),l({...t.preferences,mapVisualOptions:{topoJsonUrl:O}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:O=>{r(O.target.value)},onBlur:()=>{var O;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(O=t.preferences)==null?void 0:O.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(Ce,{className:"h-9",options:c,value:((g=(x=t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:O=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,objectKey:O}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(Ce,{className:"h-9",options:Rr,value:((p=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:p.projection)||"",label:"Projection",onValueChange:O=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projection:O}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(Ce,{className:"h-9",options:Fr,value:((f=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:f.colorScale)||"",label:"Select Color Scale",onValueChange:O=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,colorScale:O}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(js,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((k=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:k.projectionScale)||1,onChange:O=>{var I;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projectionScale:Number(O.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((D=(N=(T=t.preferences)==null?void 0:T.mapVisualOptions)==null?void 0:N.projectionOffset)==null?void 0:D[0])||0,onChange:O=>{var I,B,E,w;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projectionOffset:[Number(O.target.value),((w=(E=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:w[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((C=(S=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:S.projectionOffset)==null?void 0:C[1])||0,onChange:O=>{var I,B,E,w;l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,projectionOffset:[((w=(E=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:w[0])||0,Number(O.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Fe,{})]})}function Pr(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:n}=s.useEditorStore(l=>l.actions);function a(l){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function es({cardType:t,docContent:n,suffix:a="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${a}`}),e.jsx(s.AccordionContent,{children:n||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Pr,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ge,{})]})]})]})})}function zr(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(Ce,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{n(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[a(),e.jsx(Rt,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ge,{})]})]})]})})}function Vr({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ge,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function Pt({color:t,onColorChange:n,onClose:a}){const[r,l]=A.useState(0),[o,c]=A.useState(100),[i,d]=A.useState(50),[u,m]=A.useState(t);A.useEffect(()=>{const j=Gs(t);if(j){const f=Ys(j.r,j.g,j.b);l(f.h),c(f.s),d(f.l),m(t)}},[t]);const h=j=>{l(j),g(j,o,i)},x=j=>{const f=j.currentTarget.getBoundingClientRect(),y=Math.max(0,Math.min(1,(j.clientX-f.left)/f.width)),k=Math.max(0,Math.min(1,(j.clientY-f.top)/f.height)),T=y*100,N=(1-k)*100;c(T),d(N),g(r,T,N)},g=(j,f,y)=>{const k=Ur(j,f,y),T=_r(k.r,k.g,k.b);m(T)},b=j=>{if(m(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const f=Gs(j);if(f){const y=Ys(f.r,f.g,f.b);l(y.h),c(y.s),d(y.l)}}},p=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(n(u),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:x,onMouseMove:j=>{j.buttons===1&&x(j)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>h(Number(j.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:u,onChange:j=>b(j.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:p,children:"OK"})]})]})}function Gs(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function _r(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function Ys(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let o=0,c=0;const i=(r+l)/2;if(r!==l){const d=r-l;switch(c=i>.5?d/(2-r-l):d/(r+l),r){case t:o=((n-a)/d+(n<a?6:0))/6;break;case n:o=((a-t)/d+2)/6;break;case a:o=((t-n)/d+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function Ur(t,n,a){t/=360,n/=100,a/=100;let r,l,o;if(n===0)r=l=o=a;else{const c=(u,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(m-u)*6*h:h<.5?m:h<.6666666666666666?u+(m-u)*(.6666666666666666-h)*6:u),i=a<.5?a*(1+n):a+n-a*n,d=2*a-i;r=c(d,i,t+1/3),l=c(d,i,t),o=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const Gr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function zt(){var k,T,N,D,v,S,C,O,I,B;const t=s.useEditorStore(E=>E.card),n=s.useEditorStore(E=>{var w;return(w=E.card)==null?void 0:w.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=A.useState({}),[i,d]=A.useState(null),[u,m]=A.useState(null),h=A.useMemo(()=>{var F,R,L,P,Y,J,V;if(!(l!=null&&l.records)||l.records.length===0)return[];const E=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",w=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",M=((F=t==null?void 0:t.config)==null?void 0:F.pivotByColumns)&&t.config.pivotByColumns.length>0;if((E||w)&&M){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const K=new Set;return l.pivotSchema.forEach(q=>{q.alias&&K.add(q.alias)}),Array.from(K)}if(l.records.length>0){const K=l.records[0],q=Object.keys(K),Z=new Set;(R=t==null?void 0:t.config)!=null&&R.groupByColumns&&t.config.groupByColumns.forEach(_=>{Z.add(_.label||_.name),Z.add(_.alias||_.name)});const $=new Set;return(L=t==null?void 0:t.config)!=null&&L.metricColumns&&t.config.metricColumns.forEach(_=>{const G=_.alias||_.name;$.add(G),$.add(`${G}_count`),$.add(`${G}_sum`),$.add(`${G}_avg`),$.add(`${G}_min`),$.add(`${G}_max`);const se=_.entityName||_.qualifiedEntityName;se&&($.add(`${se}_${G}`),$.add(`${se}_${G}_count`))}),q.filter(_=>!Z.has(_)&&!$.has(_))}}if((w||E)&&!M&&((Y=(P=t==null?void 0:t.config)==null?void 0:P.metricColumns)!=null&&Y.length))return t.config.metricColumns.map(K=>K.alias||K.label||K.name);if((V=(J=t==null?void 0:t.config)==null?void 0:J.groupByColumns)!=null&&V.length){const K=t.config.groupByColumns[0],q=K.label||K.name,Z=new Set;return l.records.forEach($=>{const X=$[q];X!=null&&Z.add(String(X))}),Array.from(Z)}return[]},[l,(k=t==null?void 0:t.config)==null?void 0:k.groupByColumns,(T=t==null?void 0:t.config)==null?void 0:T.pivotByColumns,(N=t==null?void 0:t.config)==null?void 0:N.metricColumns,t==null?void 0:t.type]),x=A.useMemo(()=>s.getDefaultChartColors(),[]);A.useEffect(()=>{const E={};h.forEach((w,M)=>{E[w]=s.getColorForValue(w,M,n==null?void 0:n.colorConfig)}),c(E)},[h,n==null?void 0:n.colorConfig,x]);const g=(E,w)=>{const M={...o,[E]:w};c(M);const F={...n||{},colorConfig:{segments:M}};a(F);const R={...t,preferences:F};r(R)},b=(E,w)=>{var Y;const M=x[w%x.length],{[E]:F,...R}=((Y=n==null?void 0:n.colorConfig)==null?void 0:Y.segments)||{},L={...n||{},colorConfig:{segments:R}};a(L);const P={...t,preferences:L};r(P),c(J=>({...J,[E]:M}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((v=(D=t==null?void 0:t.config)==null?void 0:D.groupByColumns)==null?void 0:v.length)||((C=(S=t==null?void 0:t.config)==null?void 0:S.pivotByColumns)==null?void 0:C.length):(I=(O=t==null?void 0:t.config)==null?void 0:O.groupByColumns)==null?void 0:I.length)||["table","kpi","text","custom"].includes(t.type))return null;const f=()=>{const E={...n||{},colorConfig:{segments:{}}};a(E);const w={...t,preferences:E};r(w);const M={};h.forEach((F,R)=>{M[F]=s.getColorForValue(F,R,void 0)}),c(M)},y=Object.keys(((B=n==null?void 0:n.colorConfig)==null?void 0:B.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:y&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:f,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((E,w)=>{const M=s.isDefaultColor(o[E],w),F=!M;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===E,onOpenChange:R=>d(R?E:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[E]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:x.slice(0,10).map((R,L)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[E]===R?"border-gray-900":"border-transparent"),style:{backgroundColor:R},onClick:()=>{g(E,R),d(null)},children:[L===w%x.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:R})]},`default-${L}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Gr.map((R,L)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[E]===R?"border-2 border-gray-900":R==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:R},onClick:()=>{g(E,R),d(null)},children:e.jsx("span",{className:"sr-only",children:R})},`preset-${L}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{m({value:E,color:o[E]}),d(null)},children:"Custom color"}),!M&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(E,w),d(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:E}),F&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},E)})}),u&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Pt,{color:u.color,onColorChange:E=>{g(u.value,E),m(null)},onClose:()=>m(null)})})]})]})})]})}function we({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[o,c]=A.useState(t??""),[i,d]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const u=()=>{n(o),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?u():h.key==="Escape"&&m()},"aria-label":a||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Yr=["auto","number","currency","percent","scientific","date"],$r=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"GBP",label:"GBP - British Pound"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"DKK",label:"DKK - Danish Krone"},{value:"KRW",label:"KRW - South Korean Won"},{value:"INR",label:"INR - Indian Rupee"},{value:"RUB",label:"RUB - Russian Ruble"},{value:"BRL",label:"BRL - Brazilian Real"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"TRY",label:"TRY - Turkish Lira"},{value:"ZAR",label:"ZAR - South African Rand"},{value:"SAR",label:"SAR - Saudi Riyal"},{value:"AED",label:"AED - UAE Dirham"},{value:"ARS",label:"ARS - Argentine Peso"},{value:"CLP",label:"CLP - Chilean Peso"},{value:"COP",label:"COP - Colombian Peso"},{value:"THB",label:"THB - Thai Baht"},{value:"IDR",label:"IDR - Indonesian Rupiah"},{value:"MYR",label:"MYR - Malaysian Ringgit"},{value:"PHP",label:"PHP - Philippine Peso"},{value:"PLN",label:"PLN - Polish Zloty"},{value:"NGN",label:"NGN - Nigerian Naira"},{value:"KES",label:"KES - Kenyan Shilling"},{value:"GHS",label:"GHS - Ghanaian Cedi"},{value:"ZMW",label:"ZMW - Zambian Kwacha"},{value:"ZWL",label:"ZWL - Zimbabwean Dollar"},{value:"EGP",label:"EGP - Egyptian Pound"},{value:"MAD",label:"MAD - Moroccan Dirham"},{value:"UAH",label:"UAH - Ukrainian Hryvnia"},{value:"HUF",label:"HUF - Hungarian Forint"},{value:"CZK",label:"CZK - Czech Koruna"},{value:"RON",label:"RON - Romanian Leu"},{value:"PKR",label:"PKR - Pakistani Rupee"},{value:"BDT",label:"BDT - Bangladeshi Taka"},{value:"VND",label:"VND - Vietnamese Dong"},{value:"TWD",label:"TWD - New Taiwan Dollar"},{value:"ILS",label:"ILS - Israeli New Shekel"}],qr=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],Hr=t=>t.charAt(0).toUpperCase()+t.slice(1);function Es({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,d)=>{n({...t,[i]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Yr.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":Hr(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:$r.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:qr.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function $s({axis:t,label:n,type:a,config:r,onChange:l}){var h,x,g,b,p,j,f,y,k,T,N,D;const o=(v,S)=>{l({...r,[v]:S})},c=(v,S)=>{var C,O;l({...r,name:{enabled:v==="enabled"?S:((C=r==null?void 0:r.name)==null?void 0:C.enabled)??!1,text:v==="text"?S:(O=r==null?void 0:r.name)==null?void 0:O.text}})},i=(v,S)=>{var C,O;l({...r,labels:{enabled:v==="enabled"?S:((C=r==null?void 0:r.labels)==null?void 0:C.enabled)??!0,rotation:v==="rotation"?S:(O=r==null?void 0:r.labels)==null?void 0:O.rotation}})},d=(v,S)=>{l({...r,scale:{...r==null?void 0:r.scale,[v]:S===""?"auto":Number(S)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:v=>o("enabled",v),onClick:v=>v.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:v=>c("enabled",v)})]}),((x=r==null?void 0:r.name)==null?void 0:x.enabled)&&e.jsx(we,{placeholder:`${n} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:v=>c("text",v),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:v=>o("position",v),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":s.titleCase(v)},v))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((b=r==null?void 0:r.labels)==null?void 0:b.enabled)!==!1,onCheckedChange:v=>i("enabled",v)})]}),((p=r==null?void 0:r.labels)==null?void 0:p.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((j=r==null?void 0:r.labels)==null?void 0:j.rotation)||"auto"),onValueChange:v=>i("rotation",v==="auto"?"auto":Number(v)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":`${v}°`},v))})]})]})]}),a==="value"&&e.jsx(Es,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:v=>l({...r,formatOptions:v}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.min)==="auto"||((y=r==null?void 0:r.scale)==null?void 0:y.min)===void 0?"":String(r.scale.min),onSave:v=>d("min",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((k=r==null?void 0:r.scale)==null?void 0:k.max)==="auto"||((T=r==null?void 0:r.scale)==null?void 0:T.max)===void 0?"":String(r.scale.max),onSave:v=>d("max",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((N=r==null?void 0:r.scale)==null?void 0:N.stepSize)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.stepSize)===void 0?"":String(r.scale.stepSize),onSave:v=>d("stepSize",v),className:""})})]})]})]})]})]})}function Vt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const u={...n||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};a(u);const m={...t,preferences:u};r(m)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(st,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx($s,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx($s,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function _t(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var m,h,x,g;return(g=(x=(h=(m=u.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:x.plugins)==null?void 0:g.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(u,m)=>{const h={...n,[u]:m};a(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??o,onCheckedChange:u=>c("display",u)})]}),((n==null?void 0:n.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||r,onValueChange:u=>c("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||l,onValueChange:u=>c("align",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]})]})]})})]})}function Ut(){var S,C,O,I,B,E,w,M,F;const t=s.useEditorStore(R=>R.card),n=s.useEditorStore(R=>{var L,P;return(P=(L=R.card)==null?void 0:L.preferences)==null?void 0:P.dataLabelsConfig}),a=s.useEditorStore(R=>{var L;return(L=R.card)==null?void 0:L.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((S=a==null?void 0:a.chartOptions)==null?void 0:S.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!i,u=(O=(C=a==null?void 0:a.chartOptions)==null?void 0:C.plugins)==null?void 0:O.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),h=(n==null?void 0:n.enabled)!==void 0?n.enabled:m,x=(R,L)=>{const P={...n,[R]:L},Y={...t.preferences||{},dataLabelsConfig:P};r(Y);const J={...t,preferences:Y};l(J)},g=(R,L)=>{const P={...n,font:{...n==null?void 0:n.font,[R]:L}},Y={...t.preferences||{},dataLabelsConfig:P};r(Y);const J={...t,preferences:Y};l(J)},b=(R,L)=>{const P={...n,formatOptions:{...n==null?void 0:n.formatOptions,[R]:L}},Y={...t.preferences||{},dataLabelsConfig:P};r(Y);const J={...t,preferences:Y};l(J)},j=(()=>{const R=t.type;return R==="stackedBar"||R==="stackedLine"||R==="pie"||R==="doughnut"?"center":o?"right":"top"})();let f=[];c||i?f=["center"]:f=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(L=>L!==j),"custom"];const y=()=>s.titleCase(j),k=["center","start","end"],T=["center","start","end","top","bottom"],N=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],D=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],v=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:R=>x("enabled",R)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:R=>x("position",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:R==="auto"?y():R==="custom"?"Custom (Advanced)":s.titleCase(R)},R))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:R=>x("showTotal",R)})]}),(n==null?void 0:n.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(n==null?void 0:n.anchor)||"center",onValueChange:R=>x("anchor",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:k.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:s.titleCase(R)},R))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((n==null?void 0:n.align)||"center"),onValueChange:R=>x("align",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:T.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:s.titleCase(R)},R))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(d?"auto":"none"),onValueChange:R=>x("format",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:R==="auto"&&d?"Auto (Use Axis)":R==="none"?"None (Raw Value)":s.titleCase(R)},R))})]})]}),(n==null?void 0:n.format)&&!["auto","none"].includes(n.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(n.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"0",value:String(((I=n==null?void 0:n.formatOptions)==null?void 0:I.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:R=>b("decimalPlaces",Number(R)),className:""})})]}),n.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((B=n==null?void 0:n.formatOptions)==null?void 0:B.currency)||"USD",onValueChange:R=>b("currency",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:D.map(R=>e.jsx(s.SelectItem,{value:R.value,className:"text-xs",children:R.label},R.value))})]})]}),["number","currency"].includes(n.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((E=n==null?void 0:n.formatOptions)==null?void 0:E.useSuffix)??!1,onCheckedChange:R=>b("useSuffix",R)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((w=n==null?void 0:n.formatOptions)==null?void 0:w.locale)||"en-US",onValueChange:R=>b("locale",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(R=>e.jsx(s.SelectItem,{value:R.value,className:"text-xs",children:R.label},R.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"12",value:String(((M=n==null?void 0:n.font)==null?void 0:M.size)||12),onSave:R=>g("size",Number(R)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((F=n==null?void 0:n.font)==null?void 0:F.weight)||"normal",onValueChange:R=>g("weight",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(n==null?void 0:n.color)==="auto"||!(n!=null&&n.color)?"auto":"custom",onValueChange:R=>{R==="auto"&&x("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"0",value:String((n==null?void 0:n.rotation)||0),onSave:R=>x("rotation",Number(R)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Wr(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[e.jsx(zt,{}),e.jsx(Vt,{}),e.jsx(_t,{}),e.jsx(Ut,{})]})]})}const Kr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Qr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Jr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Xr(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=o=>r.includes(a)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(Wr,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(zr,{}));case"tornado":case"pyramid":return l(e.jsx(es,{docContent:Kr,cardType:a}));case"kpi":return e.jsx(Lr,{});case"line":case"bar":return l(e.jsx(wr,{cardType:a}));case"range":return l(e.jsx(es,{docContent:Qr,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(es,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(Dr,{cardType:a}));case"table":return e.jsx(Vr,{cardType:a});case"text":return e.jsx(es,{docContent:Jr,cardType:a,suffix:"Visual"});case"map":return e.jsx(Br,{});case"custom":return e.jsx(yr,{});default:return l(e.jsx(Er,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Gt({label:t,column:n,functions:a,onFunctionChange:r}){let l=a[0];"aggregate"in n?l=a.find(c=>c.value===n.aggregate)||a[0]:"granularity"in n&&(l=a.find(c=>c.value===n.granularity)||a[0]);function o(c){r(c)}return e.jsx(Ce,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:a,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const Zr=[{label:"Sum",value:"SUM",logo:e.jsx(et,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(De,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(Na,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(la,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function el({column:t}){const{updateMetricColumnOld:n}=s.useEditorActions();let a=Zr;s.isTextDataType(t.type)&&(a=a.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(a=a.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:We(t.name,l)};n(t.id,o)}return e.jsx(Gt,{column:t,functions:a,onFunctionChange:l=>r(l),label:"Aggregation"})}const sl=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function tl({column:t}){const{updateGroupByColumnOld:n}=s.useEditorActions();function a(r){const l={...t,granularity:r,label:Ue(t.name,r)};n(t.id,l)}return e.jsx(Gt,{column:t,functions:sl,onFunctionChange:r=>a(r),label:"Granularity"})}function al({col:t,onChange:n,droppableId:a}){const{columns:r}=s.useDataColumns(),l=A.useMemo(()=>{let i=[];(a===Ie||a===Ae||a===Me)&&(i=r);const d=i==null?void 0:i.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,a,t.name]),o=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(u=>{var m;return u.column_name===((m=i[0])==null?void 0:m.id)});d&&n(d)}return l!=null&&l.length?e.jsx(s.ComboBox2,{multiple:!1,options:l,selectedOptions:o,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function Yt({column:t}){const n=s.useEditorStore(d=>d.card.type),a=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(a==null?void 0:a.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Ft,{idx:o,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Bt,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&i()]})}function nl({column:t,type:n,onRemoveColumn:a,droppableId:r}){const[l,o]=A.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:m,setNodeRef:h,transform:x,transition:g,isDragging:b}=s.useSortable({id:t.id,data:{type:n}}),p=x?{opacity:b?.5:void 0,transform:s.CSS.Translate.toString(x),transition:g}:void 0,j=s.isTextDataType(t.type);function f(D){const v=s.isNumberDataType(D.data_type),S=s.isTextDataType(D.data_type),C=s.isDateDataType(D.data_type),O=v?"number":S?"string":C?"date":"string";if(r===Ie){if(S){const I={id:t.id,name:D.column_name,type:O,role:"groupby"};c(t.id,I)}if(C){const I={id:t.id,name:D.column_name,type:O,role:"groupby",label:Ue(D.column_name,"month"),granularity:"month"};c(t.id,I)}}if(r===Me){if(S){const I={id:t.id,name:D.column_name,type:O,role:"groupby"};d(t.id,I)}if(C){const I={id:t.id,name:D.column_name,type:O,label:Ue(D.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,I)}}if(r===Ae){const I={id:t.id,name:D.column_name,type:O,role:"metric",label:We(D.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};i(t.id,I)}}function y(){if(r===Ae)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(Yt,{column:t})})}function k(){const D=s.isDateDataType(t.type);if(r===Ae)return e.jsx(el,{column:t});if((r===Ie||r===Me)&&D)return e.jsx(tl,{column:t})}function T(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ie||r===Me)&&j}),children:e.jsx(al,{col:t,onChange:f,droppableId:r})})}function N(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>o(!l),children:l?e.jsx(Ga,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Xs,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...u,ref:h,style:p,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[N(),k(),T()]}),l&&y()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>a(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function bs({id:t,label:n,columns:a,previewColumns:r,sortableType:l,onRemoveColumn:o}){var p,j;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),u=s.useDndStore(f=>f.activeId),m=s.useEditorStore(f=>{var y;return(y=f.card)==null?void 0:y.type}),h=i||((j=(p=d==null?void 0:d.data)==null?void 0:p.current)==null?void 0:j.type)===l,x=u?r:a,g=l===rs?"Rows":l===ls?"Pivot Columns":"Columns";function b(){if(!x||x.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(f=>f.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:n}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),b(),e.jsx("div",{className:"space-y-2",children:x==null?void 0:x.map(f=>f.id===yt.id?e.jsx(rl,{},f.id):e.jsx(nl,{droppableId:t,type:l,column:f,onRemoveColumn:o},f.id))})]})})}function rl(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function $t({children:t,id:n,type:a}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:d}=s.useSortable({id:n,data:{type:a}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...l,...r,ref:o,style:u,children:t})}function ll(){const t=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.orderBy})||[],n=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.groupByColumns})||[],a=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...n,...a];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(ia,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(ra,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(oa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(na,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(f=>!t.some(y=>y.columnId===f.id)).map(f=>({id:f.id,value:f.label||f.name}));function x(f,y){const k=g(f);return k?k.role==="metric"?y==="asc"?u:m:y==="asc"?i:d:null}function g(f){return c.find(y=>y.id===f)}function b(f){const y=t.find(k=>k.columnId===f);if(y){const k={...y,direction:y.direction==="asc"?"desc":"asc"};o(k)}}const p=f=>{r({columnId:f.id,direction:"asc"})};function j(f){const y=t.find(k=>k.columnId===f);y&&l(y)}return e.jsx(s.SortableContext,{items:t.map(f=>$e(f.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:f=>p(f[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(f=>{var y,k;return e.jsx($t,{id:$e(f.columnId),type:Ts,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Xs,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(us,{className:"w-[175px] text-sm",children:((y=g(f.columnId))==null?void 0:y.label)||((k=g(f.columnId))==null?void 0:k.name)})]}),e.jsx("button",{title:f.direction==="asc"?"Ascending":"Descending",onClick:()=>b(f.columnId),className:"rounded-sm p-0",children:x(f.columnId,f.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>j(f.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},f.columnId)},$e(f.columnId))})]})})}function ol(){const t=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.groupByColumns)||[]}),n=s.useEditorStore(j=>j.card.type),a=s.useDndStore(j=>j.previewGroupByColumns),r=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.metricColumns)||[]}),l=s.useDndStore(j=>j.previewMetricColumns),o=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.pivotColumns)||[]}),c=s.useDndStore(j=>j.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function m(j){i(j)}function h(j){d(j)}function x(j){u(j)}let g="Group By",b="Metrics",p="Stack By";return n==="table"&&(g="Rows",b="Metrics",p="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(It,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(bs,{onRemoveColumn:m,sortableType:rs,id:Ie,label:g,columns:t,previewColumns:a}),e.jsx(bs,{onRemoveColumn:x,sortableType:ls,id:Me,label:p,columns:o,previewColumns:c}),e.jsx(bs,{onRemoveColumn:h,sortableType:Ns,id:Ae,label:b,columns:r,previewColumns:l}),e.jsx(ll,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Is({children:t,column:n,id:a,sortableType:r,className:l}){const[o,c]=A.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(h=>{var x,g;return(g=(x=h.card.queryConfig)==null?void 0:x.filters)==null?void 0:g.some(b=>b.filterColumnName===n.name)});function m(h){i(h)}return e.jsx($t,{id:a,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":o}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:n.name}),u&&e.jsx("button",{onClick:()=>d(n),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>m(n),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!o&&"rounded-b-md",o&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",l),children:t})]})]})})}function il({column:t,sortableType:n}){const a=s.useDashboardStore(k=>k.themeStyle),r=s.useEditorStore(k=>{var T,N;return(N=(T=k.card)==null?void 0:T.queryConfig)==null?void 0:N.filters}),l=s.useEditorStore(k=>{var T,N;return(N=(T=k.card.queryConfig)==null?void 0:T.filterColumns)==null?void 0:N.find(D=>D.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=A.useMemo(()=>{var k;return(k=r==null?void 0:r.find(T=>T.filterColumnName===t.name))==null?void 0:k.filterValue},[r,t.name]),u=A.useMemo(()=>Array.isArray(d)?d.map(k=>({id:k,value:k})):[],[d]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:x,isLoading:g,isFetching:b,isError:p}=s.useFilterQuery(h),j=A.useMemo(()=>{var T;return h.column?(T=x==null?void 0:x.records)==null?void 0:T.map(N=>{let D=h.column.split(".").slice(-1)[0].replace(/"/g,"");return N[D]===void 0&&(D=D.toLowerCase()),{id:N[D],value:N[D]}}):[]},[x,h.column]);function f(k){const T=k.map(N=>N.id);m(t.name,T)}function y(){return g||b?e.jsx(s.Skeleton,{style:{borderRadius:a==null?void 0:a.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):p?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(cl,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:j,onChange:f,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Is,{className:"w-60",id:t.id,sortableType:n,column:t,children:y()})}function cl({columnName:t}){const{setEditorFilterMode:n}=s.useEditorActions(),a=s.useEditorStore(l=>{var o,c;return(c=(o=l.card.queryConfig)==null?void 0:o.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(a==null?void 0:a.mode)==="exclude"?n(t,"include"):n(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((a==null?void 0:a.mode)==="exclude"?"exclude":"include")})}function dl({open:t,setOpen:n,dateRange:a,setDateRange:r,containerClassName:l,inputClassName:o,title:c,onApply:i,onClear:d}){const u=s.useDashboardStore(m=>m.themeStyle);return e.jsx("div",{className:s.cn("grid gap-2",l),children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{style:{borderRadius:u==null?void 0:u.controlInputRadius},asChild:!0,children:e.jsxs(s.Button,{size:"sm",id:"date",variant:"outline",className:s.cn("h-9 w-full justify-start rounded-sm text-left font-normal",!a&&"text-muted-foreground",o),children:[e.jsx(s.Calendar,{className:"mr-2 h-4 w-4"}),a!=null&&a.from?a.to?e.jsxs(e.Fragment,{children:[s.format(a.from,"LLL dd, y")," -"," ",s.format(a.to,"LLL dd, y")]}):s.format(a.from,"LLL dd, y"):e.jsx("span",{children:"Pick a date"})]})}),e.jsxs(s.PopoverContent,{style:{borderRadius:u==null?void 0:u.controlInputRadius},className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsx(s.Label,{children:c})}),e.jsx(s.Calendar$1,{initialFocus:!0,mode:"range",defaultMonth:a==null?void 0:a.from,selected:a,onSelect:r,numberOfMonths:2}),e.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3",children:[e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:m=>{m.stopPropagation(),i(a),n(!1)},children:"Apply"}),e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:d,children:"Clear"})]})]})]})})}function ul({column:t,sortableType:n}){const[a,r]=A.useState(!1),{selectedConnectionId:l,selectedDatabaseName:o,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:l,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:m,data:h}=s.useFilterQuery(i),x=h==null?void 0:h.records,{dateRange:g,setDateRange:b,initialDateRange:p}=s.useDateRangeFromRecords(x),{updateEditorFilterValue:j}=s.useEditorActions();function f(T){var D,v;const N={gte:(D=T==null?void 0:T.from)==null?void 0:D.toISOString(),lte:(v=T==null?void 0:T.to)==null?void 0:v.toISOString()};j(t.name,N)}function y(){j(t.name,null,!0),b(p)}function k(){return d||u?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):m?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):x?e.jsx(dl,{title:i.title,open:a,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:b,onApply:f,onClear:y}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Is,{className:"w-72",id:t.id,sortableType:n,column:t,children:k()})}function ml({id:t,label:n,columns:a,previewColumns:r,sortableType:l}){var b,p;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(j=>j.activeId),u={},m=c||((p=(b=i==null?void 0:i.data)==null?void 0:b.current)==null?void 0:p.type)===l;function h(){if(!g||g.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function x(j){const f=s.isDateDataType(j.type);return j.id===yt.id?e.jsx(Is,{id:j.id,sortableType:l,column:j,children:e.jsx(hl,{})},j.id):f?e.jsx(ul,{droppableId:t,sortableType:l,column:j},j.id):e.jsx(il,{droppableId:t,sortableType:l,column:j},j.id)}const g=d?r:a;return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(j=>j.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",m&&"border border-muted-foreground/20"),ref:o,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:n}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(j=>x(j))})]})})}function hl(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function xl(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),n=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:a}=s.useEditorActions();function r(l){a(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(ml,{onRemoveColumn:r,sortableType:Ss,id:Cs,label:"Filters",columns:t,previewColumns:n})})}function pl(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.showAIDialog),{setShowAIDialog:a}=s.useEditorActions(),{data:r,errorMessage:l,errorSql:o}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(cs,{}),!n&&e.jsxs(s.Button,{onClick:()=>a(!0),variant:"secondary",size:"sm",children:[e.jsx(Ma,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(wt,{sql:r==null?void 0:r.sql,error:l,errorSql:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(jt,{}),e.jsx(gt,{variant:"default"})]})]})}function fl(){const t=A.useRef(null),n=A.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);A.useEffect(()=>{var i,d,u,m;r?((i=t.current)==null||i.resize(0),(d=n.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(m=n.current)==null||m.resize(25))},[r]);function o(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(nr,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Xr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Ze,{})})]}):e.jsx(Ze,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:a?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:n,defaultSize:25,maxSize:30,children:e.jsx(ol,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(pl,{}),e.jsx(xl,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Ze,{})})]})})]}):e.jsx(Ze,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function gl(t){s.useAIInteractionStore(z=>z.currentAIContext);const[n,a]=A.useState(""),[r,l]=A.useState(null),{authToken:o,tokenProps:c}=s.useSemaphorContext(),i=s.useEditorStore(z=>{var ee;return(ee=z==null?void 0:z.card)==null?void 0:ee.sql}),d=s.useEditorStore(z=>z.isDevMode),u=s.useEditorStore(z=>{var ee;return(ee=z==null?void 0:z.card)==null?void 0:ee.python}),{setCardPython:m,setCardSql:h,setRunSql:x,switchCardType:g,setQueryConfig:b}=s.useEditorActions(),p=s.useEditorStore(z=>z.currentAssitantScope)||[],j=s.useEditorStore(z=>z.userInputForAI),f=s.useEditorStore(z=>z.triggerAIRun),y=s.useEditorStore(z=>z.card),k=s.useEditorStore(z=>z.selectedDatabaseName),T=s.useEditorStore(z=>z.selectedTableName),N=s.useEditorStore(z=>z.selectedConnectionId),D=s.useEditorStore(z=>z.selectedSchemaName),v=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:S,refetch:C,data:O}=s.useDashboardCardQuery(y),{setTriggerAIRun:I,setCurrentAssitantScope:B,setCardConfig:E}=s.useEditorActions(),{selectedDatamodelName:w,connectionType:M,selectedDatamodelId:F}=s.useEditorAside(),{messages:R,setMessages:L,regenerate:P,error:Y,sendMessage:J,status:V,addToolResult:K,stop:q,clearError:Z}=s.useChat({transport:new s.DefaultChatTransport({api:`${c.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const z=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:z.currentAIContext,reasoningEffort:z.reasoningEffort,showReasoning:z.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:z,body:ee})=>({body:{...ee,messages:s.cleanupIncompleteMessages(z)}})}),onError:z=>{console.log("on error",z)},onToolCall:$,onFinish(){a("")}});A.useEffect(()=>{f&&j&&(J({role:"user",parts:[{type:"text",text:j}]}),I(!1))},[f,j,J,I]);async function $({toolCall:z}){var ee,ne,le,de,xe,pe,Q,U,H,te,oe,ae,je,me,Qe,Je;if(["createChartFromSql","createForecast"].includes(z.toolName)){const Ye=((ee=z.input)==null?void 0:ee.sql)??((ne=z.args)==null?void 0:ne.sql),Te=((le=z.input)==null?void 0:le.python)??((de=z.args)==null?void 0:de.python),ue=((xe=z.input)==null?void 0:xe.chartType)??((pe=z.args)==null?void 0:pe.chartType);g(ue),h(Ye),m(Te),x(!0),K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(z.toolName==="getUserSql"){if(!i){K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",message:"No SQL found"}});return}K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",sql:i,python:u||""}})}else if(z.toolName==="generateQueryConfig"){a("Generating query config...");const Ye=((Q=z.input)==null?void 0:Q.chartType)??((U=z.args)==null?void 0:U.chartType),Te=((H=z.input)==null?void 0:H.queryConfig)??((te=z.args)==null?void 0:te.queryConfig);((oe=z.input)==null?void 0:oe.cardConfig)??((ae=z.args)==null||ae.cardConfig),g(Ye),E(Te),h(void 0),m(void 0);const ue=await C();if((je=ue==null?void 0:ue.data)!=null&&je.error){K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",queryConfig:Te,message:(me=ue==null?void 0:ue.data)==null?void 0:me.error.message}});return}if((Qe=ue==null?void 0:ue.data)!=null&&Qe.records){K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:Te,message:"The data has been visualized"}});return}K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:Te,message:"The data has been visualized",records:(Je=ue==null?void 0:ue.data)==null?void 0:Je.records}})}else a("Analyzing...")}function X(z){const ee=s.removeFromScopeArray(p,z);_(ee)}function _(z){const ee=s.sanitizeAIScope(z);B(ee),L(ne=>[...ne,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(ee)}`}]}])}function G(){const z={databaseName:k||"",schemaName:D||"",tableName:T||"",datamodelId:F||"",datamodelName:s.resolveDatamodelName(w),connectionId:N||"",connectionType:M||""},ee=s.dedup([...p,z]);_(ee)}function se(){const z={databaseName:k||"",schemaName:D||"",tableName:T||"",datamodelName:s.resolveDatamodelName(w),connectionId:N||"",connectionType:M||"",datamodelId:F||""};if(!s.isInAiScopeArray([...v||[],...p],z)||p.length===0){const ne=s.dedup([...v||[],...p,z]).filter(le=>le.connectionId===z.connectionId);_(ne)}}const re=!["ready","error"].includes(V),he=s.getErrorMessage(Y);return{messages:R,setMessages:L,sendMessage:J,regenerate:P,isLoading:re,handleSetAIScope:se,handleAddCurrentTableToScope:G,removeFromCurrentSelections:X,currentAssitantScope:p,setCurrentAssitantScope:B,stop:q,status:V,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:he,clearError:Z}}const jl=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function qs(){const t=A.useRef(null),[n,a]=A.useState(!1),[r,l]=A.useState(s.isDevEnv),[o,c]=A.useState(!1),[i,d]=A.useState(!1),u=s.useCurrentAIContext(),{setCurrentAIContext:m}=s.useAIActions(),{clearQueue:h}=s.useQueueActions(),{clearFileAttachments:x}=s.useFileActions(),g=s.useFileAttachments("editor"),b=s.useDashboardStore(H=>H.dashboard.aiContext),p=s.useEditorStore(H=>H.card.dataSource),j=s.useEditorStore(H=>H.actions.setCardSql),f=s.useEditorStore(H=>H.actions.setRunSql),y=s.useEditorStore(H=>H.showAIDialog),k=s.useDashboardStore(H=>H.handleOpenAssistantProfile),{setShowAIDialog:T,setCardPython:N}=s.useEditorActions(),{setDataSource:D}=s.useEditorActions(),{assistantProfile:v}=s.useAssistantProfile(),{messages:S,setMessages:C,sendMessage:O,isLoading:I,stop:B,status:E,llmUsage:w,errorMessage:M,clearError:F}=gl(),[R,L]=A.useState(""),P=H=>{L(H.target.value)},Y=H=>{H.preventDefault();const te=R.trim();if(!te&&g.length===0)return;const oe=[];te&&oe.push({type:"text",text:te}),g.forEach(ae=>{ae.data&&oe.push({type:"file",mediaType:ae.type,filename:ae.name,url:`data:${ae.type};base64,${ae.data}`})}),O({role:"user",parts:oe}),L(""),x("editor"),se({force:!0})},{visibleMessages:J,hasMoreMessages:V,totalMessageCount:K,loadMoreMessages:q,resetMessageWindow:Z}=s.useMessageWindow(S,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:$,isAtBottom:X,hasNewMessages:_,newMessageCount:G,scrollToBottom:se,handleScroll:re,resetNewMessageCount:he}=s.useAutoScroll(J,{threshold:50,delay:0,dependencies:[E,S.length]});A.useEffect(()=>{var H;y&&((H=t.current)==null||H.focus(),m({selectedEntities:(p==null?void 0:p.selectedEntities)||[]}))},[y,p,m]),s.useAutoSubmitQueue({assistantType:"editor",status:E,isLoading:I,sendMessage:O});const{hasActiveTools:z}=s.useActiveToolStatus(S);function ee(H,te){te==="sql"?(j(H),f(!0)):te==="python"&&(N(H),f(!0))}function ne(){var H;(H=b==null?void 0:b.selectedEntities)==null||H[0],d(!0)}function le(){u.selectedEntities.length===0&&m({selectedEntities:(b==null?void 0:b.selectedEntities)||[]})}function de(H){le();const te={role:"user",parts:[{type:"text",text:H.title+" "+H.subtitle}]};O(te)}function xe(H){le(),O({role:"user",parts:[{type:"text",text:H}]})}function pe(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:a,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:r,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:c,children:"System Message"})]})]})}function Q(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const U=(R==null?void 0:R.length)===0&&(S==null?void 0:S.filter(H=>H.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Q(),k&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:k,children:(v==null?void 0:v.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[pe(),s.isDevEnv,e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:ne,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:"New Chat",onClick:()=>{C([]),h("editor"),F(),Z()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",onClick:()=>{T(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:$,className:"mt-2 flex w-full grow basis-0",onScroll:re,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[V&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:q,className:"text-xs",children:["Load ",Math.min(5,K-J.length)," ","more messages (",K-J.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:J,showTools:r,handleRun:ee,showSystemMessage:o}),!z&&e.jsx(s.AssistantStatus,{status:E,errorMessage:M})]})}),!X&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{se({force:!0}),he()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),_&&G>0&&e.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:G>9?"9+":G})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[U&&!v&&e.jsx(s.Placeholders,{onClick:de,placeholders:jl}),e.jsx("div",{children:U&&v&&e.jsx(s.SeedQuestions,{seedQuestions:v.seedQuestions||[],handleSeedQuestionClick:xe})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:t,setInput:L,stop:B,input:R,handleInputChange:P,handleSubmit:H=>{le(),Y(H),se({force:!0})},isLoading:I,status:E,assistantType:"editor",onFocus:()=>{}})]}),w&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",w.inputTokens," prompt tokens, ",w.outputTokens," ","completion tokens, ",w.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(p==null?void 0:p.selectedEntities)||[],open:i,onOpenChange:d,dataSource:p||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}const As=t=>{var I;const{updateCardConfig:n,updateGroupByColumn:a,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(B=>B.card.type),h=t==null?void 0:t.id,x=A.useCallback(B=>{if(!(t!=null&&t.config))return[];switch(B){case"groupBy":return(t.config.groupByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType,dateFormat:E.dateFormat,customFormat:E.customFormat,granularity:E.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType,direction:E.direction}));case"source":return[];default:return[]}},[t]),g=A.useCallback((B,E)=>{if(h)switch(B){case"groupBy":{n(h,{groupByColumns:E});break}case"metrics":{n(h,{metricColumns:E});break}case"pivotBy":{n(h,{pivotByColumns:E});break}case"sortBy":{n(h,{sortByColumns:E});break}}},[h,n]),b=A.useCallback((B,E,w)=>{if(!h)return;const F=x(B)[E];if(F)switch(B){case"groupBy":a(h,F.id,{label:w});break;case"metrics":r(h,F.id,{label:w});break;case"pivotBy":l(h,F.id,{label:w});break;case"sortBy":o(h,F.id,{label:w});break}},[h,x,a,r,l,o]),p=A.useCallback((B,E)=>{if(!h)return;const M=x("metrics")[B];M&&r(h,M.id,{aggregate:E,label:s.getAggregationLabel(M.name,E)})},[h,x,r]),j=A.useCallback((B,E,w)=>{if(!h)return;const F=x("groupBy")[B];if(!F)return;const R={dateFormat:E};E==="custom"&&w?R.customFormat=w:R.customFormat=void 0,a(h,F.id,R)},[h,x,a]),f=A.useCallback((B,E)=>{if(!h)return;const M=x("groupBy")[B];M&&a(h,M.id,{granularity:E})},[h,x,a]),y=A.useCallback((B,E)=>{if(!h)return;const M=x("metrics")[B];M&&r(h,M.id,{aliasTemplate:E})},[h,x,r]),k=A.useCallback((B,E)=>{if(console.log("handleValueAliasesChange",B,E),!h)return;console.log("handleValueAliasesChange",B,E);const M=x("metrics")[B];M&&(console.log("handleValueAliasesChange",E),r(h,M.id,{valueAliases:E}))},[h,x,r]),T=A.useCallback(B=>{h&&n(h,{comparisonType:B})},[h,n]),N=A.useCallback(B=>{h&&n(h,{showTrendline:B})},[h,n]),D=A.useCallback(B=>{h&&n(h,{trendlineWindow:B})},[h,n]),v=A.useCallback(B=>{h&&n(h,{trendlineGranularity:B})},[h,n]),S=A.useCallback(B=>{h&&n(h,{targetValue:B})},[h,n]),C=A.useCallback(B=>{var P;if(!h)return;const E=[...x("groupBy"),...x("pivotBy"),...x("metrics"),...x("sortBy")],w=(P=t==null?void 0:t.config)==null?void 0:P.joinPlan,M=s.validateEntityConsistency(B,E,w);if(!M.isValid){M.showError&&s.showJoinRequiredNotification();return}const F=s.getSmartContainerForField(B,E),R=x(F);if(s.fieldAlreadyExists(B,R))return;const L=s.getNewField(B,F,R);L&&g(F,[...R,L])},[h,(I=t==null?void 0:t.config)==null?void 0:I.joinPlan,x,g]),O=A.useCallback((B,E)=>{if(!h)return;const M=x(B)[E];if(M){if(B!=="sortBy"){const F=x("sortBy"),R=F.filter(L=>!(L.name===M.name&&L.qualifiedEntityName===M.qualifiedEntityName));R.length!==F.length&&n(h,{sortByColumns:R})}switch(B){case"groupBy":c(h,M.id);break;case"metrics":i(h,M.id);break;case"pivotBy":d(h,M.id);break;case"sortBy":u(h,M.id);break}}},[h,x,c,i,d,u,n]);return{getFieldsForContainer:x,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:p,handleDateFormatChange:j,handleGranularityChange:f,handleAliasTemplateChange:y,handleValueAliasesChange:k,removeField:O,handleFieldClick:C,handleKpiComparisonTypeChange:T,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:S,cardType:m}};function bl({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function vl({field:t}){const{attributes:n,listeners:a,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,d]=A.useState(!1),u=s.useEditorStore(b=>b.card),{handleFieldClick:m}=As(u),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const x=b=>{const p=(b||"").toLowerCase();switch(s.getDataType(p)){case"number":return De;case"date":return s.Calendar;case"boolean":return Le;case"json":return ze;case"geo":return qe;default:return ve}},g=b=>{const p=(b||"").toLowerCase(),j=s.getDataType(p);return j==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):j==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):j==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):j==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):j==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ze,{className:"h-3 w-3"})}):j==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(qe,{className:"h-3 w-3"})}):j==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ke,{className:"h-3 w-3"})}):null};return x(t.dataType),e.jsxs("div",{ref:r,style:h,...n,...a,className:`group/container max-w-[265px] overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>m(t),children:[g(t.dataType),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-xs text-foreground/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(bl,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.name})]}),e.jsx(s.Badge,{variant:"outline",className:"mt-2 text-xs",children:t.dataType})]})})})]})}function yl(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useEditorStore(k=>k.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),u=o.filter(k=>k.name.toLowerCase().includes(t.toLowerCase())||k.dataType.toLowerCase().includes(t.toLowerCase())||k.qualifiedEntityName&&k.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=k=>{if(k.dataType==="number"||k.dataType==="integer"||k.dataType==="float"||k.dataType==="decimal"||k.dataType==="currency")return"metrics";const T=s.getDataType(k.dataType);return["date","string","boolean"].includes(T)?"dimensions":T==="number"?"metrics":"dimensions"},x=(a==="all"?u:u.filter(k=>m(k)===a)).reduce((k,T)=>{const N=T.qualifiedEntityName||"Other Fields";return k[N]||(k[N]={label:s.toLabel(T.entityName),fields:[]}),k[N].fields.push(T),k},{}),b=Object.keys(x),p=u.filter(k=>m(k)==="dimensions").length,j=u.filter(k=>m(k)==="metrics").length,f=u.filter(k=>m(k)==="calculated").length,y=u.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[o.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:t,onChange:k=>n(k.target.value)}),t&&e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:e.jsx(s.X,{className:"size-3.5"})})]}),y&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:k=>r(k),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:u.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Ke,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:b,className:"space-y-2",children:Object.entries(x).map(([k,T])=>{const N=c.find(D=>D.entityName===k)||{entityName:k,label:T.label};return e.jsxs(s.AccordionItem,{value:k,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{title:N.label||N.entityName,className:"flex items-center gap-2",children:[e.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:N.label||N.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:T.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:T.fields.map(D=>e.jsx(vl,{field:D},D.id))})})]},k)})}),Object.keys(x).length===0&&o.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(x).length===0&&o.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function Nl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(yl,{})," "]})}function Cl({initialJoinPlan:t,availableDataSources:n}){const[a,r]=A.useState(t),[l,o]=A.useState(new Set),c=()=>{const D=a.joins.length>0?Math.max(...a.joins.map(S=>S.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:D,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,v]}),o(new Set([...l,v.id]))},i=D=>{r({...a,joins:a.joins.filter(v=>v.id!==D)}),o(new Set([...l].filter(v=>v!==D)))},d=(D,v)=>{var I,B;const S=a.joins.find(E=>E.id===D);if(!S)return;const C={...S,...v},O=a.joins.map(E=>E.id===D?C:E);if((I=C.source)!=null&&I.name&&((B=C.target)!=null&&B.name)&&C.joinKeyGroups[0].keys.length===0){const E=n.find(R=>{var L;return R.name===((L=C.source)==null?void 0:L.name)}),w=n.find(R=>{var L;return R.name===((L=C.target)==null?void 0:L.name)}),M={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(E==null?void 0:E.name)||"",entityName:(E==null?void 0:E.name)||"",entityType:(E==null?void 0:E.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},operator:"="},F=[...C.joinKeyGroups];F[0]={...F[0],keys:[M]},C.joinKeyGroups=F,O[O.findIndex(R=>R.id===D)]=C}r({...a,joins:O})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:D=>{const v=a.joins.findIndex(S=>S.id===D);if(v>0){const S=[...a.joins],C={...S[v]},O={...S[v-1]};S[v]=O,S[v-1]=C,S.forEach((B,E)=>{B.sequence=E+1});const I={...a,joins:S};r(I)}},moveJoinDown:D=>{const v=a.joins.findIndex(S=>S.id===D);if(v<a.joins.length-1){const S=[...a.joins],C={...S[v]},O={...S[v+1]};S[v]=O,S[v+1]=C,S.forEach((B,E)=>{B.sequence=E+1});const I={...a,joins:S};r(I)}},toggleJoinExpansion:D=>{const v=new Set(l);v.has(D)?v.delete(D):v.add(D),o(v)},getAvailableSourceEntities:D=>{if(a.joins.length===0)return n;const v=a.joins.findIndex(C=>C.id===D);if(v===0)return n;const S=new Set;return a.baseEntity.name&&S.add(a.baseEntity.name),a.joins.slice(0,v).forEach(C=>{S.add(C.source.name),S.add(C.target.name)}),n.filter(C=>S.has(C.name))},getAvailableTargetEntities:D=>n.filter(v=>v.name!==D),addJoinKeyGroup:D=>{const v=a.joins.find(C=>C.id===D);if(!v)return;const S=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(D,{joinKeyGroups:S})},updateGroupOperator:(D,v,S)=>{const C=a.joins.find(I=>I.id===D);if(!C)return;const O=[...C.joinKeyGroups];O[v]={...O[v],operator:S},d(D,{joinKeyGroups:O})},removeJoinKeyGroup:(D,v)=>{const S=a.joins.find(O=>O.id===D);if(!S)return;const C=[...S.joinKeyGroups];C.splice(v,1),d(D,{joinKeyGroups:C})},addJoinKey:(D,v)=>{const S=a.joins.find(E=>E.id===D);if(!S)return;const C=n.find(E=>E.name===S.source.name),O=n.find(E=>E.name===S.target.name),I=[...S.joinKeyGroups],B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(C==null?void 0:C.name)||"",entityName:(C==null?void 0:C.name)||"",entityType:(C==null?void 0:C.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},operator:"="};I[v]={...I[v],keys:[...I[v].keys,B]},d(D,{joinKeyGroups:I})},updateJoinKey:(D,v,S,C,O)=>{const I=a.joins.find(F=>F.id===D);if(!I)return;const B=n.find(F=>F.name===I.source.name),E=n.find(F=>F.name===I.target.name),w=[...I.joinKeyGroups],M=w[v].keys[S];C==="sourceColumnName"&&B?w[v].keys[S]={...M,source:{...M.source,name:O}}:C==="targetColumnName"&&E?w[v].keys[S]={...M,target:{...M.target,name:O}}:C==="operator"&&(w[v].keys[S]={...M,operator:O}),d(D,{joinKeyGroups:w})},removeJoinKey:(D,v,S)=>{const C=a.joins.find(I=>I.id===D);if(!C)return;const O=[...C.joinKeyGroups];O[v].keys.splice(S,1),d(D,{joinKeyGroups:O})},generateSQLPreview:()=>{const D=[...a.joins].sort((C,O)=>C.sequence-O.sequence),v=a.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let S=`SELECT *
|
|
334
|
+
FROM ${v.name}`;return D.forEach(C=>{const O=n.find(E=>E.name===C.target.name);if(!O)return;const I=C.joinKeyGroups.filter(E=>E.keys&&E.keys.length>0).map(E=>{const w=E.keys.filter(M=>{var F,R,L,P;return((F=M.source)==null?void 0:F.name)&&((R=M.target)==null?void 0:R.name)&&((L=M.source)==null?void 0:L.entityName)&&((P=M.target)==null?void 0:P.entityName)}).map(M=>`${M.source.entityName}.${M.source.name} ${M.operator} ${M.target.entityName}.${M.target.name}`);return w.length>1?`(${w.join(` ${E.operator} `)})`:w[0]}).filter(Boolean),B=I.length>1?I.join(" OR "):I[0]||"condition_here";S+=`
|
|
335
|
+
${C.joinType} JOIN ${O.name}
|
|
336
|
+
ON ${B}`}),S},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(C=>!C.source.name||!C.target.name)||a.joins.some(C=>C.joinKeyGroups.some(O=>O.keys.length===0))||a.joins.some(C=>C.joinKeyGroups.some(O=>O.keys.some(I=>!I.source.name||!I.target.name||!I.operator))))}}function Sl({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(I=>I.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:x,moveJoinUp:g,moveJoinDown:b,toggleJoinExpansion:p,getAvailableSourceEntities:j,getAvailableTargetEntities:f,addJoinKeyGroup:y,updateGroupOperator:k,removeJoinKeyGroup:T,addJoinKey:N,updateJoinKey:D,removeJoinKey:v,generateSQLPreview:S,isValidConfiguration:C}=Cl({initialJoinPlan:t,availableDataSources:n}),O=I=>{const B=c.find(E=>E.entityName===I);return(B==null?void 0:B.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:I=>{const B=n.find(E=>E.name===I);u({...i,baseEntity:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:I,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(I=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:I.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:I.type}),I.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},I.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:S()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(I=>{const B=n.find(M=>M.name===I.source.name),E=n.find(M=>M.name===I.target.name),w=d.has(I.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:I.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",I.sequence,B&&E&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",B.name," → ",E.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(I.id),disabled:I.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(I.id),disabled:I.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(I.id),children:w?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(I.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),w&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:I.source.name,onValueChange:M=>{const F=n.find(R=>R.name===M);x(I.id,{source:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:M,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:j(I.id).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name]})},M.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:I.joinType,onValueChange:M=>x(I.id,{joinType:M}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:I.target.name,onValueChange:M=>{const F=n.find(R=>R.name===M);x(I.id,{target:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:M,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},disabled:!I.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:I.source.name?f(I.source.name).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name,M.name===I.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},M.name)):[]})]})]})]}),I.source.name&&I.target.name&&B&&E&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>y(I.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),I.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:I.joinKeyGroups.map((M,F)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",F+1]}),F>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:M.operator,onValueChange:R=>k(I.id,F,R),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>T(I.id,F),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[M.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:M.keys.map((R,L)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[L>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:M.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:R.source.name,onValueChange:P=>D(I.id,F,L,"sourceColumnName",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:O(I.source.name).map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:P.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:R.operator,onValueChange:P=>D(I.id,F,L,"operator",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:R.target.name,onValueChange:P=>D(I.id,F,L,"targetColumnName",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:O(I.target.name).map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:P.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>v(I.id,F,L),children:e.jsx(s.X,{className:"size-3.5"})})]},R.id||L))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>N(I.id,F),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},M.id))})]})]})]},I.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(i),disabled:!C(),children:"Save"})]})]})}function Hs({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Sl,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function wl({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=a.find(c=>c.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=a.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=a.find(d=>d.name===l.source.name),i=a.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function Dl(){var m,h;const t=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>x.actions.updateCardConfig),a=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=A.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=x=>{n(t.id,{...t==null?void 0:t.config,joinPlan:x}),l(!1)},i=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},u=()=>{const x=[...a.joins].sort((p,j)=>p.sequence-j.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let b=`SELECT *
|
|
337
|
+
FROM ${g.name}`;return x.forEach(p=>{const j=o.find(k=>k.name===p.target.name);if(!j)return;const f=p.joinKeyGroups.filter(k=>k.keys&&k.keys.length>0).map(k=>{const T=k.keys.filter(N=>{var D,v,S,C;return((D=N.source)==null?void 0:D.name)&&((v=N.target)==null?void 0:v.name)&&((S=N.source)==null?void 0:S.entityName)&&((C=N.target)==null?void 0:C.entityName)}).map(N=>`${N.source.entityName}.${N.source.name} ${N.operator} ${N.target.entityName}.${N.target.name}`);return T.length>1?`(${T.join(` ${k.operator} `)})`:T[0]}).filter(Boolean),y=f.length>1?f.join(" OR "):f[0]||"condition_here";b+=`
|
|
338
|
+
${p.joinType} JOIN ${j.name}
|
|
339
|
+
ON ${y}`}),b};return o.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[a.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>l(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":a.joins.length>0,"text-gray-500":a.joins.length===0})}),"Join",a.joins.length>1?"s":""," (",a.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(wl,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:o,generateSQLPreview:u})})]})}),e.jsx(Hs,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(Hs,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function Tl({open:t,onOpenChange:n}){const[a,r]=A.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(p=>p.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];A.useEffect(()=>{t&&r([])},[t]);const i=p=>{r(j=>j.some(y=>y.name===p.name&&y.type===p.type)?j.filter(y=>!(y.name===p.name&&y.type===p.type)):[...j,p])},d=()=>{r([...c])},u=()=>{r([])},m=()=>{if(a.length===0)return;const p=a[0],j=p.connectionId||"",f=p.connectionType||"",k=a.some(N=>N.type==="dataset")?"semanticDomain":"database";l({connectionId:j,connectionType:f,mode:k,selectedEntities:a}),n(!1)},h=p=>{switch(p.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Wa,{className:"h-4 w-4"});case"model":return e.jsx(ja,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},x=p=>"label"in p&&p.label?p.label:p.name,g=p=>{if("description"in p&&p.description)return p.description;const j=[];return p.database&&j.push(p.database),p.schema&&j.push(p.schema),p.name&&j.push(p.name),j.join(".")},b=p=>a.some(j=>j.name===p.name&&j.type===p.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:a.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((p,j)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",b(p)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:b(p),onCheckedChange:()=>i(p)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(p)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:x(p)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(p)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p.type})]},`${p.type}-${p.name}-${j}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function kl({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function El({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((n,a)=>{const r=s.getEntityDetails(n),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function Il({isVisible:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(!1),[o,c]=A.useState(!0),i=s.useEditorStore(h=>h.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:d}=s.useEditorActions(),u={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},m={...u,...i,selectedEntities:(i==null?void 0:i.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:"p-4 px-6 pb-2",children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>a(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Add Data"]})}),e.jsxs("div",{className:"relative px-6",children:[e.jsx("div",{className:"absolute inset-0 flex items-center px-6",children:e.jsx("div",{className:"w-full border-t border-border"})}),e.jsx("div",{className:"relative flex justify-center",children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>c(!o),className:"size-6 bg-background p-1 py-1 hover:bg-accent",children:o?e.jsx(s.ChevronUp,{className:"h-3.5 w-3.5"}):e.jsx(s.ChevronDown,{className:"h-3.5 w-3.5"})})})]}),e.jsxs("div",{className:`overflow-hidden px-6 ${o?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[m.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[m.selectedEntities.slice(0,3).map((h,x)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{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:[s.getDisplayName(h),e.jsx("button",{onClick:g=>{g.stopPropagation();const b=m.selectedEntities.filter(p=>!(p.name===h.name&&p.type===h.type));d({...u,...i,selectedEntities:b})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(kl,{entity:h})]},`${h.type}-${h.name}-${x}`)),m.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",m.selectedEntities.length-3," more"]})}),e.jsx(El,{entities:m.selectedEntities.slice(3)})]})]})}),e.jsx(Dl,{})]})]}),e.jsx(Nl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(i==null?void 0:i.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:a,dataSource:m,fallbackDataSource:u}),e.jsx(Tl,{open:r,onOpenChange:l})]})}const Al="chart-selector-standard-first";function Ml(){const[t,n]=s.useLocalStorageState(Al,!0);return{standardFirst:t,updatePreference:n}}const Ws=({pluginVisual:t,index:n,onSelect:a})=>{const r=ds(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},Ks=["default","standardPlugin","customPlugin"];function Ll({selectedChart:t,onChartChange:n}){var T;const[a,r]=A.useState(!1),{data:l}=Et();Ml();const c=((T=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:T.url)||"";Ds(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:x}=s.useEditorActions(),[g,b]=s.useLocalStorageState("chart-section-active",null),p=A.useMemo(()=>g?[g,...Ks.filter(N=>N!==g)]:Ks,[g]);function j(N){m(null),d({}),i(N),["custom","map"].includes(N)&&(u(!0),x(void 0)),n(N),r(!1)}function f(N){m(null),d({}),i("custom"),h({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),x(void 0),n("custom"),r(!1)}const y=()=>{var D;if(t==="custom"){const v=s.useEditorStore.getState().card;return((D=v==null?void 0:v.customCardPreferences)==null?void 0:D.componentName)||"Custom Visual"}const N=s.chartTypes.find(v=>v.id===t);return(N==null?void 0:N.label)||"Select chart type"},k=()=>{var D,v;if(t==="custom"){const S=s.useEditorStore.getState().card,C=(D=S==null?void 0:S.customCardPreferences)==null?void 0:D.icon,O=(v=S==null?void 0:S.customCardPreferences)==null?void 0:v.componentName;if(C&&O)return e.jsx(Rl,{icon:C,componentName:O});if(O){const I=s.getAutoDetectedChartIcon(O);if(I)return I}return e.jsx(He,{className:"h-4 w-4"})}const N=s.chartTypes.find(S=>S.id===t);if(N){const S=N.icon;return e.jsx(S,{className:"h-4 w-4"})}return e.jsx(He,{className:"h-4 w-4"})};return e.jsx("div",{className:"",children:e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[k(),e.jsx("span",{children:y()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),p.map(N=>{if(N==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="default",onCheckedChange:D=>b(D?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:s.chartTypes.map(D=>{const v=D.icon;return e.jsx(s.CommandItem,{value:`${D.label} ${D.id} chart graph visualization`,onSelect:()=>j(D.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{className:"h-4 w-4"}),e.jsx("span",{children:D.label})]})},D.id)})},"default");if(N==="standardPlugin"){const D=l.filter(v=>v.pluginType==="standard");return D.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="standardPlugin",onCheckedChange:v=>b(v?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.filter(v=>v.componentType==="chart").map((v,S)=>e.jsx(Ws,{pluginVisual:v,index:S,onSelect:()=>f(v)},`${v.url}-${v.name}-${S}`))},"standardPlugin"):null}if(N==="customPlugin"){const D=l.filter(v=>v.pluginType==="custom");return D.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="customPlugin",onCheckedChange:v=>b(v?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:D.map((v,S)=>e.jsx(Ws,{pluginVisual:v,index:S,onSelect:()=>f(v)},`${v.url}-${v.name}-${S}`))},"customPlugin"):null}return null})]})]})})]})})}const Rl=({icon:t,componentName:n})=>{const a=ds(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(He,{className:"h-4 w-4"})},Ol=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!0},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"}];function Fl({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(o=>o.card),r=((l=a==null?void 0:a.config)==null?void 0:l.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center justify-center gap-1",children:Ol.map(o=>{if(o.requiresPivot&&!r)return null;const c=o.icon,i=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(o.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o.label})})]},o.id)})})}const Ms=({dataType:t})=>{const n=s.getDataType(t);return n==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})};function Bl({aliasTemplate:t,onAliasTemplateChange:n}){var d;const[a,r]=A.useState(t),[l,o]=A.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?a:t,onChange:u=>{r(u.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&a!==t?(n(a),o(!1)):u.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Pl({valueAliases:t,onValueAliasesChange:n}){const[a,r]=A.useState(null),[l,o]=A.useState(""),[c,i]=A.useState(""),d=()=>{n({...t,"":""})},u=h=>{const x={...t};delete x[h],n(x)},m=h=>{const x={...t};delete x[h],x[l]=c,n(x),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,x],g)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:b=>i(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(x)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(x)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+g)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function zl({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),o=s.useEditorStore(u=>u.card),c=o==null?void 0:o.dataSource,i=["attribute-values",t.entityName,t.name,n,a],d=s.useQuery({queryKey:i,queryFn:async()=>{if(!(c!=null&&c.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},m={connection_id:c.connectionId,cardConfig:u,cardDataSource:c,cache_config:s.getCacheConfig({card:o})};console.log("requestBody",m);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const x=t.name;return((h==null?void 0:h.records)||[]).map(b=>{const p=b[x]||b[t.alias||x]||b[t.label];return{id:p||"",value:p||"",label:String(p||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(c!=null&&c.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:d.data||[],isLoading:d.isLoading,isFetching:d.isFetching,isError:d.isError,error:d.error,refetch:d.refetch}}function Vl({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:o}){var k,T;const c=!!l,[i,d]=A.useState(c?"values":"fields"),[u,m]=A.useState(""),[h,x]=A.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),g=a.filter(N=>{var v;return c?!1:!((v=r==null?void 0:r.conditions)==null?void 0:v.some(S=>S.field.id===N.id))&&N.label.toLowerCase().includes(u.toLowerCase())}),b=N=>{x({...h,field:N}),d("values")},p=()=>{if(h.field&&h.selectedValues.length>0){const N={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let D;if(c){const v=((r==null?void 0:r.conditions)||[]).map(S=>S.id===l.id?N:S);D={...r,conditions:v}}else{const v=(r==null?void 0:r.conditions)||[];D={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...v,N],groups:[]}}o(D),n(!1)}},j=()=>{if(!c||!l)return;const N=((r==null?void 0:r.conditions)||[]).filter(D=>D.id!==l.id);if(N.length>0){const D={...r,conditions:N};o(D)}else o(void 0);n(!1)},f=N=>{x({...h,selectedValues:N})},y=()=>{c&&l?(x({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(x({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return A.useEffect(()=>{t&&y()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(k=h.field)==null?void 0:k.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(T=h.field)==null?void 0:T.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(N=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[N.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(N.value)?`${N.value.length} values`:String(N.value)})]},N.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:u,onChange:N=>m(N.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(N=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(N),children:[e.jsx(Ms,{dataType:s.getDataType(N.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:N.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[N.entityName,".",N.name]})]})]},N.id))}),g.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),g.length===0&&!u&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(_l,{field:h.field,selectedValues:h.selectedValues,onValuesChange:f,onBack:c?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:j,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:y,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:p,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function _l({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,o]=A.useState(""),{values:c,isLoading:i,isFetching:d}=zl({field:t,searchQuery:l,limit:500}),u=l?c.filter(x=>String(x.value).toLowerCase().includes(l.toLowerCase())):c,m=x=>{const g=n.includes(x);a(g?n.filter(b=>b!==x):[...n,x])},h=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(x=>x.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:x=>o(x.target.value),className:"pl-10"})]}),i||d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(x=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(x.value),children:[e.jsx(s.Checkbox,{checked:n.includes(x.value),onCheckedChange:()=>m(x.value)}),e.jsx(us,{className:"text-sm",children:x.label})]},x.id))})]})]})}function Ul({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Rs,Os,Fs;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:x}=s.useSortable({id:t.id}),g=s.useEditorStore(W=>W.card),{updateLabel:b,handleAggregationChange:p,handleDateFormatChange:j,handleGranularityChange:f,handleAliasTemplateChange:y,handleValueAliasesChange:k,removeField:T,handleKpiComparisonTypeChange:N,handleKpiShowTrendlineChange:D,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:S,handleKpiTargetValueChange:C}=As(g),[O,I]=A.useState(!1),[B,E]=A.useState(!1),[w,M]=A.useState(null),[F,R]=A.useState(t.dateFormat||"YYYY-MM-DD"),[L,P]=A.useState(t.customFormat||""),[Y,J]=A.useState(!!t.customFormat),[V,K]=A.useState(t.granularity||"day"),[q,Z]=A.useState(t.aliasTemplate||""),[$,X]=A.useState(t.valueAliases||{}),[_,G]=A.useState((Rs=t.parameters)==null?void 0:Rs.filters),se=W=>{W==="custom"?J(!0):(J(!1),R(W),n==="groupBy"&&j(a,W,""))},re=W=>{P(W),n==="groupBy"&&j(a,"custom",W)},he=W=>{var fe;K(W);const ce=(fe=H(W)[0])==null?void 0:fe.value;ce&&!Y&&(R(ce),n==="groupBy"&&j(a,ce,"")),n==="groupBy"&&f(a,W)},z=W=>{Z(W),n==="metrics"&&y(a,W)},ee=W=>{X(W),n==="metrics"&&k(a,W)},ne=W=>{b(n,a,W)},le=W=>{var ie;if(G(W),n==="metrics"){const ce={...t,parameters:{...t.parameters,filters:W}},fe=[...((ie=g.config)==null?void 0:ie.metricColumns)||[]];fe[a]=ce,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:fe})}E(!1)},de=()=>{T(n,a)},xe={transform:s.CSS.Transform.toString(m),transition:h},pe=s.getDataType(t.dataType),Q=pe==="date",U=c==="kpi",H=W=>{switch(W){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},te=H(V),oe=n!=="pivotBy",ae=Q&&n==="groupBy",je=!U&&Q&&n==="groupBy",me=U&&Q&&n==="groupBy",Qe=U&&n==="metrics"&&((Os=g.config)==null?void 0:Os.comparisonType)==="target",Je=n==="metrics",Ye=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:W=>{W.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),Te=()=>oe?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(we,{value:t.label??"",onSave:ne,placeholder:"Display label...",type:"text"})]}):null,ue=()=>ae?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:V,onValueChange:he,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(W=>e.jsx(s.SelectItem,{className:"text-xs",value:W,children:s.toTitleCase(W)},W))})]})]}):null,Qt=()=>je?e.jsxs(e.Fragment,{children:[ue(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:Y?"custom":F,onValueChange:se,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:te.map(W=>e.jsx(s.SelectItem,{className:"text-xs",value:W.value,children:W.label},W.value))})]}),Y&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:L,onChange:W=>{W.stopPropagation(),re(W.target.value)},onClick:W=>W.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,Jt=()=>{var W,ie,ce,fe,ke;return me?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((W=g.config)==null?void 0:W.comparisonType)||"none",onValueChange:N,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ie=g.config)==null?void 0:ie.showTrendline)||!1,onCheckedChange:D})]})}),((ce=g.config)==null?void 0:ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((fe=g.config)==null?void 0:fe.trendlineWindow)||30,onChange:Xe=>{const ta=parseInt(Xe.target.value)||30;v(ta)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((ke=g.config)==null?void 0:ke.trendlineGranularity)||"day",onValueChange:S,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},Xt=()=>{var W,ie;return Qe?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(we,{value:((W=g.config)==null?void 0:W.targetValue)!==void 0&&((ie=g.config)==null?void 0:ie.targetValue)!==null?String(g.config.targetValue):"",onSave:ce=>{!isNaN(Number(ce))&&ce!==null?C(Number(ce)):C(0)},placeholder:"Enter target value...",type:"text"})]}):null},Zt=()=>Je?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:W=>{p(a,W)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(_==null?void 0:_.conditions)&&_.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:_.conditions.map(W=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{M(W),E(!0)},children:[e.jsxs("span",{className:"font-medium",children:[W.field.label,":"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(W.value)?W.value.length===1?String(W.value[0]):W.value.length<=2?W.value.join(", "):`${W.value.slice(0,2).join(", ")} +${W.value.length-2}`:String(W.value)})}),Array.isArray(W.value)&&W.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",W.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:W.value.map((ie,ce)=>e.jsx("div",{children:String(ie)},ce))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ie=>{var fe;ie.stopPropagation();const ce=_.conditions.filter(ke=>ke.id!==W.id);if(ce.length>0){const ke={..._,conditions:ce};le(ke)}else if(G(void 0),n==="metrics"){const ke={...t,parameters:{...t.parameters,filters:void 0}},Xe=[...((fe=g.config)==null?void 0:fe.metricColumns)||[]];Xe[a]=ke,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:Xe})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},W.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{M(null),E(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Yt,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(Bl,{aliasTemplate:q,onAliasTemplateChange:z}),e.jsx(Pl,{valueAliases:$,onValueAliasesChange:ee})]})]}):null,{columns:ea=[]}=s.useColumns(),sa=(_==null?void 0:_.conditions)&&_.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:xe,...i,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${x?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Ms,{dataType:pe}),e.jsx(us,{className:s.cn("w-[140px] flex-1 text-xs",sa&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Fs=_==null?void 0:_.conditions)==null?void 0:Fs.length)&&!O&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:_.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:_.conditions.map(W=>e.jsxs("div",{children:[W.field.label,":"," ",Array.isArray(W.value)?`${W.value.length} values`:String(W.value)]},W.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:W=>{W.stopPropagation(),I(!O)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${O?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:W=>{W.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ie=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ie),l(ie)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:W=>{W.stopPropagation(),de()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),O&&e.jsxs("div",{className:"space-y-3",children:[Ye(),Te(),c==="kpi"&&ue(),Qt(),Jt(),Xt(),Zt()]})]}),B&&e.jsx(Vl,{open:B,onOpenChange:W=>{E(W),W||M(null)},availableFields:ea,existingFilters:_,editingCondition:w,onSave:W=>{var ie;if(W)le(W);else if(G(void 0),n==="metrics"){const ce={...t,parameters:{...t.parameters,filters:void 0}},fe=[...((ie=g.config)==null?void 0:ie.metricColumns)||[]];fe[a]=ce,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:fe})}M(null)}})]})}function Gl({concept:t}){const n=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}function ss({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(b=>b.card),m=s.useEditorStore(b=>b.card.type),h=n.length>0,x=(b,p)=>{var f;!((f=u.config)!=null&&f.sortByColumns)||u.config.sortByColumns.findIndex(y=>y.id===b)===-1||d(u.id,b,{direction:p})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),g&&e.jsx(Gl,{concept:t})]}),e.jsx("div",{ref:i,className:`rounded-lg border-2 border-dashed p-1 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"min-h-[60px] border-muted-foreground/20 bg-background"}`,children:n.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:n.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((b,p)=>{const f=b.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Ul,{field:b,zone:t,index:p,sortDirection:f,onSortDirectionChange:y=>x(b.id,y),hasPivotColumns:o,cardType:m})})},b.id)})})})})]})}const Qs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Yl=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function vs({value:t,onChange:n,label:a}){const[r,l]=A.useState(!1),[o,c]=A.useState(!1),i=()=>{const d=Qs.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Qs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:Yl.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{n(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Pt,{color:i(),onColorChange:d=>{n(d),c(!1)},onClose:()=>c(!1)})})]})]})}const ts={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
|
|
340
|
+
Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function $l(){var i,d,u,m,h,x,g,b,p,j;const t=s.useEditorStore(f=>f.card),{setCardPreferences:n}=s.useEditorActions(),a=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(a.length>=2&&r.length===0||a.length>=1&&r.length>0)))return null;const o=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=f=>{var k;const y={...t.preferences,kpiVisualOptions:{...(k=t.preferences)==null?void 0:k.kpiVisualOptions,metricComparison:{...o,...f}}};n(y)};return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ca,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:f=>c({enabled:f,...f&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:f=>c({calculationType:f}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(ts).map(([f,y])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:y.label},f))})]}),(()=>{var y,k,T;const f=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(y=ts[f])==null?void 0:y.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(k=ts[f])==null?void 0:k.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(T=ts[f])==null?void 0:T.example]})]})})()]}),e.jsx(Es,{formatOptions:o.formatOptions||{},onFormatOptionsChange:f=>c({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"left",onValueChange:f=>c({position:f}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:f=>c({showArrow:f})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:f=>c({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(vs,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:f=>c({colorConfig:{...o.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(vs,{value:((x=o.colorConfig)==null?void 0:x.decrease)||"red",onChange:f=>c({colorConfig:{...o.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(vs,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:f=>c({colorConfig:{...o.colorConfig,noChange:f}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:f=>c({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((b=o.conditionalLabels)==null?void 0:b.increase)??"Increase",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,increase:f.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((p=o.conditionalLabels)==null?void 0:p.decrease)??"Decrease",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,decrease:f.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((j=o.conditionalLabels)==null?void 0:j.noChange)??"No change",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,noChange:f.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:f=>c({labelName:f.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function ql(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var d;const i={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};n(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(Es,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function Hl({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const l=s.useEditorStore(b=>{var p;return((p=b.card.customCardPreferences)==null?void 0:p.url)&&b.card.type==="custom"}),o=s.useEditorStore(b=>b.card),c=o==null?void 0:o.type,i=t.length>0||a.length>0,d=c!=="kpi",u=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel","aggregateTable"].includes(c),h=d&&!m,x=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(ss,{zone:"groupBy",fields:t,label:x().label,placeholder:x().placeholder}),h&&e.jsx(ss,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(ss,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),u&&e.jsx(ss,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(ql,{}),e.jsx($l,{}),e.jsx(zt,{}),e.jsx(Vt,{}),e.jsx(_t,{}),e.jsx(Ut,{})]})})]})]})}function Wl({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}){const[c,i]=A.useState(!1);s.useEditorStore(p=>p.showAIDialog);const d=s.useEditorStore(p=>p.card),{isLoading:u,isFetching:m,refetch:h}=s.useDashboardCardQuery(d),x=a.length>0||r.length>0||l.length>0,{setShowAIDialog:g}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(d);return A.useEffect(()=>{m||i(!1)},[m]),e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx(Fl,{selectedChart:t,onChartChange:n}),e.jsx(Ll,{selectedChart:t,onChartChange:n})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsxs("div",{className:s.cn("invisible flex gap-2",{visible:x||b}),children:[e.jsx(cs,{}),e.jsx(s.Button,{disabled:u||m,onClick:()=>{i(!0),h()},className:"h-8 shrink-0",size:"sm",variant:"secondary",children:c?e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}):e.jsx(s.RefreshCcw,{className:"h-4 w-4"})})]})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(Hl,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Kl({initialFilters:t,availableFields:n}={}){const[a,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(N=>N.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=n||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=N=>{const D=v=>{if(v.id===N){const S=i[0]||d,C=s.getDataType(S.dataType)==="date";return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:S,operator:C?"between":"=",value:C?[]:""}]}}return{...v,groups:v.groups.map(D)}};r(D(a))},m=N=>{const D=v=>{if(v.id===N){const S=i[0]||d,C=s.getDataType(S.dataType)==="date";return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:S,operator:C?"between":"=",value:C?[]:""}],groups:[]}]}}return{...v,groups:v.groups.map(D)}};r(D(a))},h=(N,D)=>{const v=S=>S.id===N?{...S,conditions:S.conditions.filter(C=>C.id!==D)}:{...S,groups:S.groups.map(v)};r(v(a))},x=(N,D)=>{const v=S=>S.id===N?{...S,groups:S.groups.filter(C=>C.id!==D)}:{...S,groups:S.groups.map(v)};r(v(a))},g=(N,D,v,S)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const C=O=>O.id===N?{...O,conditions:O.conditions.map(I=>I.id===D?{...I,[v]:S}:I)}:{...O,groups:O.groups.map(C)};r(C(a))},b=(N,D,v)=>{const S=C=>C.id===N?{...C,conditions:C.conditions.map(O=>O.id===D?{...O,...v}:O)}:{...C,groups:C.groups.map(S)};r(S(a))},p=(N,D)=>{const v=S=>S.id===N?{...S,logicalOperator:D}:{...S,groups:S.groups.map(v)};r(v(a))},j=(N,D)=>{const v=S=>S.id===N?{...S,negate:D}:{...S,groups:S.groups.map(v)};r(v(a))},f=(N,D,v)=>{const S=C=>C.id===N?{...C,conditions:s.arrayMove(C.conditions,D,v)}:{...C,groups:C.groups.map(S)};r(S(a))},y=(N,D,v)=>{const S=C=>C.id===N?{...C,groups:s.arrayMove(C.groups,D,v)}:{...C,groups:C.groups.map(S)};r(S(a))},k=N=>{if(!N||N.conditions.length===0&&N.groups.length===0)return"-- No filters defined";const D=S=>{let C="";typeof S.field=="object"?C=S.field.entityName?`${S.field.entityName}.${S.field.name}`:S.field.name:C=String(S.field);const O=S.operator;let I=S.value;if(S.field.dataType==="string"&&!["in","not in"].includes(S.operator))typeof I=="string"?I=`'${I}'`:Array.isArray(I)&&(I=`'${I.join(", ")}'`);else if(S.field.dataType==="date"||S.field.dataType==="datetime"||S.field.dataType==="timestamp")if(S.operator==="between"&&Array.isArray(I)&&I.length===2){const B=I[0]?`'${I[0]}'`:"NULL",E=I[1]?`'${I[1]}'`:"NULL";return`${C} BETWEEN ${B} AND ${E}`}else if((S.operator==="in"||S.operator==="not in")&&Array.isArray(I)){const B=I.map(E=>E?`'${E}'`:"NULL").join(", ");return`${C} ${O} (${B})`}else typeof I=="string"||I instanceof Date?I=`'${I}'`:Array.isArray(I)&&I.length>0&&(I=`'${I[0]}'`);else if(["in","not in"].includes(S.operator)){let B=[];Array.isArray(I)?B=I.map(E=>typeof E=="string"?`'${E}'`:String(E)):typeof I=="string"?B=I.split(",").map(E=>{const w=E.trim();return S.field.dataType==="string"?`'${w}'`:w}):typeof I=="number"&&(B=[String(I)]),I=`(${B.join(", ")})`}switch(O){case"contains":return typeof I=="string"?`${C} LIKE '%${I.replace(/'/g,"")}'`:`${C} LIKE '%${String(I)}'`;case"startsWith":return typeof I=="string"?`${C} LIKE '${I.replace(/'/g,"")}%'`:`${C} LIKE '${String(I)}%'`;case"endsWith":return typeof I=="string"?`${C} LIKE '%${I.replace(/'/g,"")}'`:`${C} LIKE '%${String(I)}'`;case"isNull":return`${C} IS NULL`;case"isNotNull":return`${C} IS NOT NULL`;default:return`${C} ${O} ${I}`}},v=S=>{const C=S.conditions.map(D),O=S.groups.map(w=>v(w)),I=[...C,...O].filter(Boolean);if(I.length===0)return"";const B=I.join(` ${S.logicalOperator} `),E=I.length>1?`(${B})`:B;return S.negate?`NOT ${E}`:E};return v(N)},T=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:u,addGroup:m,removeCondition:h,removeGroup:x,updateCondition:g,updateConditionFields:b,updateGroupOperator:p,updateGroupNegate:j,reorderConditions:f,reorderGroups:y,generateSQLPreview:k,hasAnyFilters:T}}function Ql({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Jl=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(s.File,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Xl=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function Zl({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[o,c]=A.useState(!1),i=A.useMemo(()=>{const d={};return a.forEach(u=>{const m=Xl(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[a]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ql,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Jl(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((x,g)=>e.jsxs(s.CommandItem,{value:x.id,onSelect:()=>{n(x),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===x.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:x.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:x.description&&e.jsx("span",{children:x.description})})]})]},x.id+g))]},`${d}-${m}`))},d))})]})})]})}function Ls(t){var p;const n=s.useEditorStore(j=>j.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(j=>j.card.config),o=l==null?void 0:l.joinPlan,c={...t,alias:t.name,label:"value",role:"groupby"},i={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...c,role:"sortby",direction:"asc"},u={joinPlan:o,groupByColumns:[c],metricColumns:[i],sortByColumns:[d]},m=((p=n.dataSource)==null?void 0:p.connectionId)||n.connectionId,{data:h,isPending:x,error:g}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:m,cardConfig:u,cardDataSource:n.dataSource})}catch(j){console.log(t),console.error("error",j)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:x,error:g}}function eo({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[o,c]=Ee.useState(!1),{filterValues:i}=Ls(t),d=m=>{a(n.filter(h=>h!==m))},u=m=>{n.includes(m)?a(n.filter(h=>h!==m)):a([...n,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(m=>{const h=i.find(x=>x.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:x=>{x.key==="Enter"&&d(m)},onMouseDown:x=>{x.preventDefault(),x.stopPropagation()},onClick:x=>{x.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function so({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=Ls(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:o.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function to({value:t,operator:n,onChange:a,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),o=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=A.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(u&&m)return{from:u,to:m}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:m}}}},[t,n]),i=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),a([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),a([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const ao=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],no=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ro=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],lo=["=","!=","isNull","isNotNull"],oo=["between","isNull","isNotNull"],io={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null"};function Js(t){return io[t]||s.titleCase(t)}function co(t){switch(t){case"string":return no;case"number":return ro;case"boolean":return lo;case"date":return oo;default:return ao}}function qt({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:x,transition:g,isDragging:b}=s.useSortable({id:t.id}),{isPending:p,error:j}=Ls(t.field),f={transform:s.CSS.Transform.toString(x),transition:g};return e.jsxs("div",{ref:h,style:f,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:y=>c(a,y),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(Zl,{value:t.field,onValueChange:y=>{const k=y,T=s.getDataType(k.dataType)==="date";d(a,t.id,{field:k,value:"",operator:T?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:y=>{y==="in"||y==="not in"?d(a,t.id,{operator:y,value:[]}):y==="isNull"||y==="isNotNull"?d(a,t.id,{operator:y,value:null}):d(a,t.id,{operator:y,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Js(t.operator):""})}),e.jsx(s.SelectContent,{children:co(s.getDataType(t.field.dataType)).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y,children:Js(y)},y))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?p?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):j?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(eo,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(y=>typeof y=="string")?t.value:[],onChange:y=>d(a,t.id,{value:y}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:y=>d(a,t.id,{value:y.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(so,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:y=>d(a,t.id,{value:y}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:y=>d(a,t.id,{value:y==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(to,{value:t.value,operator:t.operator,onChange:y=>d(a,t.id,{value:y}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:y=>l(a,t.id,"value",y.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function uo({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:x,availableFields:g,renderFilterGroup:b,updateConditionFields:p}){const{attributes:j,listeners:f,setNodeRef:y,transform:k,transition:T,isDragging:N}=s.useSortable({id:t.id}),D={transform:s.CSS.Transform.toString(k),transition:T},v=C=>{const{active:O,over:I}=C;if(I&&O.id!==I.id){const B=t.conditions.findIndex(w=>w.id===O.id),E=t.conditions.findIndex(w=>w.id===I.id);B!==-1&&E!==-1&&u(t.id,B,E)}},S=C=>{const{active:O,over:I}=C;if(I&&O.id!==I.id&&a){const B=t.groups.findIndex(w=>w.id===O.id),E=t.groups.findIndex(w=>w.id===I.id);B!==-1&&E!==-1&&m(a,B,E)}};return e.jsxs("div",{ref:y,style:D,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${N?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...j,...f,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:C=>r(t.id,C),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&o(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:v,children:e.jsx(s.SortableContext,{items:t.conditions.map(C=>C.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((C,O)=>e.jsx(qt,{condition:C,index:O,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:p},C.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:S,children:e.jsx(s.SortableContext,{items:t.groups.map(C=>C.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(C=>b(C,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function mo({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:x,updateConditionFields:g,updateGroupOperator:b,updateGroupNegate:p,reorderConditions:j,reorderGroups:f,generateSQLPreview:y,hasAnyFilters:k,setCurrentFilters:T}=Kl({initialFilters:t,availableFields:n}),N=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[D,v]=A.useState(!1),S=(I,B,E)=>{const w=M=>M.id===I?{...M,conditions:M.conditions.map(F=>F.id===B?{...F,field:E,dataType:E.dataType}:F)}:{...M,groups:M.groups.map(w)};T(w(o))},C=(I,B=0,E)=>B===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:N,collisionDetection:s.closestCenter,onDragEnd:w=>{const{active:M,over:F}=w;if(F&&M.id!==F.id){const R=I.conditions.findIndex(P=>P.id===M.id),L=I.conditions.findIndex(P=>P.id===F.id);R!==-1&&L!==-1&&j(I.id,R,L)}},children:e.jsx(s.SortableContext,{items:I.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:I.conditions.map((w,M)=>e.jsx(qt,{condition:w,index:M,groupId:I.id,groupLogicalOperator:I.logicalOperator,onUpdateCondition:x,onUpdateField:S,onRemoveCondition:m,onUpdateGroupOperator:b,availableFields:c,updateConditionFields:g},w.id))})}),e.jsx(s.DndContext,{sensors:N,collisionDetection:s.closestCenter,onDragEnd:w=>{const{active:M,over:F}=w;if(F&&M.id!==F.id){const R=I.groups.findIndex(P=>P.id===M.id),L=I.groups.findIndex(P=>P.id===F.id);R!==-1&&L!==-1&&f(I.id,R,L)}},children:e.jsx(s.SortableContext,{items:I.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:I.groups.map(w=>C(w,B+1,I.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(I.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),D&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(I.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},I.id):e.jsx(uo,{group:I,depth:B,parentGroupId:E,onUpdateGroupOperator:b,onUpdateGroupNegate:p,onRemoveGroup:h,onUpdateCondition:x,onUpdateField:S,onRemoveCondition:m,onReorderConditions:j,onReorderGroups:f,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:C,updateConditionFields:g},I.id),O=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):C(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{id:"advanced-mode",checked:D,onCheckedChange:I=>v(I)}),e.jsx(s.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),k&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:y(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),O>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(k?o:null),children:"Apply Filters"})]})]})}function ho({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=u=>{a(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(mo,{filters:n,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function xo({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[l,o]=A.useState(null),c=s.useEditorStore(b=>b.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],u=A.useCallback(b=>b.startsWith("card-")?null:b.startsWith("source-")||n.find(p=>p.id===b)?"source":a("groupBy").find(p=>p.id===b)?"groupBy":a("metrics").find(p=>p.id===b)?"metrics":a("pivotBy").find(p=>p.id===b)?"pivotBy":a("sortBy").find(p=>p.id===b)?"sortBy":null,[n,a]),m=A.useCallback(b=>{o(b.active.id)},[]),h=A.useCallback(b=>{const{active:p,over:j}=b;if(!j||!t){o(null);return}const f=p.id,y=j.id,k=u(f),T=u(y)||y;if(T==="sortBy"){if(k==="source"){const N=n.find(v=>v.id===f);if(!N){o(null);return}if(!(a("groupBy").some(v=>v.name===N.name&&v.qualifiedEntityName===N.qualifiedEntityName)||a("metrics").some(v=>v.name===N.name&&v.qualifiedEntityName===N.qualifiedEntityName))){o(null);return}}else if(k==="pivotBy"){o(null);return}else if(k!=="groupBy"&&k!=="metrics"&&k!=="sortBy"){o(null);return}}if(k==="source"&&T==="sortBy"){const N=[...n].find(S=>S.id===f);if(!N){o(null);return}const D=a("sortBy");if(s.fieldAlreadyExists(N,D)){o(null);return}const v=s.getNewField(N,"sortBy",D);o(null),r("sortBy",[...D,v]);return}if(k==="source"&&T!=="source"&&T!=="sortBy"){const N=[...n].find(C=>C.id===f);if(!N){o(null);return}const D=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(D.length>0){const C=D[0].qualifiedEntityName;if(!C){o(null);return}if(C!==N.qualifiedEntityName&&N.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(C,N.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const v=a(T);if(s.fieldAlreadyExists(N,v)){o(null);return}const S=s.getNewField(N,T,v);o(null),r(T,[...v,S]);return}if(k&&T&&k!=="source"&&T!=="source"&&k!==T){const N=a(k),D=a(T),v=N.find(O=>O.id===f);if(!v){o(null);return}const S=s.getNewField(v,T,D);if(o(null),T==="sortBy"){s.fieldAlreadyExists(v,D)||r(T,[...D,S]);return}const C=N.filter(O=>O.id!==f);r(k,C),r(T,[...D,S]);return}if(k&&T&&k===T&&k!=="source"){const N=a(k),D=N.findIndex(S=>S.id===f),v=N.findIndex(S=>S.id===y);if(D!==v){const S=s.arrayMove(N,D,v);r(k,S)}}o(null)},[t,n,a,r,u,i]),x=l?d.find(b=>b.id===l):null;return{activeId:l,activeField:x,handleDragStart:m,handleDragEnd:h}}function po({dashboardFilterCount:t=0,cardFilterCount:n=0,clickFilterCount:a=0,onClick:r,className:l,showIcon:o=!0}){const c=t+n+a,i=c>0,d=t>0,u=n>0,m=a>0,h=e.jsxs(e.Fragment,{children:[o&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),x=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",l),children:h});return i?e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:x}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"p-2 text-xs",children:e.jsxs("div",{className:"space-y-1.5",children:[d&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-purple-500"}),e.jsxs("span",{children:[t," Dashboard filter",t!==1?"s":""]})]}),u&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),e.jsxs("span",{children:[n," Card filter",n!==1?"s":""]})]}),m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-gray-500"}),e.jsxs("span",{children:[a," Click filter",a!==1?"s":""]})]})]})})]})}):x}function fo({activeView:t,onViewChange:n}){const a=s.useEditorStore(c=>c.card),{config:r}=A.useContext(s.SemaphorContext).tokenProps,l=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:o}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:c=>n(c),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),a.type!=="kpi"&&l&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",o&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:o?"Error":"Info"})]})})}const go=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function jo(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=A.useState(!1),[l,o]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:go.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function bo({isOpen:t,onClose:n}){const a=it(n,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=A.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function vo(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{currentUser:a}=s.useCurrentUserInfo(),r=s.useMutation({mutationFn:async l=>{if(!(t!=null&&t.accessToken))throw new Error("No authentication token available");const c=`${n.apiServiceUrl||""}/v1/feedback`,i={...l,user:a,tokenContext:n},d=await s.postRequestRegular(c,t.accessToken,i,"POST");if(!d||!d.success)throw new Error((d==null?void 0:d.error)||"Failed to send feedback");return d},onSuccess:l=>{s.ue.success(`Feedback sent successfully! Issue: ${l.issueNumber}`,{duration:5e3})},onError:l=>{console.error("Feedback submission error:",l),s.ue.error("Failed to send feedback. Please try again later.",{duration:5e3})}});return{sendFeedback:r.mutate,sendFeedbackAsync:r.mutateAsync,isLoading:r.isPending,isSuccess:r.isSuccess,isError:r.isError,error:r.error,data:r.data,reset:r.reset}}function yo(t,n,a){return{category:t,userMessage:a,systemState:n,metadata:{url:window.location.href,userAgent:navigator.userAgent,timestamp:new Date().toISOString(),viewport:`${window.innerWidth}x${window.innerHeight}`}}}function No({open:t,onOpenChange:n,feedbackData:a}){var p,j,f,y,k,T;const[r,l]=A.useState(""),[o,c]=A.useState(!1),{sendFeedback:i,isLoading:d,isSuccess:u,data:m,reset:h}=vo(),x=()=>{const N={...a,userMessage:r.trim()||void 0};i(N)},g=()=>{l(""),c(!1),h(),n(!1)},b={category:a.category,error:{message:(p=a.systemState)==null?void 0:p.errorMessage,sql:(j=a.systemState)==null?void 0:j.generatedSql,errorSql:(f=a.systemState)==null?void 0:f.errorSql},cardConfig:(y=a.systemState)==null?void 0:y.cardConfig,dataSource:(k=a.systemState)==null?void 0:k.dataSource,filters:(T=a.systemState)==null?void 0:T.dashboardFilters,metadata:a.metadata};return e.jsx(s.Dialog,{open:t,onOpenChange:g,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:u?"Feedback Sent Successfully":"Report Query Generation Issue"}),e.jsx(s.DialogDescription,{children:u?`Your feedback has been submitted with issue number: ${m==null?void 0:m.issueNumber}`:"Help us improve by reporting this query generation issue. Your feedback will be sent to our support team."})]}),!u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"message",children:"Additional Information (Optional)"}),e.jsx(s.Textarea,{id:"message",placeholder:"Please describe what you were trying to do when this error occurred...",value:r,onChange:N=>l(N.target.value),className:"min-h-[100px] resize-none ring-inset focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",disabled:d})]}),e.jsxs(s.Collapsible,{open:o,onOpenChange:c,children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"flex w-full items-center justify-between p-2 hover:bg-muted",children:[e.jsx("span",{className:"text-sm font-medium",children:"View data to be sent"}),o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx(s.ScrollArea,{className:"h-[300px] w-full rounded-md border bg-muted/50 p-4",children:e.jsx("div",{className:"text-xs",children:e.jsx(s.CodeHighlighter,{code:JSON.stringify(b,null,2),language:"json"})})})})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:g,disabled:d,children:"Cancel"}),e.jsx(s.Button,{onClick:x,disabled:d,className:"min-w-[100px]",children:d?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Sending..."]}):"Send Feedback"})]})]}),u&&e.jsxs("div",{className:"flex flex-col items-center space-y-4 py-6",children:[e.jsx(ha,{className:"h-12 w-12 text-green-600"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-medium",children:"Thank you for your feedback!"}),e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Issue Number:"," ",e.jsx("span",{className:"font-mono font-medium",children:m==null?void 0:m.issueNumber})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Our support team will review your feedback and take appropriate action."})]}),e.jsx(s.Button,{onClick:g,className:"mt-4",children:"Close"})]})]})})}var Ht=(t=>(t.QUERY_GENERATION="query-generation",t))(Ht||{});function Co({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:l,filterCount:o,activeCard:c,columns:i,columnsLoading:d,columnsError:u}){var $;const m=s.useEditorStore(X=>X.card),h=s.useDashboardStore(X=>X.filterValues),x=(h==null?void 0:h.length)||0,{updateCardConfig:g,setCard:b,updateCardInFrame:p,setCardId:j,setShowAIDialog:f}=s.useEditorActions(),{updateCardId:y}=s.useDashboardActions(),[k,T]=A.useState(null),N=s.useEditorStore(X=>X.showAIDialog),[D,v]=A.useState(!1),[S,C]=A.useState(!1),[O,I]=A.useState(null),{isConsoleMode:B}=s.useDashboardPreferences(),{config:E}=A.useContext(s.SemaphorContext).tokenProps,w=(E==null?void 0:E.showInfoTab)!==!1,M=s.useEditorStore(X=>{var _;return((_=X.card.customCardPreferences)==null?void 0:_.url)&&X.card.type==="custom"}),{data:F,errorMessage:R,isLoading:L,isFetching:P,errorSql:Y,pagination:J}=s.useDashboardCardQuery(c),V=(X,_)=>{const G={...c,paginationConfig:{page:X+1,pageSize:_}};b(G),p(G)};function K(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(m.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(h||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(c.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",i.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:d?"Loading...":u?"Error loading columns":JSON.stringify(i.slice(0,5),null,2)})]})]})]})}const q=X=>{if(!m.config)return;if(!X.length){g(m.id,{...m.config,sortByColumns:[]});return}const _=m.config,G=X.map(({id:se,desc:re})=>{var ne,le;const he=(ne=_.metricColumns)==null?void 0:ne.find(de=>de.label===se),z=(le=_.groupByColumns)==null?void 0:le.find(de=>de.label===se),ee=he||z;return ee?{id:s.getFieldId("sortBy",ee),name:ee.name,dataType:ee.dataType,label:ee.label,qualifiedEntityName:ee.qualifiedEntityName,entityId:ee.entityId,entityName:ee.entityName,entityType:ee.entityType,role:"sortby",direction:re?"desc":"asc"}:null}).filter(se=>se!==null);g(m.id,{..._,sortByColumns:G})},Z=A.useMemo(()=>{var X,_;return(_=(X=m.config)==null?void 0:X.sortByColumns)==null?void 0:_.map(G=>({id:G.label,desc:G.direction==="desc"}))},[($=m.config)==null?void 0:$.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[a&&K(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&N&&e.jsx(At,{variant:"outline"}),e.jsx(fo,{activeView:t,onViewChange:n}),l&&e.jsx(po,{dashboardFilterCount:x,cardFilterCount:o,onClick:l,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(jo,{})}),N&&e.jsx(cs,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end"),children:[t==="chart"&&e.jsx(Mt,{}),!N&&e.jsx(s.IconButton,{onClick:()=>f(!N),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!D&&M&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>v(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(Lt,{})}),t==="table"&&(F==null?void 0:F.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:c,data:(F==null?void 0:F.records)||[],paginationMetadata:J,onPaginationChange:V,isLoading:L||P,onSortChange:q,sortState:Z})}),t==="info"&&w&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[B&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:m.id,onSave:X=>{const _=s.sanitizeCardId(X);if(!_){T("Card ID cannot be empty");return}const G=y(m.id,_);if(G.success){j(_);const se={...m,id:_};b(se),p(se),T(null),s.ue.success("Card ID updated successfully")}else T(G.error||"Failed to update Card ID"),s.ue.error(G.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:m.id,className:"h-5 w-5"})]}),k&&e.jsx("p",{className:"text-xs text-destructive",children:k})]}),R||Y?e.jsx(Ct,{error:R,errorSql:Y,onSendFeedback:()=>{const X=yo(Ht.QUERY_GENERATION,{cardConfig:m.config,dataSource:c.dataSource,dashboardFilters:h,errorMessage:R,errorSql:Y,generatedSql:F==null?void 0:F.sql});I(X),C(!0)}}):e.jsxs(e.Fragment,{children:[(F==null?void 0:F.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(St,{sql:F==null?void 0:F.sql,error:R,errorSql:Y})]})]})})]}),e.jsx(bo,{isOpen:D,onClose:()=>v(!1)}),O&&e.jsx(No,{open:S,onOpenChange:C,feedbackData:O})]})]})}function So({activeField:t}){const[n,a]=A.useState(!0);return A.useEffect(()=>{t&&a(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Ms,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const wo=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const n=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},a=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function Do(){var Y,J;const[t,n]=A.useState("chart"),[a,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(V=>V.showAIDialog),u=s.useDashboardStore(V=>V.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(V=>V.card.type);A.useEffect(()=>wo(),[]);const x=()=>{o(!0)},g=V=>{m(V)},b=s.useEditorStore(V=>V.frame),p=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.activeTabCardId),s.useEditorStore(V=>V.actions.getAvailableFields);const{addCard:j,removeCard:f,updateCard:y,setActiveCard:k,updateFilters:T}=s.useEditorActions(),{columns:N=[],isLoading:D,error:v}=s.useColumns(),S=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),C=p,{getFieldsForContainer:O,setFieldsForContainer:I}=As(C),{activeField:B,handleDragStart:E,handleDragEnd:w}=xo({activeCardId:b.activeCardId,sourceFields:N,getFieldsForContainer:O,setFieldsForContainer:I}),M=(V,K)=>{K&&T(V,K)},F=V=>{var K;y(V,{config:{...(K=b.cards.find(q=>q.id===V))==null?void 0:K.config,filters:void 0}})},R=N,L=V=>{if(!V)return 0;let K=V.conditions.length;return V.groups.forEach(q=>{K+=L(q)}),K},P=L(((Y=C==null?void 0:C.config)==null?void 0:Y.filters)||null);return e.jsxs(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragStart:E,onDragEnd:w,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Il,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Wl,{selectedChart:h,onChartChange:g,groupByFields:O("groupBy"),pivotByFields:O("pivotBy"),metricsFields:O("metrics"),sortByFields:O("sortBy")}),e.jsx(Co,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:x,filterCount:P,activeCard:C,dataSourceState:p.dataSource||s.EMPTY_DATA_SOURCE,columns:N,columnsLoading:D,columnsError:v,getFieldsForContainer:O,cards:b.cards,activeCardId:b.activeCardId,addCard:j,setActiveCard:k})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),C&&e.jsx(ho,{cardId:C.id,filters:((J=C.config)==null?void 0:J.filters)||null,onFiltersChange:M,onClearFilters:F,availableFields:R,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(So,{activeField:B||null})})]})}function To({authToken:t,onSave:n,onClose:a}){const r=A.useRef(null),l=s.useEditorStore(y=>y.showAIDialog),o=s.useEditorStore(y=>y.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:x,handleDragCancel:g,sensors:b}=Jn();A.useEffect(()=>{n&&d(n),a&&u(a)},[n,d,a,u]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var y,k;l?((y=r.current)==null||y.resize(40),i(!0)):(i(!1),(k=r.current)==null||k.resize(0))},[l,i]);function p(y){y<1?i(!1):l||i(!0)}function j(){return e.jsxs(e.Fragment,{children:[e.jsx(Nt,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(fl,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(qs,{})})]})]})}function f(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Do,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(qs,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:b,onDragStart:x,onDragEnd:h,onDragOver:m,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:j()})}):f()})}function ko(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(c=>c.actions),a=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),n(!1))}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(To,{onSave:l,onClose:o})})}function Eo({column:t}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{className:"shrink-0",asChild:!0,children:s.isTextDataType(t.data_type)?e.jsx(s.TextIcon,{className:"size-3 text-muted-foreground"}):s.isNumberDataType(t.data_type)?e.jsx(De,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(Le,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(ma,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})})}function Io(){const t=s.useEditorStore(o=>o.selectedDatabaseName),n=s.useEditorStore(o=>o.selectedTableName),a=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=ks();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(o.column_name)&&i.table===n&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Eo,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function Ao({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ze,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(qe,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ke,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function Mo(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useDashboardStore(f=>f.dashboard.filters)||[],{assignFilter:o}=ks(),c=s.useEditorStore(f=>f.card.dataSource),{columns:i=[],isLoading:d,error:u}=s.useColumns(),m=i.filter(f=>f.name.toLowerCase().includes(t.toLowerCase())||f.dataType.toLowerCase().includes(t.toLowerCase())||f.label&&f.label.toLowerCase().includes(t.toLowerCase())),h=f=>{const y=s.getDataType(f.dataType);return y==="number"?"metrics":(["date","string","boolean"].includes(y),"dimensions")},x=a==="all"?m:m.filter(f=>h(f)===a),g=m.filter(f=>h(f)==="dimensions").length,b=m.filter(f=>h(f)==="metrics").length,p=f=>{const y={column_name:f.name,data_type:f.dataType,label:f.label,description:f.description};o(y,"dashboard",f)};if(d)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(u)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:u.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const j=m.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:f=>n(f.target.value)})]}),j&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:f=>r(f),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:b})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[x.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),x.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),x.map(f=>{const y=l==null?void 0:l.some(k=>{var T;return k.title===f.name||((T=k.column)==null?void 0:T.includes(f.name))});return e.jsx("div",{onClick:()=>p(f),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":y}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ao,{dataType:f.dataType}),e.jsx("span",{children:f.label||f.name})]})},f.id)})]})]})}function Lo(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),n=s.useCurrentActiveCard(),a=n&&((r=n.dataSource)==null?void 0:r.selectedEntities)&&n.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:a?e.jsx(Mo,{}):e.jsx(Nt,{type:"filter",ColumnsComponent:()=>e.jsx(Io,{})})})]})}function Ro(){const t=s.useDashboardStore(r=>r.dashboard.filters),n=s.useDashboardStore(r=>r.theme),a=t==null?void 0:t.filter(r=>r.hide);return a!=null&&a.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":n==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":n==="dark"}),children:a==null?void 0:a.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Oo(){const t=s.useDashboardStore(r=>r.showFilters),n=s.useDashboardStore(r=>r.isVisualEditing),a=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":n,"flex grow overflow-auto":!n}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[a&&e.jsx(Ro,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Lo,{})})]})}function Fo(){const t=s.useDashboardStore(l=>l.dashboard),n=s.useDashboardStore(l=>l.actions.setDashboard),a=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!a}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),n(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function Wt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,n)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},n))})]})})}const Bo=t=>{const n=s.useDashboardStore(l=>l.isVisualEditing),a=s.useDashboardStore(l=>l.selectedFrameId),r=s.useEditorStore(l=>l.frame);return!!(n&&a&&(r==null?void 0:r.visualId)===t)};function Po({visual:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var v,S,C;const{selectVisual:x}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),b=Bo(t.id),{isConsoleMode:p}=s.useDashboardPreferences();s.useDashboardStore(O=>O.actions.setIsDashboardPanelOpen);const j=A.useRef(null),[f,y]=A.useState(!1),[k,T]=A.useState(!1);A.useEffect(()=>{a?(y(!0),T(!0)):k&&(y(!1),T(!1))},[a,k]),A.useEffect(()=>{b&&j.current&&j.current.scrollIntoView({behavior:"smooth",block:"center"})},[b]);const N=()=>e.jsx(os,{className:"h-4 w-4"}),D=()=>{x(t),c==null||c(t)};return e.jsx(s.Card,{ref:j,className:s.cn("group cursor-pointer border-border/50 p-3 transition-colors hover:bg-accent/50",g&&"ring-1 ring-primary",b&&"ring-1 ring-purple-500"),onClick:D,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children:N()}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:O=>i==null?void 0:i(t.id,{title:O}),isEditable:t.ownership.isOwner&&g,isPending:r,placeholder:"Untitled Visual",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"mr-1 h-2.5 w-2.5"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:O=>i==null?void 0:i(t.id,{description:O}),isEditable:t.ownership.isOwner&&g,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2"})]}),e.jsxs("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex flex-shrink-0 items-center gap-1"),onClick:O=>O.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:O=>{O.stopPropagation(),o(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:f,onOpenChange:y,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:O=>{O.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:O=>{O.preventDefault(),O.stopPropagation(),u(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:O=>{O.stopPropagation(),console.log("Edit visual",t),c==null||c(t)},children:[e.jsx(Pa,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:O=>{O.stopPropagation(),m(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:O=>{O.stopPropagation(),d(t)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((v=t.ownership.createdBy)==null?void 0:v.type)==="tenant"||((S=t.ownership.createdBy)==null?void 0:S.type)==="organization"&&p)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((C=t.ownership.createdBy)==null?void 0:C.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:h(t.lastModified)})]})]})]})]})]})]})},t.id)}function zo(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(!1),[m,h]=A.useState(null),[x,g]=A.useState(!1),[b,p]=A.useState(null),[j,f]=A.useState(null),{setIsDashboardEditing:y,setIsVisualEditing:k}=s.useDashboardActions(),{handleEditLibraryVisual:T,handleAddLibraryVisual:N}=Oe(),{resources:D,isLoading:v,isError:S,createResource:C,updateResource:O,deleteResource:I,duplicateResource:B,isCreating:E,isDeleting:w}=s.useVisualManagement(()=>{g(!1),p(null)},()=>{r(!1),o(""),i("")});s.useCurrentUserInfo();const M=D.filter(G=>{var se,re;return((se=G==null?void 0:G.title)==null?void 0:se.toLowerCase().includes(t.toLowerCase()))||((re=G==null?void 0:G.description)==null?void 0:re.toLowerCase().includes(t.toLowerCase()))}),F=G=>new Date(G).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),R=()=>{l.trim()&&C({title:l,description:c,isPrivate:!1})},L=G=>{p(G),g(!0)},P=()=>{b&&I(b.id)},{startUpdating:Y,stopUpdating:J,isUpdating:V}=s.useResourceUpdateState(),K=(G,se)=>{const re=se.title!==void 0?"title":"description";Y(G,re),O({resourceId:G,data:se},{onSuccess:()=>{J(G,re)},onError:()=>{J(G,re)}})},q=G=>{f(G),B(G,{onSettled:()=>f(null)})},Z=G=>{T(G)},$=G=>{N(G)},X=G=>{const se=D.find(re=>re.id===G);se&&O({resourceId:G,data:{isPrivate:!se.isPrivate}})},_=G=>{h(G),u(!0)};return v?e.jsx(Wt,{}):S?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:a?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:G=>o(G.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:G=>i(G.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:R,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||E,children:E?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:E,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"w-full bg-primary text-primary-foreground hover:bg-primary/90",disabled:E,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),E?"Creating...":"Create New Visual"]})}),D&&D.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:G=>n(G.target.value),className:"h-9"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:M.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(os,{className:"mx-auto h-12 w-12 text-muted-foreground/50"})}),e.jsx("h3",{className:"mb-1 font-medium text-foreground",children:t?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:t?"Try adjusting your search":"Create your first visual component to get started"}),!t&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Visual"]})]}):M.map(G=>e.jsx(Po,{visual:G,onAddVisual:$,onEditVisual:Z,onUpdateVisual:K,onDeleteClick:L,onDuplicateVisual:q,onTogglePrivacy:X,onShareVisual:_,isDeleting:w,isDuplicating:j===G.id,isTitleUpdating:V(G.id,"title"),isDescriptionUpdating:V(G.id,"description"),formatDate:F},G.id))})}),d&&m&&e.jsx(is,{resource:m,resourceType:s.ResourceType.VISUAL,onClose:()=>{u(!1),h(null)}}),e.jsx(s.AlertDialog,{open:x,onOpenChange:G=>{!G&&w||(g(G),G||p(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',b==null?void 0:b.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:w,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:G=>{G.preventDefault(),G.stopPropagation(),P()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:w,children:[w?e.jsx(s.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):e.jsx(s.Trash2,{className:"mr-2 h-3.5 w-3.5"}),w?"Deleting...":"Delete"]})]})]})})]})}function Vo({dashboard:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var N,D,v;const{selectDashboard:x}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences(),[p,j]=A.useState(!1),[f,y]=A.useState(!1);s.useDashboardStore(S=>S.actions.setIsDashboardPanelOpen),A.useEffect(()=>{a?(j(!0),y(!0)):f&&(j(!1),y(!1))},[a,f]);const k=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),T=()=>{x(t),o(t.id),h==null||h(t.id)};return e.jsx(s.Card,{className:s.cn("group cursor-pointer border-border/50 p-3 transition-colors hover:bg-accent/50",g&&"ring-1 ring-primary"),onClick:T,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children:k()}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:S=>c==null?void 0:c(t.id,{title:S}),isEditable:t.permissions.canEdit&&g,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"mr-1 h-2.5 w-2.5"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:S=>c==null?void 0:c(t.id,{description:S}),isEditable:t.permissions.canEdit&&g,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2"})]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0"),onClick:S=>S.stopPropagation(),children:e.jsxs(s.DropdownMenu,{modal:!1,open:p,onOpenChange:j,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.preventDefault(),S.stopPropagation(),d(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),u(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),i(t)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((N=t.ownership.createdBy)==null?void 0:N.type)==="tenant"||((D=t.ownership.createdBy)==null?void 0:D.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((v=t.ownership.createdBy)==null?void 0:v.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:m(t.lastModified)})]})]})]})]})})]})},t.id)}function _o({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function Uo(t){const[n,a]=A.useState(""),[r,l]=A.useState(!1),[o,c]=A.useState(""),[i,d]=A.useState(""),[u,m]=A.useState(!1),[h,x]=A.useState(null),[g,b]=A.useState(!1),[p,j]=A.useState(null),[f,y]=A.useState(null),k=s.useManagementStore(z=>z.lastSelectedDashboard),T=s.useManagementStore(z=>z.selectedDashboard),N=s.useManagementStore(z=>z.actions.selectDashboard),D=s.useManagementStore(z=>z.actions.clearSelectedDashboard),{tokenProps:v,id:S}=s.useSemaphorContext(),{permissions:C}=s.useRoleAwareDisplayPreferences(),{resources:O,isLoading:I,isError:B,createResource:E,updateResource:w,deleteResource:M,duplicateResource:F,isCreating:R,isDeleting:L}=s.useDashboardManagement(()=>{b(!1);const z=p==null?void 0:p.id;j(null),(T==null?void 0:T.id)===z&&(!(v!=null&&v.dashboard_id)&&!S?D():k&&k.id!==z&&N(k))},()=>{l(!1),c(""),d("")}),{currentUser:P}=s.useCurrentUserInfo(),Y=O.filter(z=>{var ee,ne;return((ee=z==null?void 0:z.title)==null?void 0:ee.toLowerCase().includes(n.toLowerCase()))||((ne=z==null?void 0:z.description)==null?void 0:ne.toLowerCase().includes(n.toLowerCase()))}),J=z=>new Date(z).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),V=()=>{o.trim()&&E({title:o,description:i,isPrivate:!1})},K=z=>{var ee;(ee=t.onLoadDashboard)==null||ee.call(t,z)},q=z=>{j(z),b(!0)},Z=()=>{p&&M(p.id)},$=z=>{y(z),F(z,{onSettled:()=>y(null)})},{startUpdating:X,stopUpdating:_,isUpdating:G}=s.useResourceUpdateState(),se=(z,ee)=>{const ne=ee.title!==void 0?"title":"description";X(z,ne),w({resourceId:z,data:ee},{onSuccess:()=>{_(z,ne)},onError:()=>{_(z,ne)}})},re=z=>{const ee=O.find(ne=>ne.id===z);ee&&w({resourceId:z,data:{isPrivate:!ee.isPrivate}})},he=z=>{x(z),P==null||P.type,m(!0)};return I?e.jsx(Wt,{}):B?e.jsx(_o,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[C.canCreateDashboards&&e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:o,onChange:z=>c(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:z=>d(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:V,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||R,children:R?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:R,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"w-full bg-primary text-primary-foreground hover:bg-primary/90",disabled:R,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),R?"Creating...":"Create New Dashboard"]})}),O&&O.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:n,onChange:z=>a(z.target.value),className:"h-9"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:Y.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.ChartColumn,{className:"mx-auto h-12 w-12 text-muted-foreground/50"})}),e.jsx("h3",{className:"mb-1 font-medium text-foreground",children:n?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:n?"Try adjusting your search":C.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),C.canCreateDashboards&&!n&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>l(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Dashboard"]})]}):Y.map(z=>e.jsx(Vo,{dashboard:z,isDeleting:L,isDuplicating:f===z.id,isTitleUpdating:G(z.id,"title"),isDescriptionUpdating:G(z.id,"description"),onLoadDashboard:K,onEditDashboard:t.onEditDashboard,onUpdateDashboard:se,onDeleteClick:q,onDuplicateDashboard:$,onTogglePrivacy:re,onShareDashboard:he,formatDate:J,onDashboardItemClick:t.onDashboardItemClick},z.id))})}),u&&h&&e.jsx(is,{resource:h,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{m(!1),x(null)}}),e.jsx(s.AlertDialog,{open:g,onOpenChange:z=>{!z&&L||(b(z),z||j(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',p==null?void 0:p.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:L,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:z=>{z.preventDefault(),z.stopPropagation(),Z()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:L,children:[L?e.jsx(s.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):e.jsx(s.Trash2,{className:"mr-2 h-3.5 w-3.5"}),L?"Deleting...":"Delete"]})]})]})})]})}function Kt({isOpen:t,onClose:n,className:a,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(k=>k.dashboard);const{setDashboard:o,addSheet:c}=s.useDashboardStore(k=>k.actions),{currentUser:i}=s.useCurrentUserInfo(),d=i,{permissions:u}=s.useRoleAwareDisplayPreferences(),m=(u.canAccessVisuals,"dashboards"),[h,x]=s.useLocalStorageState("resource-management-active-tab",m),g=u.canAccessVisuals?h:"dashboards",b=l==="overlay",p=it(n,{enabled:t&&b}),j=s.cn("flex h-full flex-col border-r bg-background",b?s.cn("absolute inset-y-0 left-0 z-[51] w-96 shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"pointer-events-none -translate-x-full"):"w-full max-w-[28rem] min-w-[18rem] overflow-hidden shadow-sm",a),f=k=>{},y=k=>{console.log("Editing dashboard:",k)};return e.jsx(s.TooltipProvider,{children:(!b||t)&&e.jsxs("div",{ref:p,className:j,children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border p-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:d&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-full bg-primary/10",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:d.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:d.name}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:u.canCreateDashboards?"default":"secondary",className:"cursor-help text-xs",children:u.canCreateDashboards?e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-1 h-3 w-3"}),"Power User"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Viewer"]})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email}),d.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(d.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",d.id]})]})})]})})]})]})}),e.jsx(s.IconButton,{className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",onClick:n,tooltip:"Close Sidebar",children:e.jsx(Ba,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:g,onValueChange:u.canAccessVisuals?x:void 0,className:"flex h-9 grow flex-col",children:[u.canAccessVisuals?e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}):e.jsx("div",{className:"px-4 pb-0 pt-4",children:e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Dashboards"})}),e.jsx(s.TabsContent,{value:"dashboards",className:"mt-4 flex-1",children:e.jsx(Uo,{onLoadDashboard:f,onEditDashboard:y,onDashboardItemClick:r})}),u.canAccessVisuals&&e.jsx(s.TabsContent,{value:"visuals",className:"mt-4 flex-1",children:e.jsx(zo,{})})]})})]})})}function Go({showControls:t=!1,showFooter:n=!0,...a}){const r=s.useDashboardStore(x=>x.isDashboardPanelOpen);s.useDashboardStore(x=>x.isVisualEditing);const l=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),o=20,c=20,i=30,d=r,u=A.useRef(null),m=A.useRef(null);A.useEffect(()=>{u.current&&m.current&&(r?(u.current.resize(o),m.current.resize(100-o)):(u.current.resize(0),m.current.resize(100)))},[r]);const{preferences:h}=a;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:h,children:[e.jsx(Fo,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx($n,{}),e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",className:"flex grow overflow-hidden",children:[e.jsx(s.ResizablePanel,{ref:u,className:s.cn("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?o:0,minSize:d?c:0,maxSize:d?i:0,children:e.jsx(Kt,{isOpen:r,onClose:()=>l(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{withHandle:d,className:s.cn("w-1",{"w-0":!d})}),e.jsx(s.ResizablePanel,{ref:m,className:"flex min-w-0 flex-1",defaultSize:d?100-o:100,minSize:d?40:100,children:e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(ko,{}),e.jsx(Oo,{})]})})]})]})]})})]})})}exports.AdvancedModeToggle=vt;exports.DashboardPlus=Go;exports.ResourceManagementPanel=Kt;exports.ScheduleDashboard=nt;exports.SelectComponent=Be;exports.ShareDialog=is;exports.VisualBadge=pt;exports.VisualEditingControls=bt;exports.cleanCard=at;exports.getDashbaordStateWithoutData=as;
|