react-semaphor 0.1.26 → 0.1.28
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-BZ8k_sGe.js → dashboard-plus-9g7duCXD.js} +11 -11
- package/dist/chunks/{dashboard-plus-qMRXHdYf.js → dashboard-plus-CX2koYDg.js} +2190 -2187
- package/dist/chunks/{index-Bo0bvCRT.js → index-BjZT0XXz.js} +160 -160
- package/dist/chunks/{index-CE57mw6l.js → index-Dk-32lGT.js} +15092 -15052
- 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/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/dist/types/dashboard.d.ts +1 -0
- package/dist/types/main.d.ts +1 -0
- package/dist/types/surfboard.d.ts +1 -0
- package/dist/types/types.d.ts +1 -0
- 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-BjZT0XXz.js"),k=require("react"),Vt=require("react-dom");function zt(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 ss=zt(k);/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -53,12 +53,12 @@
|
|
|
53
53
|
*
|
|
54
54
|
* This source code is licensed under the ISC license.
|
|
55
55
|
* See the LICENSE file in the root directory of this source tree.
|
|
56
|
-
*/const
|
|
56
|
+
*/const Qt=s.createLucideIcon("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]);/**
|
|
57
57
|
* @license lucide-react v0.453.0 - ISC
|
|
58
58
|
*
|
|
59
59
|
* This source code is licensed under the ISC license.
|
|
60
60
|
* See the LICENSE file in the root directory of this source tree.
|
|
61
|
-
*/const
|
|
61
|
+
*/const Ht=s.createLucideIcon("EyeClosed",[["path",{d:"m15 18-.722-3.25",key:"1j64jw"}],["path",{d:"M2 8a10.645 10.645 0 0 0 20 0",key:"1e7gxb"}],["path",{d:"m20 15-1.726-2.05",key:"1cnuld"}],["path",{d:"m4 15 1.726-2.05",key:"1dsqqd"}],["path",{d:"m9 18 .722-3.25",key:"ypw2yx"}]]);/**
|
|
62
62
|
* @license lucide-react v0.453.0 - ISC
|
|
63
63
|
*
|
|
64
64
|
* This source code is licensed under the ISC license.
|
|
@@ -88,7 +88,7 @@
|
|
|
88
88
|
*
|
|
89
89
|
* This source code is licensed under the ISC license.
|
|
90
90
|
* See the LICENSE file in the root directory of this source tree.
|
|
91
|
-
*/const
|
|
91
|
+
*/const He=s.createLucideIcon("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
92
92
|
* @license lucide-react v0.453.0 - ISC
|
|
93
93
|
*
|
|
94
94
|
* This source code is licensed under the ISC license.
|
|
@@ -178,7 +178,7 @@
|
|
|
178
178
|
*
|
|
179
179
|
* This source code is licensed under the ISC license.
|
|
180
180
|
* See the LICENSE file in the root directory of this source tree.
|
|
181
|
-
*/const
|
|
181
|
+
*/const Oe=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"}]]);/**
|
|
182
182
|
* @license lucide-react v0.453.0 - ISC
|
|
183
183
|
*
|
|
184
184
|
* This source code is licensed under the ISC license.
|
|
@@ -188,7 +188,7 @@
|
|
|
188
188
|
*
|
|
189
189
|
* This source code is licensed under the ISC license.
|
|
190
190
|
* See the LICENSE file in the root directory of this source tree.
|
|
191
|
-
*/const
|
|
191
|
+
*/const Ie=s.createLucideIcon("Share2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]);/**
|
|
192
192
|
* @license lucide-react v0.453.0 - ISC
|
|
193
193
|
*
|
|
194
194
|
* This source code is licensed under the ISC license.
|
|
@@ -253,13 +253,13 @@
|
|
|
253
253
|
*
|
|
254
254
|
* This source code is licensed under the ISC license.
|
|
255
255
|
* See the LICENSE file in the root directory of this source tree.
|
|
256
|
-
*/const ya=s.createLucideIcon("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);function Na(){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(ga,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(ca,{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 Ke(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 c;return{...l,cards:(c=l.cards)==null?void 0:c.map(d=>Ys(d))}})}})}}function Ys(t){return{...t,customCfg:Ca(t.customCfg),data:[]}}function Ca(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 Sa(t,n,a,r,l){if(!l)return null;const c=JSON.stringify(a),d=`${t}/v1/lens`;return await s.postRequest(d,l,{name:n,template:c,filterValues:r,operation:"create"})}async function ts(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:c,isDefault:d,shared:o}=n,i=`${t}/v1/lens`;return await s.postRequest(i,a,{lensId:r,template:l,filterValues:c,isDefault:d,shared:o,operation:"update"})}async function wa(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function Da(){const[t,n]=k.useState(""),[a,r]=k.useState(!1),l=s.useDashboardStore(j=>j.lenses),{setLenses:c,setSelectedLensId:d}=s.useDashboardActions(),[o,i]=k.useState(!1),[u,m]=k.useState(!1),x=s.useDashboardStore(j=>j.dashboard),h=s.useDashboardStore(j=>j.filterValues),{authToken:p,tokenProps:b}=s.useSemaphorContext();async function f(){i(!0);const j=Ke(x),N=await Sa(b.apiServiceUrl,t,j,h,p==null?void 0:p.accessToken);N&&(c([...l||[],N]),d(N.id),m(!1)),i(!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:f,disabled:o,children:o?"Creating...":"Add"})})]})]})}function Ta(){const[t,n]=k.useState(!1),a=s.useDashboardStore(x=>x.lenses),r=s.useDashboardStore(x=>x.selectedLensId),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),{authToken:d,tokenProps:o}=s.useSemaphorContext();async function i(x){c(x)}async function u(x){if(await wa(o.apiServiceUrl,x,d==null?void 0:d.accessToken)){const p=a==null?void 0:a.filter(b=>b.id!==x);l(p||[]),c("original")}}async function m(x){const h=a==null?void 0:a.map(f=>f.id===x.id?{...f,isDefault:!x.isDefault}:{...f,isDefault:!1});l(h||[]);const p={...x,isDefault:!x.isDefault};await ts(o.apiServiceUrl,p,d==null?void 0:d.accessToken);const b=a==null?void 0:a.find(f=>f.isDefault);if(b&&b.id!==x.id){const f={...b,isDefault:!1};await ts(o.apiServiceUrl,f,d==null?void 0:d.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(ea,{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:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(x=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:x.id,children:[e.jsx("p",{children:x.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),m(x)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!x.isDefault,"text-green-500":x.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),u(x.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},x.id))]})]})]})}function ka({iconClassName:t}){const[n,a]=k.useState(!1),[r,l]=k.useState(""),[c,d]=k.useState(!1),o=s.useDashboardStore(x=>x.isDownloadingPdf),{tokenProps:i}=s.useSemaphorContext();async function u(){const x=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(i.apiServiceUrl),s.ue.dismiss(x),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(h){s.ue.dismiss(x),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",h)}}async function m(){if(!r)return;a(!1),l(""),d(!1);const x=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(i.apiServiceUrl,r),s.ue.dismiss(x),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(h){s.ue.dismiss(x),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",h)}}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:o,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:c?"text":"password",value:r,onChange:x=>l(x.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:x=>{x.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:()=>d(!c),children:c?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 qs({triggerButtonClassName:t}){const[n,a]=k.useState(!1),r=s.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.id}),l=s.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.title}),c=s.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.sheets}),d=s.useDashboardStore(o=>o.selectedSheetId);return c==null||c.find(o=>o.id===d),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 He({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 Ie({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:c=!0}){var i;const d=((i=a.find(u=>u.value===t))==null?void 0:i.label)||t,o=a.filter(u=>u.value!==t);return c?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:d})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:o.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:d})}function Ks({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(c=>a(c.id)),className:"h-7 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(c=>{const d=t.find(i=>i.id===c.id),o=l(c.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[c.name,e.jsx(Ie,{currentRole:(d==null?void 0:d.role)||"VIEWER",onRoleChange:i=>r(c.id,i),roleOptions:o}),e.jsx("button",{onClick:()=>a(c.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},c.id)})}),e.jsx(s.Separator,{})]})}function Hs({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 Qs({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),c=o=>{const i=n.find(u=>u.id===o);return(i==null?void 0:i.name)||"Unknown User"},d=o=>{const i=l.find(u=>u.value===o);return(i==null?void 0:i.label)||o};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(o=>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:c(o.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:d(o.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:d(o.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(o.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id))})]})}function Ws(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=k.useRef(null);return k.useEffect(()=>{const c=d=>{const o=d.target;l.current&&l.current.contains(o)||o instanceof Element&&(o.closest("[data-radix-popper-content-wrapper]")||o.closest("[data-radix-select-content]")||o.closest("[data-radix-popover-content]")||o.closest("[data-radix-dropdown-menu-content]")||o.closest("[data-radix-tooltip-content]")||o.closest('[role="listbox"]')||o.closest('[role="option"]')||o.closest('[role="combobox"]'))||o instanceof Element&&o.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,c),()=>{document.removeEventListener(r,c)}},[t,a,r]),l}function Ne(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function Ea(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Js(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function Ia(t,n,a){const r=Js(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(o=>o.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(o=>o.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(o=>o.tenantUserId===t.id)}function Aa({user:t}){return Js(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 Ma({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:c}){if(!(n!=null&&n.role))return null;const d=Ea((r==null?void 0:r.type)||""),o=a.some(x=>x.id===t.id),i=a.find(x=>x.id===t.id),u=i?i.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:d?e.jsx(Ie,{currentRole:u,onRoleChange:x=>{c(t.id,n.role,x)},roleOptions:m,disabled:!d,allowDropdown:d,className:o?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:Ne(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function Ra({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(Ee,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function La({isUserRemoving:t,isRemoving:n}){return e.jsx(e.Fragment,{children:t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:n?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"})})}function Fa({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const d=t.shares,o=d.specificOrgUsers||[],i=d.specificTenantUsers||[],u=d.orgWide||[],m=d.orgUsersOnly||[],x=d.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:[o.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 (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((h,p)=>{var N,C;const b=((N=n.find(L=>L.id===h.orgUserId))==null?void 0:N.name)||"Unknown User",f=((C=n.find(L=>L.id===h.orgUserId))==null?void 0:C.type)||"",j=Ne(h.role,a(f));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})]},p)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),i.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 (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((h,p)=>{var N,C;const b=((N=n.find(L=>L.id===h.tenantUserId))==null?void 0:N.name)||"Unknown User",f=((C=n.find(L=>L.id===h.tenantUserId))==null?void 0:C.type)||"",j=Ne(h.role,a(f));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})]},p)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.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((h,p)=>{const b=Ne(h.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})]},p)})})]}),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((h,p)=>{const b=Ne(h.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})]},p)})})]}),x.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:x.map((h,p)=>{const b=Ne(h.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})]},p)})})]}),!o.length&&!i.length&&!u.length&&!m.length&&!x.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const d=t.shares.specificTenantUsers||[],o=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:[d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((i,u)=>{var p,b;const m=((p=n.find(f=>f.id===i.tenantUserId))==null?void 0:p.name)||"Unknown User",x=((b=n.find(f=>f.id===i.tenantUserId))==null?void 0:b.type)||"",h=Ne(i.role,a(x));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:h})]},u)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),o.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:o.map((i,u)=>{const m=Ne(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:m})]},u)})})]}),!d.length&&!o.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],d=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((o,i)=>{var h,p;const u=((h=n.find(b=>b.id===o.tenantUserId))==null?void 0:h.name)||"Unknown User",m=((p=n.find(b=>b.id===o.tenantUserId))==null?void 0:p.type)||"",x=Ne(o.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:x})]},i)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),d.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:d.map((o,i)=>{const u=Ne(o.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})]},i)})})]}),!c.length&&!d.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function Oa({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 Pa({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:c,selectedUser:d,roleOptions:o,currentUser:i,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:x,handleUpdateAccess:h,handleUserRoleChange:p}){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":c?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:c,onCheckedChange:()=>{l?a?m(t.id):x(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(Aa,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Ie,{currentRole:n==null?void 0:n.role,onRoleChange:b=>h(t.id,n.role,b),roleOptions:o,disabled:!1,allowDropdown:!0}):e.jsx(Ma,{user:t,userShare:n,usersToUpdate:u,currentUser:i,getRoleOptions:()=>o,handleUpdateAccess:h}),c&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(Ie,{currentRole:(d==null?void 0:d.role)||"VIEWER",onRoleChange:b=>p(t.id,b),roleOptions:o,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(Ra,{hasAccess:r,isUserRemoving:a,isSelected:c,hasAccessFromAPI:l}),e.jsx(La,{isUserRemoving:a,isSelected:c,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Xs({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:c,handleUserToggle:d,handleUserRoleChange:o,handleRemoveAccess:i,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),x=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate(),p=s.useShareSearchQuery(),b=s.useShareManagementActions(),f=d||(w=>{const D=m.some(y=>y.id===w),g=x.includes(w);D?b.removeSelectedUser(w):g?b.removeUserFromRemove(w):b.addSelectedUser({id:w,role:"VIEWER"})}),j=o||b.updateSelectedUserRole,N=i||b.addUserToRemove,C=u||((w,D,g)=>{b.addUserToUpdate({id:w,currentRole:D,newRole:g})}),L=l.filter(w=>w.id!==(c==null?void 0:c.id)),A=x;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 (",(L??[]).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(Fa,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:c})})]})})]}),(L==null?void 0:L.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===L.length?b.setSelectedUsers([]):b.setSelectedUsers(L.map(w=>({id:w.id,role:"VIEWER"})))},className:"h-7 text-xs",children:m.length===L.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(Oa,{isInitialLoading:n,isSearching:a,searchQuery:p,availableUsers:L||[]}),!n&&!a&&(L==null?void 0:L.length)>0&&L.map(w=>{const D=t?Ia(w,t,c):void 0,g=A.includes(w.id),y=!!D,v=y&&!g,R=m.some(I=>I.id===w.id),S=m.find(I=>I.id===w.id),F=r(w.type);return e.jsx(Pa,{user:w,userShare:D,isUserRemoving:g,hasAccess:v,hasAccessFromAPI:y,isSelected:R,selectedUser:S,roleOptions:F,currentUser:c,usersToUpdate:h,handleUserToggle:f,handleRemoveAccess:N,handleUpdateAccess:C,handleUserRoleChange:j},w.id)})]})]})}function ls({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(c=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:c.value,id:c.value,className:"peer sr-only",disabled:c.disabled}),e.jsxs(s.Label,{htmlFor:c.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 ${c.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[c.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:c.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:c.description})]})]})]},c.value))}),!l&&r.some(c=>c.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 ye=()=>[{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 Ba({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:c=!1,isUpdating:d=!1,isRemoving:o=!1}){const i=s.useShareCurrentMode(),u=ye().filter(C=>C.value==="VIEWER"||C.value==="EDITOR"||C.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",x=l?l.newRole:m,h=n.role!=="NONE"&&!c&&(!l||l.newRole===m),p=l!==null&&l.newRole!==m,b=c,f=m==="NONE"||!m,j=C=>{switch(C){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(ha,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},N=C=>{r(m,C)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",p&&!b&&!f?"border-orange-300 bg-orange-50":h?"border-green-300 bg-green-50":b||f?"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"," ",i==="allOrgUsers"?"Organization":i==="allTenantUsers"?"Tenant":i==="specificOrgUsers"?"Org":"Tenant"," ","Users",h&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),p&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(b||f)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:b||f?"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(C=>e.jsxs(s.Button,{variant:x===C.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>N(C.value),disabled:a||d||o,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(C.value),e.jsx("span",{className:"font-medium",children:C.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:C.description})]},C.value))})]})})]})})}function Zs({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:c,onRemoveAccess:d,allUsersToUpdate:o,allUsersToRemove:i}){const u=f=>f==="OWNER"?"CONTRIBUTOR":f,x=n?{role:u(n.role)}:{role:"NONE"},h=o?{currentRole:u(o.currentRole),newRole:u(o.newRole)}:null,p=(f,j)=>{c(f,j)},b=()=>{d()};return e.jsx(Ba,{currentUser:t,currentShare:x,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:p,onRemoveAccess:b,allUsersToUpdate:h,allUsersToRemove:i})}function Oe(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:c}=t,d=k.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&c?{tenantId:c}:{}}),[n,l,c]),{users:o,isLoading:i,isError:u}=s.useUnifiedUsers(d),m=s.useResourceShares(r,a);return{allUsers:o,isLoadingUsers:i,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function Va({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:c=!1,isRemoving:d=!1}){var z,W;const o=s.useShareSelectedTab(),i=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:x}=s.useShareSearchWithDebounce(),h=s.useShareSelectedUsers(),p=s.useShareUsersToRemove(),b=s.useShareUsersToUpdate(),f=s.useShareCurrentMode(),j=s.useShareOrgWideRole(),N=s.useShareManagementActions(),[C,L]=k.useState("specific_users"),A=()=>{if(o==="org")return"organization";if(o==="tenant")return"tenant"},w=()=>{if(o==="tenant"&&i)return i},{allUsers:D,existingShares:g,isLoadingUsers:y}=Oe({debouncedSearchQuery:x,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:A(),tenantId:w()});k.useEffect(()=>{N.setCurrentContext("org-tab"),N.setCurrentMode(C==="all_users"?"allOrgUsers":"specificOrgUsers")},[N,C]);const v=X=>{var te,ie;const se=X;if(L(se),r==null||r(se),N.setCurrentContext("org-tab"),se==="specific_users")N.setCurrentMode("specificOrgUsers");else if(se==="all_users"){N.setCurrentMode("allOrgUsers");const H=(ie=(te=g==null?void 0:g.shares)==null?void 0:te.orgUsersOnly)==null?void 0:ie[0];H&&H.role!==void 0&&N.setOrgWideRole(H.role)}},R=D.filter(X=>X.name.toLowerCase().includes(u.toLowerCase())||X.email.toLowerCase().includes(u.toLowerCase())),S=D.filter(X=>h.some(se=>se.id===X.id)),F=X=>{var H,$;const se=h.some(ae=>ae.id===X),te=p.includes(X),ie=($=(H=g==null?void 0:g.shares)==null?void 0:H.specificOrgUsers)==null?void 0:$.some(ae=>ae.orgUserId===X);se?N.removeSelectedUser(X):te?N.removeUserFromRemove(X):ie||N.addSelectedUser({id:X,role:"VIEWER"})},I=(X,se)=>{N.updateSelectedUserRole(X,se)},T=X=>{N.addUserToRemove(X),N.removeSelectedUser(X)},M=X=>{N.removeUserFromRemove(X)},O=X=>{N.removeUserFromUpdate(X)},E=(X,se)=>{N.setOrgWideRole(se)},P=()=>{N.setOrgWideRole((B==null?void 0:B.role)||"NONE")},B=(W=(z=g==null?void 0:g.shares)==null?void 0:z.orgUsersOnly)==null?void 0:W[0];k.useEffect(()=>{C==="all_users"&&B&&B.role!==void 0&&N.setOrgWideRole(B.role)},[C,B,N]);const q=y,Y=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(ls,{shareType:C,onShareTypeChange:v,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??"")}]}),C==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(He,{value:u,onChange:m}),e.jsx(Ks,{selectedUsers:h,selectedUserObjects:S,onRemove:F,onRoleChange:I,getRoleOptions:ye}),e.jsx(Hs,{usersToRemove:p,allUsers:R,onRemove:M}),e.jsx(Qs,{usersToUpdate:b,allUsers:R,onRemove:O,getRoleOptions:ye}),e.jsx(Xs,{existingShares:g,isInitialLoading:q,isSearching:Y,resource:t,onShare:()=>{},getRoleOptions:ye,allUsers:R,currentUser:a,handleUserToggle:F,handleUserRoleChange:I,handleRemoveAccess:T,handleUpdateAccess:(X,se,te)=>{N.addUserToUpdate({id:X,currentRole:se,newRole:te})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Zs,{currentUser:a,currentShare:B,isSharing:l,isUpdating:c,isRemoving:d,onUpdateAccess:E,onRemoveAccess:P,allUsersToUpdate:f==="allOrgUsers"&&j!==((B==null?void 0:B.role)||"NONE")?{currentRole:(B==null?void 0:B.role)||"NONE",newRole:j}:null,allUsersToRemove:f==="allOrgUsers"&&(B==null?void 0:B.role)===void 0})})]}):null}function za(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function Ua(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function et({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:l,currentUser:c,handleGroupToggle:d,handleGroupRoleChange:o,handleRemoveAccess:i,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),p=s.useShareManagementActions(),b=l(c==null?void 0:c.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(f=>{const j=n==null?void 0:n.find(g=>g.groupId===f.id),N=m.some(g=>g.id===f.id),C=x.includes(f.id),L=h.find(g=>g.id===f.id),A=!!j&&!C;let D=(j==null?void 0:j.role)||"VIEWER";if(N){const g=m.find(y=>y.id===f.id);D=(g==null?void 0:g.role)||"VIEWER"}else L&&(D=L.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",A&&!C?"border border-green-200 bg-green-50":C?"border border-red-200 bg-red-50":N?"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-${f.id}`,checked:A?!C:N,disabled:!1,onCheckedChange:()=>{A?C?p.removeGroupFromRemove(f.id):i==null||i(f.id):d==null||d(f.id)}}),e.jsxs("label",{htmlFor:`group-${f.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:f.name}),f.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:[f.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",Ua(f.type)),children:za(f.type)}),f.type==="TENANT_GROUP"&&f.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",f.tenantName]})]}),f.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:f.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[A&&!C?e.jsx(Ie,{currentRole:D,onRoleChange:g=>{j&&g!==j.role&&(u==null||u(f.id,j.role,g))},roleOptions:b,disabled:!1,allowDropdown:!0,className:L?"border-orange-300 bg-orange-100":""}):N&&!A&&e.jsx(Ie,{currentRole:D,onRoleChange:g=>o==null?void 0:o(f.id,g),roleOptions:b,disabled:!1}),A&&!C&&!L&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i==null?void 0:i(f.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),C&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p.removeGroupFromRemove(f.id),children:"Undo"}),L&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p.removeGroupFromUpdate(f.id),children:"Cancel"})]})]},f.id)})})]})}function st({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){if(t.length===0)return null;const c=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(d=>{const o=n.find(i=>i.id===d.id);return o?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:[o.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:o.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[o.memberCount," members"]}),o.type==="TENANT_GROUP"&&o.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",o.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ie,{currentRole:d.role,onRoleChange:i=>r(d.id,i),roleOptions:c}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(d.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},d.id):null})})]})}function ws({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:c=!1,isRemoving:d=!1}){var _;const{searchQuery:o,debouncedSearchQuery:i,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),x=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate(),p=s.useShareSelectedGroups(),b=s.useShareGroupsToRemove(),f=s.useShareGroupsToUpdate(),j=s.useShareCurrentMode(),N=s.useShareTenantWideRole(),C=s.useShareAllTenantsRole(),L=s.useShareSelectedTenant(),A=s.useShareManagementActions(),{data:w,isLoading:D}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:g,isLoading:y}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||L),[v,R]=k.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");k.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(A.setCurrentContext("tenant-dialog"),A.setCurrentMode("specificTenantUsers")):(A.setCurrentContext("tenant-tab"),A.setCurrentMode("allTenants"))},[A,a==null?void 0:a.type]);const S=V=>{var oe,de,ne,me;R(V);let Z;if(V==="specific_tenant_users"?Z="specific_users":V==="all_tenant_users"||V==="all_tenants"?Z="all_users":V==="groups"?Z="groups":Z="specific_users",r==null||r(Z),V==="groups"?(A.setCurrentContext("group-share"),A.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(A.setCurrentContext("tenant-dialog"),V==="specific_tenant_users"?A.setCurrentMode("specificTenantUsers"):V==="all_tenant_users"&&(A.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&A.setSelectedTenant(a.tenantId))):(A.setCurrentContext("tenant-tab"),V==="specific_tenant_users"?A.setCurrentMode("specificTenantUsers"):V==="all_tenant_users"?A.setCurrentMode("allTenantUsers"):V==="all_tenants"&&A.setCurrentMode("allTenants")),V==="all_tenant_users"){const pe=(de=(oe=T==null?void 0:T.shares)==null?void 0:oe.tenantWide)==null?void 0:de[0];pe&&pe.role!==void 0&&A.setTenantWideRole(pe.role)}else if(V==="all_tenants"){const pe=(me=(ne=T==null?void 0:T.shares)==null?void 0:ne.allTenantsOnly)==null?void 0:me[0];pe&&pe.role!==void 0&&A.setAllTenantsRole(pe.role)}},F=V=>{A.setSelectedTenant(V)},{allUsers:I,existingShares:T,isLoadingUsers:M,isErrorLoadingUsers:O,isLoadingShares:E,isErrorLoadingShares:P}=Oe({debouncedSearchQuery:i,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:L}),B=V=>{var ne,me;const Z=m.some(pe=>pe.id===V),oe=x.includes(V),de=(me=(ne=T==null?void 0:T.shares)==null?void 0:ne.specificTenantUsers)==null?void 0:me.some(pe=>pe.tenantUserId===V);Z?A.removeSelectedUser(V):oe?A.removeUserFromRemove(V):de||A.addSelectedUser({id:V,role:"VIEWER"})},q=(V,Z)=>{A.updateSelectedUserRole(V,Z)},Y=V=>{A.addUserToRemove(V),A.removeSelectedUser(V)},z=V=>{A.removeUserFromRemove(V)},W=V=>{A.removeUserFromUpdate(V)},X=(V,Z,oe)=>{A.addUserToUpdate({id:V,currentRole:Z,newRole:oe})},se=(V,Z)=>{v==="all_tenant_users"?A.setTenantWideRole(Z):v==="all_tenants"&&A.setAllTenantsRole(Z)},te=()=>{v==="all_tenant_users"?A.setTenantWideRole("VIEWER"):v==="all_tenants"&&A.setAllTenantsRole("VIEWER")},H=(()=>{var V,Z,oe,de;return j==="allTenants"?(Z=(V=T==null?void 0:T.shares)==null?void 0:V.allTenantsOnly)==null?void 0:Z[0]:j==="allTenantUsers"?(de=(oe=T==null?void 0:T.shares)==null?void 0:oe.tenantWide)==null?void 0:de[0]:null})();k.useEffect(()=>{var V,Z,oe,de;if(v==="all_tenant_users"){const ne=(Z=(V=T==null?void 0:T.shares)==null?void 0:V.tenantWide)==null?void 0:Z[0];ne&&ne.role!==void 0&&A.setTenantWideRole(ne.role)}else if(v==="all_tenants"){const ne=(de=(oe=T==null?void 0:T.shares)==null?void 0:oe.allTenantsOnly)==null?void 0:de[0];ne&&ne.role!==void 0&&A.setAllTenantsRole(ne.role)}},[v,T,A]);const $=I.filter(V=>m.some(Z=>Z.id===V.id)),ae=V=>{const Z=p.some(ne=>ne.id===V),oe=b.includes(V),de=le==null?void 0:le.some(ne=>ne.groupId===V);Z?A.removeSelectedGroup(V):oe?A.removeGroupFromRemove(V):de||A.addSelectedGroup({id:V,role:"VIEWER"})},Q=(V,Z)=>{A.updateSelectedGroupRole(V,Z)},re=V=>{A.addGroupToRemove(V),A.removeSelectedGroup(V)},U=(V,Z,oe)=>{A.addGroupToUpdate({id:V,currentRole:Z,newRole:oe})},ee=g.filter(V=>p.some(Z=>Z.id===V.id)),ce=k.useMemo(()=>v!=="groups"?[]:g.filter(V=>V.type!=="TENANT_GROUP"?!1:V.name.toLowerCase().includes(o.toLowerCase())||V.description&&V.description.toLowerCase().includes(o.toLowerCase())),[g,v,o]),le=k.useMemo(()=>{var Z,oe;const V=((Z=T==null?void 0:T.shares)==null?void 0:Z.specificGroups)||((oe=T==null?void 0:T.shares)==null?void 0:oe.groups)||[];return!V||V.length===0?[]:V.filter(de=>{const ne=g.find(me=>me.id===de.groupId);return(ne==null?void 0:ne.type)==="TENANT_GROUP"})},[T,g]),fe=M||E||v==="groups"&&y,ue=O||P,K=()=>(a==null?void 0:a.type)==="tenant"||v==="all_tenants"||v==="groups"?!0:L&&(v==="specific_tenant_users"||v==="all_tenant_users");return e.jsxs(e.Fragment,{children:[ue&&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"})]})}),!ue&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(ls,{shareType:v,onShareTypeChange:S,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(ys,{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"&&(v==="specific_tenant_users"||v==="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:L||"",onValueChange:F,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:(_=w==null?void 0:w.tenants)==null?void 0:_.map(V=>e.jsx(s.SelectItem,{value:V.id,children:V.name},V.id))})]})]}),K()?e.jsx(e.Fragment,{children:v==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(He,{value:o,onChange:u}),e.jsx(Ks,{selectedUsers:m,selectedUserObjects:$,onRemove:V=>B(V),onRoleChange:q,getRoleOptions:ye}),e.jsx(Hs,{usersToRemove:x,allUsers:I,onRemove:z}),e.jsx(Qs,{usersToUpdate:h,allUsers:I,onRemove:W,getRoleOptions:ye}),e.jsx(Xs,{existingShares:T,isInitialLoading:!!fe,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:ye,allUsers:I,currentUser:a,handleUserToggle:B,handleUserRoleChange:q,handleRemoveAccess:Y,handleUpdateAccess:X})]}):v==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(He,{value:o,onChange:u,placeholder:"Search groups..."}),e.jsx(st,{selectedGroups:p,groupObjects:ee,onRemove:ae,onRoleChange:Q,getRoleOptions:ye}),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"})]}),f.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 (",f.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(et,{groups:ce,existingGroupShares:le,isLoading:y,resource:t,getRoleOptions:ye,currentUser:a,handleGroupToggle:ae,handleGroupRoleChange:Q,handleRemoveAccess:re,handleUpdateAccess:U})]}):v==="all_tenant_users"||v==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Zs,{currentUser:a,currentShare:H,isSharing:l,isUpdating:c,isRemoving:d,onUpdateAccess:se,onRemoveAccess:te,allUsersToUpdate:j==="allTenantUsers"&&((H==null?void 0:H.role)===void 0||N!==H.role)||j==="allTenants"&&((H==null?void 0:H.role)===void 0||C!==H.role)?{currentRole:(H==null?void 0:H.role)||"VIEWER",newRole:j==="allTenantUsers"?N:C}:null,allUsersToRemove:j==="allTenantUsers"&&(H==null?void 0:H.role)===void 0||j==="allTenants"&&(H==null?void 0:H.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(v==="specific_tenant_users"||v==="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(ys,{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 _a({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:c=!1,isRemoving:d=!1}){var O,E;const{searchQuery:o,setSearchQuery:i}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),h=s.useShareManagementActions(),[p,b]=k.useState("org_groups"),[f,j]=k.useState(""),{data:N,isLoading:C}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&p==="tenant_groups"}),L=Array.isArray(N)?N:(N==null?void 0:N.tenants)||[],A=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:w,isLoading:D}=s.useShareableGroups(A(),p==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?f:a==null?void 0:a.tenantId),{existingShares:g}=Oe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),y=w.filter(P=>p==="org_groups"&&P.type!=="ORG_GROUP"||p==="tenant_groups"&&P.type!=="TENANT_GROUP"||p==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!f||P.tenantId&&P.tenantId!==f)?!1:P.name.toLowerCase().includes(o.toLowerCase())||P.description&&P.description.toLowerCase().includes(o.toLowerCase())),v=((O=g==null?void 0:g.shares)==null?void 0:O.specificGroups)||((E=g==null?void 0:g.shares)==null?void 0:E.groups)||[];k.useEffect(()=>{h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},[h]);const R=P=>{const B=P;b(B),B==="org_groups"&&j(""),r==null||r(B==="org_groups"?"specific_groups":"all_groups"),h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},S=w.filter(P=>u.some(B=>B.id===P.id)),F=P=>{const B=u.some(z=>z.id===P),q=m.includes(P),Y=v==null?void 0:v.some(z=>z.groupId===P);B?h.removeSelectedGroup(P):q?h.removeGroupFromRemove(P):Y||h.addSelectedGroup({id:P,role:"VIEWER"})},I=(P,B)=>{h.updateSelectedGroupRole(P,B)},T=P=>{h.addGroupToRemove(P),h.removeSelectedGroup(P)},M=(P,B,q)=>{h.addGroupToUpdate({id:P,currentRole:B,newRole:q})};return a?e.jsxs(e.Fragment,{children:[e.jsx(ls,{shareType:p,onShareTypeChange:R,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"})}]}),p==="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:f,onValueChange:j,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:L.map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.id,children:P.name},P.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:p==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!f?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(He,{value:o,onChange:i,placeholder:"Search groups..."}),e.jsx(st,{selectedGroups:u,groupObjects:S,onRemove:F,onRoleChange:I,getRoleOptions:ye}),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"})]}),x.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 (",x.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(et,{groups:y,existingGroupShares:v,isLoading:D,resource:t,getRoleOptions:ye,currentUser:a,handleGroupToggle:F,handleGroupRoleChange:I,handleRemoveAccess:T,handleUpdateAccess:M})]})})]}):null}const tt=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),c=s.useShareSelectedGroups(),d=s.useShareGroupsToRemove(),o=s.useShareGroupsToUpdate(),i=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),x=s.useShareTenantWideRole(),h=s.useShareGroupWideRole(),p=k.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedGroups:c,groupsToRemove:d,groupsToUpdate:o,selectedTenant:i,orgWideRole:u,allTenantsRole:m,tenantWideRole:x}),[t,n,a,r,l,c,d,o,i,u,m,x,h]),b=k.useMemo(()=>j=>s.validateShareData(j),[]),f=k.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(!i)return!1}else if(n==="specificTenantUsers")return i?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"?c.length>0||d.length>0||o.length>0:!0}return!1},[t,n,a,r,l,c,d,o,i]);return{buildShareData:p,validateShareData:b,isCurrentStateValid:f,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:i,orgWideRole:u,allTenantsRole:m,tenantWideRole:x}};function Ds({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:d,shareTabType:o,currentAllUsersShare:i,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),x=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate(),p=s.useShareSelectedTenant(),b=s.useShareOrgWideRole(),f=s.useShareAllTenantsRole(),j=s.useShareTenantWideRole(),{buildShareData:N,validateShareData:C,isCurrentStateValid:L}=tt(),A=a||r||l,w=()=>{var R,S,F,I;if(A)return"Updating...";if(o==="specific_users"){if(m.length===0&&x.length===0&&h.length===0)return"Select users to share with";const T=m.length+x.length+h.length;return T===0?"Select users to share with":m.length>0&&x.length>0?`Update access for ${T} user${T!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Remove access for ${x.length} user${x.length!==1?"s":""}`:m.length>0&&x.length===0&&h.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${T} user${T!==1?"s":""}`}else if(o==="all_users"){if(!i||i.role===void 0)return"Share with All Users";const T=i.role;return b===T?"Remove Access":"Update Access"}else if(o==="all_tenants"){const T=(S=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0)return"Share with All Tenants";const M=T.role;return f===M?"Remove Access":"Update Access"}else if(o==="all_tenant_users"){const T=(I=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:I[0];if(!T||T.role===void 0)return"Share with All Tenant Users";const M=T.role;return j===M?"Remove Access":"Update Access"}else if(o==="specific_tenant_users"){if(m.length===0&&x.length===0&&h.length===0)return"Select users to share with";const T=m.length+x.length+h.length;return T===0?"Select users to share with":m.length>0&&x.length>0?`Update access for ${T} user${T!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Remove access for ${x.length} user${x.length!==1?"s":""}`:m.length>0&&x.length===0&&h.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${T} user${T!==1?"s":""}`}return"Share"},D=()=>A||!t||o==="all_tenant_users"&&!p||o==="specific_tenant_users"&&!p?!0:!L,g=()=>{const R=N();R&&C(R)&&c(R)},y=()=>{var R,S,F,I;if(o==="all_users")if(!i||i.role===void 0){const T=N();T&&C(T)&&c(T)}else{const T=i.role;if(b===T)u==null||u();else{const O=N();if(O&&C(O)){const E={...O,updateAccess:!0};c(E)}}}else if(o==="all_tenants"){const T=(S=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0){const M=N();M&&C(M)&&c(M)}else{const M=T.role;if(f===M)u==null||u();else{const E=N();if(E&&C(E)){const P={...E,updateAccess:!0};c(P)}}}}else if(o==="all_tenant_users"){const T=(I=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:I[0];if(!T||T.role===void 0){const M=N();M&&C(M)&&c(M)}else{const M=T.role;if(j===M)u==null||u();else{const E=N();if(E&&C(E)){const P={...E,updateAccess:!0};c(P)}}}}},v=()=>{var R,S,F,I;if(o==="all_users"){if(!i||i.role===void 0)return"default";const T=i.role;return b===T?"destructive":"default"}else if(o==="all_tenants"){const T=(S=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0)return"default";const M=T.role;return f===M?"destructive":"default"}else if(o==="all_tenant_users"){const T=(I=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:I[0];if(!T||T.role===void 0)return"default";const M=T.role;return j===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsxs(s.Button,{variant:"outline",onClick:d,disabled:A,children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),(o==="specific_users"||o==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||x.length>0||h.length>0)&&e.jsxs(s.Button,{onClick:g,disabled:!t||A,variant:"default",children:[A?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ee,{className:"mr-2 h-4 w-4"}),!A&&w()]})}),(o==="all_users"||o==="all_tenants"||o==="all_tenant_users")&&e.jsxs(s.Button,{onClick:y,disabled:D(),variant:v(),children:[A?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"}),!A&&w()]})]})}function Ga({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:c,shareTabType:d,currentAllUsersShare:o}){const i=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),x=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const b=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:j,isCurrentStateValid:N}=tt(),C=n||a||r,L=()=>{if(C)return"Updating...";if(d==="specific_users"){if(i.length===0&&u.length===0&&m.length===0)return"Select users to share with";const v=i.length+u.length+m.length;return v===0?"Select users to share with":i.length>0&&u.length>0?`Update access for ${v} user${v!==1?"s":""}`:u.length>0&&i.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:i.length>0&&u.length===0&&m.length===0?`Share with ${i.length} user${i.length!==1?"s":""}`:m.length>0&&i.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${v} user${v!==1?"s":""}`}else if(d==="groups"){if(x.length===0&&h.length===0&&p.length===0)return"Select groups to share with";const v=x.length+h.length+p.length;return v===0?"Select groups to share with":x.length>0&&h.length>0?`Update access for ${v} group${v!==1?"s":""}`:h.length>0&&x.length===0&&p.length===0?`Remove access for ${h.length} group${h.length!==1?"s":""}`:x.length>0&&h.length===0&&p.length===0?`Share with ${x.length} group${x.length!==1?"s":""}`:p.length>0&&x.length===0&&h.length===0?`Update access for ${p.length} group${p.length!==1?"s":""}`:`Update access for ${v} group${v!==1?"s":""}`}else if(d==="all_users"){if(!o||o.role==="NONE")return"Share with All Users";const v=o.role;return b===v?"Remove Access":"Update Access"}return"Share"},A=()=>C||!t?!0:!N,w=()=>{const v=f();v&&j(v)&&l(v)},D=()=>{const v=f();v&&j(v)&&l(v)},g=()=>{if(!o||o.role==="NONE"){const v=f();v&&j(v)&&l(v)}else{const v=o.role;if(b===v){const S=f();if(S&&j(S)){const F={...S,removeAccess:!0};l(F)}}else{const S=f();if(S&&j(S)){const F={...S,updateAccess:!0};l(F)}}}},y=()=>!o||o.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsxs(s.Button,{variant:"outline",onClick:c,disabled:C,children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),d==="specific_users"&&e.jsx(e.Fragment,{children:(i.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:w,disabled:!t||C,variant:"default",children:[C?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ee,{className:"mr-2 h-4 w-4"}),!C&&L()]})}),d==="groups"&&e.jsx(e.Fragment,{children:(x.length>0||h.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:D,disabled:!t||C,variant:"default",children:[C?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ee,{className:"mr-2 h-4 w-4"}),!C&&L()]})}),d==="all_users"&&e.jsxs(s.Button,{onClick:g,disabled:A(),variant:y(),children:[C?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ee,{className:"mr-2 h-4 w-4"}),!C&&L()]})]})}function $a({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:d,shareTabType:o,currentAllGroupsShare:i,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const p=()=>{c({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:x,groupsToUpdate:h})},b=()=>m.length>0||x.length>0||h.length>0,f=()=>x.length>0&&m.length===0&&h.length===0?"Remove Access":h.length>0&&m.length===0&&x.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"]}),x.length>0&&e.jsxs("span",{className:"ml-2 text-destructive",children:["• ",x.length," to remove"]}),h.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",h.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:d,disabled:j,children:"Cancel"}),e.jsxs(s.Button,{onClick:p,disabled:!b()||j,children:[j&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),f()]})]})]})}function be(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Ce(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Ya(t,n,a){const{resourceType:r,resourceId:l,shareMutation:c,removeMutation:d,existingShares:o,resetUserSelections:i}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=be(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:x}=t;if(u&&u.length>0){const h=be(r,l,u.map(p=>({scope:"specific_org_user",orgUserId:p.id,role:p.role})));c(h,{onSuccess:()=>{i()}})}if(m&&m.length>0){const h=Ce(r,l,m.map(p=>{var f,j;const b=(j=(f=o==null?void 0:o.shares)==null?void 0:f.specificOrgUsers)==null?void 0:j.find(N=>N.orgUserId===p);return{scope:"specific_org_user",orgUserId:p,role:(b==null?void 0:b.role)||"VIEWER"}}));d(h,{onSuccess:()=>{i()}})}x&&x.length>0&&x.forEach(h=>{const p=be(r,l,[{scope:"specific_org_user",orgUserId:h.id,role:h.newRole}]);c(p,{onSuccess:()=>{i()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=be(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="allTenantUsers"){const u=be(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:x,tenantId:h}=t;if(m&&m.length>0){const p=Ce(r,l,m.map(b=>{var j,N;const f=(N=(j=o==null?void 0:o.shares)==null?void 0:j.specificTenantUsers)==null?void 0:N.find(C=>C.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,tenantId:h,role:(f==null?void 0:f.role)||"VIEWER"}}));d(p,{onSuccess:()=>{i()}})}if(x&&x.length>0&&x.forEach(p=>{const b=be(r,l,[{scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.newRole}]);c(b,{onSuccess:()=>{i()}})}),u&&u.length>0){const p=be(r,l,u.map(b=>({scope:"specific_tenant_user",tenantUserId:b.id,tenantId:h,role:b.role})));c(p,{onSuccess:()=>{i()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=Ce(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);d(u,{onSuccess:()=>{i()}})}else if(t.updateAccess){const u=be(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);c(u,{onSuccess:()=>{i()}})}else{const u=be(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:x}=t;if(u&&u.length>0){const h=be(r,l,u.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,role:p.role})));c(h,{onSuccess:()=>{i()}})}if(m&&m.length>0){const h=Ce(r,l,m.map(p=>{var f,j;const b=(j=(f=o==null?void 0:o.shares)==null?void 0:f.specificTenantUsers)==null?void 0:j.find(N=>N.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,role:(b==null?void 0:b.role)||"VIEWER"}}));d(h,{onSuccess:()=>{i()}})}x&&x.length>0&&x.forEach(h=>{const p=be(r,l,[{scope:"specific_tenant_user",tenantUserId:h.id,role:h.newRole}]);c(p,{onSuccess:()=>{i()}})})}break;case"group-share":if(t.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:m,groupsToUpdate:x}=t;if(u&&u.length>0){const h=be(r,l,u.map(p=>({scope:"group",groupId:p.id,role:p.role})));c(h,{onSuccess:()=>{var p;i(),(p=n.resetGroupSelections)==null||p.call(n),s.ue.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(m&&m.length>0){const h=Ce(r,l,m.map(p=>({scope:"group",groupId:p,role:"VIEWER"})));d(h,{onSuccess:()=>{var p;i(),(p=n.resetGroupSelections)==null||p.call(n),s.ue.success(`Removed access from ${m.length} group${m.length!==1?"s":""}`)}})}x&&x.length>0&&x.forEach(h=>{const p=be(r,l,[{scope:"group",groupId:h.id,role:h.newRole}]);c(p,{onSuccess:()=>{var b;i(),(b=n.resetGroupSelections)==null||b.call(n),s.ue.success("Updated access for group")}})})}break}}function qa(t,n,a,r){var u,m,x,h,p,b;const{resourceType:l,resourceId:c,removeMutation:d,existingShares:o,resetUserSelections:i}=r;if(c)if(t.length>0){const f=Ce(l,c,t.map(j=>{var C,L;const N=(L=(C=o==null?void 0:o.shares)==null?void 0:C.specificTenantUsers)==null?void 0:L.find(A=>A.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,role:(N==null?void 0:N.role)||"VIEWER"}}));d(f,{onSuccess:()=>{i()},onError:j=>{console.error("Remove access failed:",j)}})}else{const f=n==="tenant"&&a==="allTenants",j=n==="tenant"&&a==="allTenantUsers";if(f){const N=(m=(u=o==null?void 0:o.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(N){const C=Ce(l,c,[{scope:"all_tenants_only",role:N.role}]);d(C,{onSuccess:()=>{i()},onError:L=>{console.error("Remove all-tenants access failed:",L)}})}}else if(j){const N=(h=(x=o==null?void 0:o.shares)==null?void 0:x.tenantWide)==null?void 0:h[0];if(N){const C=Ce(l,c,[{scope:"all_tenant_users",role:N.role}]);d(C,{onSuccess:()=>{i()},onError:L=>{console.error("Remove all-tenant-users access failed:",L)}})}}else{const N=(b=(p=o==null?void 0:o.shares)==null?void 0:p.orgUsersOnly)==null?void 0:b[0];if(N){const C=Ce(l,c,[{scope:"org_users_only",role:N.role}]);d(C,{onSuccess:()=>{i()},onError:L=>{console.error("Remove org-wide access failed:",L)}})}}}}function Ka(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),d=s.useShareCurrentMode(),{currentUser:o}=s.useCurrentUserInfo(),{existingShares:i}=Oe({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=k.useCallback(()=>{r.resetUserSelections()},[r]),m=k.useCallback(()=>{r.resetGroupSelections()},[r]),x=k.useCallback(p=>{if(!t)return;const b={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:i,resetUserSelections:u,resetGroupSelections:m};Ya(p,b,o)},[t,n,a,i,u,m,o]),h=k.useCallback(()=>{if(!t)return;const p={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:i,resetUserSelections:u};qa(l,c||"",d||"",p)},[t,n,a,i,u,m,l,c,d]);return{handleShareSubmit:x,handleRemoveAccess:h}}function We({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var I,T,M,O,E,P,B,q;const{currentUser:c}=s.useCurrentUserInfo(),[d,o]=k.useState("specific_users"),[i,u]=k.useState("specific_users"),[m,x]=k.useState("specific_groups"),h=s.useShareManagementActions(),p=s.useShareSelectedTab(),b=s.useShareCurrentMode(),f=s.useShareResource(),j=s.useRemoveResourceShares(),{handleShareSubmit:N,handleRemoveAccess:C}=Ka(t.id,(Y,z)=>{f.mutate(Y,{...z,onSuccess:()=>{var W;(W=z==null?void 0:z.onSuccess)==null||W.call(z),r==null||r()}})},(Y,z)=>{j.mutate(Y,{...z,onSuccess:()=>{var W;(W=z==null?void 0:z.onSuccess)==null||W.call(z),l==null||l()}})}),L=f.isPending,A=j.isPending,w=f.isPending,{existingShares:D}=Oe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:g}=Oe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),y=(T=(I=D==null?void 0:D.shares)==null?void 0:I.tenantWide)==null?void 0:T[0],v=(O=(M=g==null?void 0:g.shares)==null?void 0:M.orgUsersOnly)==null?void 0:O[0],R=()=>{if(p==="org")return i;switch(b){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},S=k.useCallback(()=>{h.resetShareState(),a()},[h,a]),F=(c==null?void 0:c.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:S,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(Ee,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:F?"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."})]}),F?e.jsxs(s.Tabs,{value:p,onValueChange:Y=>{const z=Y;h.setSelectedTab(z),h.resetUserSelections(),h.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(Va,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:u,isSharing:L,isUpdating:w,isRemoving:A})})}),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(ws,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:Y=>o(Y),isSharing:L,isUpdating:w,isRemoving:A})})}),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(_a,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:x,isSharing:L,isUpdating:w,isRemoving:A})})})]}):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(ws,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:Y=>o(Y),isSharing:L,isUpdating:w,isRemoving:A})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:F?p==="org"?e.jsx(Ds,{resource:t,existingShares:g,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:i,currentAllUsersShare:v,onRemoveAccess:C}):p==="tenant"?e.jsx(Ds,{resource:t,existingShares:D,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:R(),currentAllUsersShare:y,onRemoveAccess:C}):e.jsx($a,{resource:t,existingShares:g,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:m,currentAllGroupsShare:(c==null?void 0:c.type)==="organization"?(P=(E=g==null?void 0:g.shares)==null?void 0:E.allOrgGroups)==null?void 0:P[0]:(q=(B=D==null?void 0:D.shares)==null?void 0:B.allTenantGroups)==null?void 0:q[0],onRemoveAccess:C}):e.jsx(Ga,{resource:t,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:d,currentAllUsersShare:y,onRemoveAccess:C})})]})})}function at({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(u=>u.selectedFrameId),l=s.useManagementStore(u=>u.selectedVisual),c=s.useEditorStore(u=>u.frame);let d;if(t)d=t;else if(n!==void 0)d=n?"linked":"library";else if(!!!(c!=null&&c.visualId||l!=null&&l.id)&&r)d="local";else if(l&&!r)d="library";else if(c!=null&&c.visualId&&r)d="linked";else if(l!=null&&l.id&&r)d="library";else return null;const o={local:"bg-gray-100 text-gray-700",linked:"bg-purple-100 text-purple-700",library:"bg-blue-100 text-blue-700"},i={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",o[d],a),children:i[d]})}const Ha=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},Qa=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 c=await l.text();throw new Error(c||"Failed to delete group")}},Wa=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},Ja=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,c=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!c.ok){const d=await c.text();throw new Error(d||"Failed to remove group members")}};function Xa(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Ha(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 Za(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Qa(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 en(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Wa(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 sn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Ja(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 tn({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=k.useState(""),[c,d]=k.useState(""),[o,i]=k.useState({}),u=Xa(),m=()=>{const h={};return r.trim()?r.length<3?h.name="Group name must be at least 3 characters":r.length>50&&(h.name="Group name must be less than 50 characters"):h.name="Group name is required",c&&c.length>200&&(h.description="Description must be less than 200 characters"),i(h),Object.keys(h).length===0},x=async h=>{if(h.preventDefault(),!m())return;const p={name:r.trim(),description:c.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(p),l(""),d(""),i({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:x,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:h=>{l(h.target.value),o.name&&i(p=>({...p,name:""}))},className:o.name?"border-destructive":"",disabled:u.isPending}),o.name&&e.jsx("p",{className:"text-sm text-destructive",children:o.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:c,onChange:h=>{d(h.target.value),o.description&&i(p=>({...p,description:""}))},className:o.description?"border-destructive":"",disabled:u.isPending,rows:3}),o.description&&e.jsx("p",{className:"text-sm text-destructive",children:o.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.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(""),d(""),i({})},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,c]=k.useState("members"),[d,o]=k.useState(""),[i,u]=k.useState([]),[m,x]=k.useState([]),{data:h,isLoading:p,refetch:b}=s.useGroupMembers(a.id),f=a.type==="TENANT_GROUP"?"tenant":"organization",{users:j,isLoading:N}=s.useUnifiedUsers({type:f,tenantId:a.tenantId||void 0,active:!0,limit:100}),C=en(),L=sn(),A=(h==null?void 0:h.members)||[],w=k.useMemo(()=>new Set(A.map(I=>I.userId)),[A]),D=k.useMemo(()=>j.filter(I=>!w.has(I.id)),[j,w]),g=k.useMemo(()=>{if(!d)return D;const I=d.toLowerCase();return D.filter(T=>{var M,O;return((M=T.name)==null?void 0:M.toLowerCase().includes(I))||((O=T.email)==null?void 0:O.toLowerCase().includes(I))})},[D,d]),y=k.useMemo(()=>{if(!d)return A;const I=d.toLowerCase();return A.filter(T=>{var M,O,E,P;return((O=(M=T.user)==null?void 0:M.name)==null?void 0:O.toLowerCase().includes(I))||((P=(E=T.user)==null?void 0:E.email)==null?void 0:P.toLowerCase().includes(I))})},[A,d]),v=async()=>{if(i.length!==0)try{await C.mutateAsync({groupId:a.id,data:{userIds:i,userType:f==="tenant"?"tenant":"org"}}),u([]),c("members"),b(),r==null||r()}catch(I){console.error("Failed to add members:",I)}},R=async()=>{if(m.length!==0)try{await L.mutateAsync({groupId:a.id,data:{userIds:m}}),x([]),b(),r==null||r()}catch(I){console.error("Failed to remove members:",I)}},S=I=>{u(T=>T.includes(I)?T.filter(M=>M!==I):[...T,I])},F=I=>{x(T=>T.includes(I)?T.filter(M=>M!==I):[...T,I])};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:[A.length," ",A.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:I=>{c(I),o(""),x([])},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:d,onChange:I=>o(I.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:p?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):y.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:d?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:d?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:y.map(I=>e.jsx(nn,{member:I,selected:m.includes(I.userId),onToggle:()=>F(I.userId)},I.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:R,disabled:L.isPending,children:L.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:d,onChange:I=>o(I.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:N?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):g.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:d?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:g.map(I=>e.jsx(rn,{user:I,selected:i.includes(I.id),onToggle:()=>S(I.id)},I.id))})}),i.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:[i.length," user",i.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:v,disabled:C.isPending,children:C.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 nn({member:t,selected:n,onToggle:a}){var l,c,d,o;const r=((c=(l=t.user)==null?void 0:l.name)==null?void 0:c.split(" ").map(i=>i[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:((d=t.user)==null?void 0:d.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(o=t.user)==null?void 0:o.email})]})]})}function rn({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(c=>c[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 ln({open:t,onOpenChange:n}){const[a,r]=k.useState("groups"),[l,c]=k.useState(""),[d,o]=k.useState(null),[i,u]=k.useState(!1),[m,x]=k.useState(null),{tokenProps:h}=s.useSemaphorContext(),{currentUser:p}=s.useCurrentUserInfo(),b=Za(),f=(p==null?void 0:p.type)==="tenant",j=h==null?void 0:h.tenantId,{groups:N,isLoading:C,refetch:L}=s.useGroups({type:f?"TENANT_GROUP":"all",tenantId:f?j:void 0,includeMembers:!1}),A=N.filter(y=>{var v;return y.name.toLowerCase().includes(l.toLowerCase())||((v=y.description)==null?void 0:v.toLowerCase().includes(l.toLowerCase()))}),w=async()=>{if(m)try{await b.mutateAsync(m.id),x(null),L()}catch(y){console.error("Failed to delete group:",y)}},D=y=>{o(y),u(!0)},g=()=>{r("groups"),L()};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:y=>c(y.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:C?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(y=>e.jsx(s.Skeleton,{className:"h-24 w-full"},y))}):A.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:A.map(y=>e.jsx(on,{group:y,onManageMembers:()=>D(y),onDelete:()=>x(y),currentUserId:p==null?void 0:p.id},y.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(tn,{onSuccess:g,tenantId:j,isTenantUser:f})})]})]})}),d&&e.jsx(an,{open:i,onOpenChange:u,group:d,onUpdate:()=>L()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>x(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:w,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 os(t){const[n,a]=k.useState(null),[r,l]=k.useState(null);return k.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 o=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(o,{method:"HEAD"})).ok)throw new Error(`Module not found at ${o}`)}catch{}const i=await import(o);if(typeof i.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>i.useChartStore),l(null)}catch(d){const o=d instanceof Error?d.message:"Unknown error";console.error("Failed to load remote chart store:",o),l(o),a(null)}})()},[t]),n}function cn(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 c=t.length;if(l!==-1&&(c=l),r!==-1&&r<c&&(c=r),n!==-1){const d=t.substring(0,n),o=t.substring(n);return`${d} {{ filters | where }} AND ${o.substring(6)}`}else if(a!==-1){const d=t.substring(0,a),o=t.substring(a);return`${d} {{ filters | where }} ${o}`}else{const d=t.substring(0,c),o=t.substring(c);return console.log("beforeClause",d),console.log("afterClause",o),o?`${d} {{ filters | where }} ${o}`:`${d.replace(/;$/,"")} {{ filters | where }}`}}function dn(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 c=r.split("__")[0],d=t.find(o=>o.tabTitle===c);return d?d.id:t[0].id}return n}}return t[0].id}async function Ts(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],c=r.getQueryData(l);if(c)return console.log("Using cached visual data for:",a),{data:c,fromCache:!0};console.log("Fetching visual data from network for:",a);const d=s.ue.loading("Loading visual...",{position:"top-center"});try{const o=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!o.ok)throw new Error("Failed to load visual");const i=await o.json();return r.setQueryData(l,i),s.ue.dismiss(d),{data:i,fromCache:!1}}catch(o){throw s.ue.dismiss(d),o}}function nt(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function un(t,n){var c,d;const a=(t==null?void 0:t.frameObject)??((c=t==null?void 0:t.visual)==null?void 0:c.frameObject);if(!a)return!1;const r=nt(a);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(d=r.cards)==null?void 0:d.find(o=>o.id===r.activeCardId);return l?(s.setupEditorWithCard({...n,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function mn(){var h;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(p=>p.frame),a=s.useEditorStore(p=>p.card),r=os(((h=a.customCardPreferences)==null?void 0:h.url)||""),l=s.useEditorStore(p=>p.selectedSchemaName),c=s.useEditorStore(p=>p.selectedDatamodelId),d=s.useEditorStore(p=>p.selectedDatabaseName),o=s.useEditorStore(p=>p.selectedTableName),i=s.useEditorStore(p=>p.selectedConnectionId),u=s.useEditorStore(p=>p.isShowingVisual),m=a.sql;return{getUpdatedFrame:k.useCallback(()=>{var N;let p=m;m&&!m.includes("{{")&&(p=cn(m),t(p));const b=(N=r==null?void 0:r.getState())==null?void 0:N.settings,f={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:c,lastSelectedDatabase:d,lastSelectedTable:o,connectionId:i,sql:p,customCfg:u?a.customCfg:null,preferences:a.preferences,...b&&{customCardPreferences:{...a.customCardPreferences,settings:b}}},j=n.cards.map(C=>C.id===a.id?f:C);return{...n,cards:j,activeCardId:dn(j,n.activeCardId)}},[a,n,u,l,c,d,o,i,t,r,m])}}function Ae(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:c,setCard:d,setIsDevMode:o,setActiveTabCardId:i,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:x,setSelectedDatabaseName:h,setSelectedSchemaName:p,setSelectedTableName:b,setSelectedDatamodelId:f,setFilterValues:j,setApplyFilters:N}=s.useEditorActions(),{setIsDashboardEditing:C,setIsVisualEditing:L,setSelectedFrameId:A,clearSelectedFrameId:w,addFrame:D,setIsDashboardPanelOpen:g}=s.useDashboardActions(),y=s.useDashboardStore(M=>M.selectedSheetId),v=s.useDashboardStore(M=>M.selectedFrameId),R=s.useDashboardStore(M=>M.dashboard),S=s.useDashboardStore(M=>M.filterValues),F=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),I=k.useCallback(async M=>{try{l(M),w();const{data:O,fromCache:E}=await Ts(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a);if(!un(O,{setFrame:c,setCard:d,setIsDevMode:o,setActiveTabCardId:i,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:x,setSelectedDatabaseName:h,setSelectedSchemaName:p,setSelectedTableName:b,setSelectedDatamodelId:f,setFilterValues:j,setApplyFilters:N,setIsDashboardEditing:C,setIsVisualEditing:L,dashboard:R,selectedSheetId:y,selectedFrameId:v,filterValues:S}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:E}}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,c,d,C,L,o,i,u,m,x,h,p,b,f,j,N,w,R,y,v,S]),T=k.useCallback(async M=>{var O;try{if(l(M),!y)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:E,fromCache:P}=await Ts(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a),B=(E==null?void 0:E.frameObject)??((O=E==null?void 0:E.visual)==null?void 0:O.frameObject);if(!B)return{success:!1,error:"Visual has no frame data"};const q=nt(B);if(!(q!=null&&q.cards)||q.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const Y={...q,id:s.v4(),visualId:M.id};return D(y,Y,"end"),C(!0),A(Y.id),g(!1),{success:!0,fromCache:P}}catch(E){return console.error("Error adding visual:",E),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,y,D,C,A,g]);return{visual:F.data,isLoading:F.isLoading,isError:F.isError,error:F.error,handleEditLibraryVisual:I,handleAddLibraryVisual:T,getUpdatedFrame:mn().getUpdatedFrame,refetch:F.refetch}}function hn({open:t,onOpenChange:n,isLibraryVisual:a,currentVisualName:r,isSaving:l=!1,onConfirm:c}){const[d,o]=k.useState(a&&r?`Copy of ${r}`:r||""),[i,u]=k.useState(""),[m,x]=k.useState(!a),[h,p]=k.useState(!0);k.useEffect(()=>{t&&(o(a&&r?`Copy of ${r}`:r||""),u(""),x(!a),p(!0))},[t,a,r]);const b=()=>{d.trim()&&(!m&&!h||c({name:d.trim(),description:i.trim()||void 0,saveToLibrary:m,saveToCurrentDashboard:h}))},f=d.trim()&&(m||h);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:d,onChange:j=>o(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:i,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:h,onCheckedChange:j=>p(!!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=>x(!!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&&!h&&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:!f||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function xn({className:t,variant:n="outline"}){var o;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const r=s.useEditorStore(i=>i.card);os(((o=r.customCardPreferences)==null?void 0:o.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),r.sql;const l=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:c}=Ae();function d(){const i=c();l==null||l(i)}return e.jsxs(s.Button,{onClick:d,className:s.cn("h-8",t),size:"sm",variant:n,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function pn({className:t,variant:n="default"}){const a=s.useQueryClient(),[r,l]=k.useState(!1),c=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),{setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:o}=Ae(),i=s.useSelectedVisual(),u=s.useEditorStore(h=>h.frame),m=s.useUpdateVisualMutation(),x=()=>{const h=o(),p=(u==null?void 0:u.visualId)||(i==null?void 0:i.id);if(!p){s.ue.error("No visual to save");return}l(!0),m.mutate({visualId:p,data:{frameObject:h}},{onSuccess:()=>{l(!1),c(!0),s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["resource-by-id","visual",p],exact:!0})},onError:()=>{l(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:x,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(Fe,{className:"mr-2 size-4 font-bold"}),"Save to Library"]})]})}function fn({className:t}){const n=s.useQueryClient(),[a,r]=k.useState(!1),l=s.useSelectedVisual(),c=s.useEditorStore(h=>h.frame),d=s.useDashboardStore(h=>h.selectedSheetId),{updateFrame:o,setIsVisualEditing:i}=s.useDashboardActions(),{getUpdatedFrame:u}=Ae(),m=s.useUpdateVisualMutation(),x=async()=>{if(!d){s.ue.error("No sheet selected");return}const h=(c==null?void 0:c.visualId)||(l==null?void 0:l.id);if(!h){s.ue.error("No visual to update");return}r(!0);try{const p=u();await m.mutateAsync({visualId:h,data:{frameObject:p}});const b={...p,visualId:h};o(d,b),n.invalidateQueries({queryKey:["visuals"]}),n.invalidateQueries({queryKey:["visual",h]}),s.ue.success("Saved to library and applied locally"),setTimeout(()=>{i(!1)},300)}catch(p){console.error("Failed to save and apply:",p),s.ue.error("Failed to save and apply changes")}finally{r(!1)}};return e.jsx(s.Button,{onClick:x,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(Fe,{className:"mr-2 size-4 font-bold"}),"Save & Apply"]})})}function gn({className:t}){const{getUpdatedFrame:n}=Ae();s.useEditorStore(i=>i.frame);const a=s.useDashboardStore(i=>i.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[c,d]=k.useState(!1),o=()=>{if(!a){s.ue.error("No sheet selected");return}d(!0);const u={...n(),visualId:void 0};r(a,u),setTimeout(()=>{d(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:o,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[c&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!c&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function jn({className:t}){const{setTempQueryData:n,setSqlGen:a}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),c=s.useEditorStore(u=>u.onClose),d=s.useEditorStore(u=>u.card),{queryKey:o}=s.useDashboardCardQuery(d);function i(){if(l){const{queryKey:u,queryData:m}=l;u&&m&&r.setQueryData(u,m)}a({}),c==null||c()}return e.jsxs(s.Button,{onClick:i,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function is(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient();s.useEditorStore(f=>f.isDevMode);const a=s.useEditorStore(f=>f.tempQueryData),r=s.useEditorStore(f=>f.card),{queryKey:l}=s.useDashboardCardQuery(r),{setCardSql:c,setSqlGen:d,setCardPython:o,setCardCustomCfg:i,setCardPreferences:u,updateDataSource:m,clearQueryConfig:x,setCardConfig:h,setCardType:p}=s.useEditorActions();function b(){const f=n.getQueryData(l);a!=null&&a.queryData||t({queryKey:l,queryData:f}),n.setQueryData(l,null),n.removeQueries({queryKey:l,exact:!0}),c(""),d({}),x(),h(void 0),o(""),i(""),u({}),p("bar")}return e.jsxs(s.Button,{onClick:b,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(Ht,{className:"mr-2 size-4"}),"Clear"]})}function bn(){const[t,n]=k.useState(!1),[a,r]=k.useState(!1),[l,c]=k.useState(null),d=s.useEditorStore(A=>A.frame),o=s.useEditorStore(A=>A.card),i=s.useSelectedVisual(),u=s.useDashboardStore(A=>A.selectedSheetId),m=s.useDashboardStore(A=>A.actions.setIsDashboardPanelOpen),{getUpdatedFrame:x}=Ae(),{selectVisual:h}=s.useManagementActions(),{addFrame:p,setSelectedFrameId:b,setIsVisualEditing:f}=s.useDashboardActions(),j=!!(d!=null&&d.visualId),N=(i==null?void 0:i.title)||(o==null?void 0:o.title)||"Untitled Visual",C=s.useCreateVisualWithFrame(A=>{if(A!=null&&A.id){if(h(A),a&&l&&u){const w={...l,id:s.v4(),visualId:A.id};p(u,w,"end"),b(w.id),r(!1),c(null),f(!1)}m(!0),n(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:n,handleSaveAs:async A=>{if(!u){s.ue.error("No sheet selected");return}const w=x();if(A.saveToLibrary){r(A.saveToCurrentDashboard),c(w);const D={title:A.name,description:A.description,frameObject:w,isPrivate:!1};C.mutate(D)}else if(A.saveToCurrentDashboard){const D={...w,id:s.v4(),visualId:void 0,cards:w.cards.map(g=>({...g,title:g.id===o.id?A.name:g.title}))};p(u,D,"end"),b(D.id),s.ue.success("Visual saved to dashboard"),n(!1),f(!1)}},isLibraryVisual:j,currentVisualName:N,isSaving:C.isPending}}function rt({className:t}){const n=s.useEditorStore(C=>C.frame),a=s.useEditorStore(C=>C.card),r=s.useManagementStore(C=>C.selectedVisual),l=s.useDashboardStore(C=>C.selectedFrameId),c=s.useDashboardStore(C=>C.selectedSheetId),{setIsVisualEditing:d}=s.useDashboardActions(),o=!!(n!=null&&n.visualId||r!=null&&r.id),i=!!(n!=null&&n.visualId&&l),u=o&&!i,{saveAsDialogOpen:m,setSaveAsDialogOpen:x,handleSaveAs:h,isLibraryVisual:p,currentVisualName:b,isSaving:f}=bn(),{handleAddLibraryVisual:j}=Ae(),N=async()=>{if(!c){s.ue.error("No dashboard sheet selected");return}if(!r){s.ue.error("No visual selected");return}const C=await j(r);C.success?(s.ue.success("Visual added to dashboard"),d(!1)):s.ue.error(C.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[!o&&e.jsx(xn,{className:t,variant:"default"}),o&&e.jsxs(e.Fragment,{children:[i&&e.jsx(gn,{className:t}),u&&c&&a&&(a.sql||s.hasValidCardConfig(a.config))&&e.jsxs(s.Button,{onClick:N,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(Gt,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),u&&e.jsx(pn,{className:t,variant:"default"}),i&&e.jsx(fn,{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:C=>{C.stopPropagation(),x(!0)},children:[e.jsx(Fe,{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:()=>x(!0),children:[e.jsx(Fe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(jn,{className:t}),e.jsx(hn,{open:m,onOpenChange:C=>{f||x(C)},isLibraryVisual:p,currentVisualName:b,isSaving:f,onConfirm:h})]})}function lt({className:t,labelClassName:n,switchClassName:a}){const r=s.useEditorStore(i=>i.isDevMode),l=s.useDashboardStore(i=>i.isVisualEditing),{setIsDevMode:c}=s.useEditorActions(),{config:d}=k.useContext(s.SemaphorContext).tokenProps,o=(d==null?void 0:d.showAdvancedMode)!==!1;return!l||!o?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:()=>c(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:s.cn("text-sm font-medium",n),children:"Advanced Mode"})]})}function vn(){var fe,ue,K;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:c}=s.useRoleAwareDisplayPreferences(),d=s.useHasDashboardId();s.useDashboardStore(_=>_.theme);const o=s.useDashboardStore(_=>_.lenses),i=s.useDashboardStore(_=>_.selectedLensId),u=o==null?void 0:o.find(_=>_.id===i),m=s.useDashboardStore(_=>_.dashboard);s.useDashboardStore(_=>_.selectedSheetId);const x=s.useDashboardStore(_=>_.isDashboardEditing),[h,p]=k.useState(!1),[b,f]=k.useState(!1),[j,N]=k.useState(!1),C=s.useDashboardStore(_=>_.isDashboardPanelOpen),L=s.useDashboardStore(_=>_.actions.setIsDashboardPanelOpen),A=s.useDashboardStore(_=>_.filterValues),w=s.useDashboardStore(_=>_.isVisualEditing),D=s.useEditorStore(_=>_.card),g=s.useManagementStore(_=>_.selectedDashboard),y=s.useManagementStore(_=>_.initialDashboard),v=s.useManagementStore(_=>_.selectedVisual);s.useDashboardStore(_=>_.selectedFrameId),s.useEditorStore(_=>_.frame);const R=g?(ue=g==null?void 0:g.permissions)==null?void 0:ue.canEdit:(fe=y==null?void 0:y.permissions)==null?void 0:fe.canEdit,S=s.useDashboardStore(_=>_.showFilters),F=s.useDashboardStore(_=>_.showDashboardJSON),I=s.useDashboardStore(_=>_.onSaveFunction),T=s.useDashboardStore(_=>_.actions.setShowFilters),{setIsDashboardEditing:M,setShowDashboardJSON:O}=s.useDashboardStore(_=>_.actions),{setInitialDashboard:E,clearSelectedDashboard:P}=s.useManagementStore(_=>_.actions),{resources:B}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:q}=s.useCurrentUserInfo(),Y=s.canUserManageGroups(q),z=g||y,W=z?{id:z.id,title:(m==null?void 0:m.title)||z.title||"Dashboard"}:null,{handleAddNewFrame:X}=s.useAddNewFrame(),[se,te]=k.useState(!1),ie=s.useUpdateResource(s.ResourceType.DASHBOARD);k.useEffect(()=>{if(B&&B.length>0){const _=m==null?void 0:m.id;if(_){const V=B.find(Z=>Z.id===_);V&&E(V)}}},[B,m==null?void 0:m.id,E]);const H=n.orgUserId||n.tenantId,$=x&&!w&&H&&R,ae=()=>{M(!0)};async function Q(){const _=Ke(m);te(!0);const V={template:_};ie.mutate({resourceId:_.id,data:V},{onSuccess:()=>{te(!1),s.ue.success("Dashboard saved!")},onError:()=>{te(!1),s.ue.error("Failed to save dashboard")}})}async function re(){if(p(!0),!i||!u)return;const _=Ke(m),V=JSON.stringify(_),Z={...u,template:V,filterValues:A};await ts(n.apiServiceUrl,Z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),I==null||I(_),p(!1)}const U=(u==null?void 0:u.name)||m.title,ce=B&&B.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),le=g&&!(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-2",children:[ce&&e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>{L(!C)},className:"h-7 p-2",children:e.jsx(ia,{className:"h-4 w-4"})}),le&&!w&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Dashboard Hub",onClick:()=>P(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})})]}),!w&&d&&e.jsx(s.Label,{children:U}),w&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm font-medium",children:(v==null?void 0:v.title)||(D==null?void 0:D.title)||"Untitled Visual"}),e.jsx(at,{})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[w&&e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"mr-2"}),e.jsx(rt,{className:"h-7"})]}),r&&!w&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(xa,{className:"h-4 w-4"})}),!w&&d&&e.jsx(ka,{}),!w&&d&&e.jsx(qs,{}),!w&&d&&Y&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>N(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!w&&d&&((K=z==null?void 0:z.permissions)==null?void 0:K.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(Ee,{className:"h-4 w-4"})}),!S&&!w&&x&&c.canUseFilters&&d&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>T(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),x&&!w&&H&&r&&d&&e.jsx(Da,{}),!w&&H&&r&&d&&e.jsx(Ta,{}),x&&!w&&H&&u&&r&&d&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:h,onClick:re,size:"sm",children:[e.jsx(Fe,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),x&&!w&&d&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!x,onClick:()=>X(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!w&&!x&&c.canEdit&&d&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:ae,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),$&&d&&e.jsxs(s.Button,{className:"h-7 p-2",disabled:se,onClick:Q,size:"sm",children:[se?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Fe,{className:"mr-2 h-4 w-4"}),se?"Saving...":"Save"]}),!w&&x&&r&&d&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>O(!F),size:"sm",variant:"ghost",children:e.jsx(Us,{className:"h-4 w-4"})})}),!w&&r&&e.jsx(Na,{}),x&&!w&&d&&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"]}),b&&W&&e.jsx(We,{resource:W,resourceType:s.ResourceType.DASHBOARD,onClose:()=>f(!1)}),e.jsx(ln,{open:j,onOpenChange:N})]})]})}function cs(t){const{tokenProps:n,authToken:a}=s.useSemaphorContext(),r=n==null?void 0:n.apiServiceUrl;return s.useQuery({queryKey:["joinability-map",t],queryFn:async()=>{if(!t||!(a!=null&&a.accessToken))return null;const l=`${r}/v1/domains/${t}/joinability`;return s.getRequest(l,a.accessToken)},enabled:!!t&&!!(a!=null&&a.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:l=>Math.min(1e3*2**l,3e4)})}function Ve(t,n,a){if(n==="source")return{isValid:!0};const r=s.getDataType(t.dataType);if(a==="kpi"){if(n==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(n==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function as(t,n,a,r,l){if(t!=="kpi"||l.length<3)return;const c=(n==null?void 0:n.groupByColumns)&&n.groupByColumns.length>0,d=(n==null?void 0:n.comparisonType)==="none";!c&&d||a(r,{groupByColumns:[],comparisonType:"none"})}const ds=t=>{var I;const n=(I=t==null?void 0:t.dataSource)==null?void 0:I.semanticDomainId,{data:a}=cs(n),{updateCardConfig:r,updateGroupByColumn:l,updateMetricColumn:c,updatePivotByColumn:d,updateSortByColumn:o,removeGroupByColumn:i,removeMetricColumn:u,removePivotByColumn:m,removeSortByColumn:x}=s.useEditorActions(),h=s.useEditorStore(T=>T.card.type),p=t==null?void 0:t.id,b=k.useCallback(T=>{if(!(t!=null&&t.config))return[];switch(T){case"groupBy":return(t.config.groupByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,dateFormat:M.dateFormat,customFormat:M.customFormat,granularity:M.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,direction:M.direction}));case"source":return[];default:return[]}},[t]),f=k.useCallback((T,M)=>{if(p)switch(T){case"groupBy":{r(p,{groupByColumns:M});break}case"metrics":{r(p,{metricColumns:M});break}case"pivotBy":{r(p,{pivotByColumns:M});break}case"sortBy":{r(p,{sortByColumns:M});break}}},[p,r]),j=k.useCallback((T,M,O)=>{if(!p)return;const P=b(T)[M];if(P)switch(T){case"groupBy":l(p,P.id,{label:O});break;case"metrics":c(p,P.id,{label:O});break;case"pivotBy":d(p,P.id,{label:O});break;case"sortBy":o(p,P.id,{label:O});break}},[p,b,l,c,d,o]),N=k.useCallback((T,M)=>{if(!p)return;const E=b("metrics")[T];E&&c(p,E.id,{aggregate:M,label:s.getAggregationLabel(E.name,M)})},[p,b,c]),C=k.useCallback((T,M,O)=>{if(!p)return;const P=b("groupBy")[T];if(!P)return;const B={dateFormat:M};M==="custom"&&O?B.customFormat=O:B.customFormat=void 0,l(p,P.id,B)},[p,b,l]),L=k.useCallback((T,M)=>{if(!p)return;const E=b("groupBy")[T];E&&l(p,E.id,{granularity:M})},[p,b,l]),A=k.useCallback((T,M)=>{if(!p)return;const E=b("metrics")[T];E&&c(p,E.id,{aliasTemplate:M})},[p,b,c]),w=k.useCallback((T,M)=>{if(console.log("handleValueAliasesChange",T,M),!p)return;console.log("handleValueAliasesChange",T,M);const E=b("metrics")[T];E&&(console.log("handleValueAliasesChange",M),c(p,E.id,{valueAliases:M}))},[p,b,c]),D=k.useCallback(T=>{if(!p)return;if(b("metrics").length===0){s.ue.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:T})},[p,r,b]),g=k.useCallback(T=>{p&&r(p,{showTrendline:T})},[p,r]),y=k.useCallback(T=>{p&&r(p,{trendlineWindow:T})},[p,r]),v=k.useCallback(T=>{p&&r(p,{trendlineGranularity:T})},[p,r]),R=k.useCallback(T=>{p&&r(p,{targetValue:T})},[p,r]),S=k.useCallback(T=>{var Y;if(!p)return;const M=[...b("groupBy"),...b("pivotBy"),...b("metrics"),...b("sortBy")],O=s.validateEntityConsistency(T,M,{joinPlan:(Y=t==null?void 0:t.config)==null?void 0:Y.joinPlan,joinabilityMap:a==null?void 0:a.joinabilityMap,semanticDomainId:n});if(!O.isValid){O.showError&&s.showJoinRequiredNotification();return}const E=s.getSmartContainerForField(T,M,h);if(!E){s.ue.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const P=Ve(T,E,h);if(!P.isValid){s.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3});return}const B=b(E);if(s.fieldAlreadyExists(T,B))return;const q=s.getNewField(T,E,B);if(q){const z=[...B,q];f(E,z),E==="metrics"&&as(h,t==null?void 0:t.config,r,p,z)}},[p,t==null?void 0:t.config,b,f,n,a,h,r]),F=k.useCallback((T,M)=>{if(!p)return;const E=b(T)[M];if(E){if(T!=="sortBy"){const P=b("sortBy"),B=P.filter(q=>!(q.name===E.name&&q.qualifiedEntityName===E.qualifiedEntityName));B.length!==P.length&&r(p,{sortByColumns:B})}switch(T){case"groupBy":i(p,E.id);break;case"metrics":u(p,E.id);break;case"pivotBy":m(p,E.id);break;case"sortBy":x(p,E.id);break}}},[p,b,i,u,m,x,r]);return{getFieldsForContainer:b,setFieldsForContainer:f,updateLabel:j,handleAggregationChange:N,handleDateFormatChange:C,handleGranularityChange:L,handleAliasTemplateChange:A,handleValueAliasesChange:w,removeField:F,handleFieldClick:S,handleKpiComparisonTypeChange:D,handleKpiShowTrendlineChange:g,handleKpiTrendlineWindowChange:y,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:R,cardType:h}};function _e(t){return`${t}-${s.v4()}`}function ks(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 yn(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 us(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:t==null?void 0:t.connectionId,connectionType:t==null?void 0:t.connectionType};const n=t.selectedEntities[0];return{tableName:n==null?void 0:n.name,schemaName:n==null?void 0:n.schema,databaseName:n==null?void 0:n.database,connectionId:t.connectionId,connectionType:t.connectionType}}function ot(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return!1;const n=t.selectedEntities[0];return!!(n!=null&&n.name)}function it(){const t=s.useEditorStore(D=>D.sqlGen),n=s.useEditorStore(D=>D.isDevMode),a=s.useEditorStore(D=>D.card.dataSource),r=s.useEditorStore(D=>{var g,y;return(y=(g=D.card)==null?void 0:g.queryConfig)==null?void 0:y.metricColumns}),{tableName:l,schemaName:c,databaseName:d}=us(a),o=ot(a),i=s.useEditorStore(D=>D.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:m,setCardSql:x,setRunSql:h,setSqlGen:p,setIsShowingVisual:b}=s.useEditorActions(),{connectionType:f,modelItems:j,selectedDatamodelName:N}=s.useEditorAside(),C=D=>({column_name:D.name,data_type:D.dataType,label:D.label,description:D.description});return{handleDevModeFieldClick:D=>{var y;if(!n)return;const g=C(D);if(n&&o&&l){const v=s.createSqlGenConfig(g,t);p(v);const R=(y=j==null?void 0:j.find(F=>F.id===i))==null?void 0:y.name,S=s.getSql(v,s.fmt(c||""),s.fmt(l),R||"",f,d||"");S&&(x(S),h(!0))}else if(!n){if(s.isTextDataType(g.data_type))if(r&&r.length>0){const v={...g,role:"groupby",id:_e(g.column_name),name:g.column_name,type:g.data_type};m(v)}else{const v={...g,role:"metric",id:_e(g.column_name),name:g.column_name,label:ks(g.column_name,"COUNT"),type:g.data_type,aggregate:"COUNT"};u(v)}if(s.isDateDataType(g.data_type)){const v={...g,role:"groupby",id:_e(g.column_name),name:g.column_name,type:g.data_type,label:yn(g.column_name,"month"),granularity:"month"};m(v)}if(s.isNumberDataType(g.data_type)){const v={...g,role:"metric",id:_e(g.column_name),name:g.column_name,label:ks(g.column_name,"SUM"),type:g.data_type,aggregate:"SUM"};u(v)}}},handleShowSample:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const D=s.getFormattedTableNameForQuery({schemaName:c||"",tableName:l,modelName:N,connectionType:f,databaseName:d||""});b(!1);const g=f==="MSSQL"?`SELECT top 10 * FROM ${D}`:`SELECT * FROM ${D} LIMIT 10`;x(g),h(!0)},handleShowCount:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const D=s.getFormattedTableNameForQuery({schemaName:c||"",tableName:l,modelName:N,connectionType:f,databaseName:d||""});x(`SELECT COUNT(*) as count FROM ${D}`),h(!0)},isNumberField:D=>s.isNumberDataType(D.dataType)}}function ct(){const t=s.useEditorStore(p=>p.selectedConnectionId),n=s.useEditorStore(p=>p.selectedDatamodelId),a=s.useEditorStore(p=>p.selectedDatabaseName),r=s.useEditorStore(p=>p.selectedSchemaName),l=s.useEditorStore(p=>p.selectedTableName),c=s.useDashboardStore(p=>p.dashboard.filters)||[],d=s.useDashboardStore(p=>p.actions.addFilter),o=s.useDashboardStore(p=>p.actions.removeFilter),{removeFilterValues:i}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:x}=s.useEditorAside();function h(p,b="dashboard",f){var y;const j=s.fmt(p.column_name),N=s.fmt(a||""),C=s.fmt(r||""),L=s.fmt(m);let A=s.getQualifiedTableName({schemaName:C,tableName:L,connectionType:x,databaseName:N}),w=`${A}.${j}`;const D=(y=u==null?void 0:u.find(v=>v.id===n))==null?void 0:y.name;n&&n!=="none"&&(w=`${s.DATAMODEL_NAMESPCACE}.${D}.${j}`,A=`${s.DATAMODEL_NAMESPCACE}.${D}`),f!=null&&f.qualifiedFieldName&&(w=f.qualifiedFieldName),f!=null&&f.entityName&&(A=f.entityName);const g=c==null?void 0:c.find(v=>v.column===w&&v.table===L&&(v.database===N||v.database===a));if(g)i(g.id),o(g.id);else{const v=s.v4();return m==="api"&&t?(d({location:b,id:v,column:w,title:p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(p.data_type,A,j)}),v):(d({id:v,location:b,column:w,title:p.column_name,dataType:p.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(p.data_type,A,j)}),v)}}return{assignFilter:h}}function Nn({column:t}){const[n,a]=k.useState(!1),r=s.useEditorStore(N=>N.card.dataSource),{tableName:l,schemaName:c,databaseName:d}=us(r),o=s.useEditorStore(N=>N.selectedDatamodelId),i=s.useEditorStore(N=>N.sqlGen),{modelItems:u,connectionType:m}=s.useEditorAside(),x=s.useEditorStore(N=>N.actions.setSqlGen),h=s.useEditorStore(N=>N.actions.setCardSql),p=s.useEditorStore(N=>N.actions.setRunSql),b=ot(r);function f(N,C){var D;if(!b||!l){console.warn("Cannot generate SQL: missing table metadata");return}const L=s.createSqlGenConfig(N,i,C),A=(D=u==null?void 0:u.find(g=>g.id===o))==null?void 0:D.name;x(L);const w=s.getSql(L,s.fmt(c||""),s.fmt(l),A||"",m,d||"");w&&(h(w),p(!0)),a(!1)}function j(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>f(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>f(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>f(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>f(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>f(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return b?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/container:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:j()})]}):null}function Cn({field:t,fieldState:n}){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}),n&&n.tooltip&&e.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:n.tooltip})}),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 Sn({field:t,context:n="editor",fieldState:a}){const r=s.useEditorStore(S=>S.isDevMode),l=n==="filter",c=r||l||(a==null?void 0:a.state)==="unreachable"&&!l,d=s.useDashboardStore(S=>S.dashboard.filters),{assignFilter:o}=ct(),i=l&&(d==null?void 0:d.some(S=>{var F;return S.title===t.name||((F=S.column)==null?void 0:F.includes(t.name))})),{attributes:u,listeners:m,setNodeRef:x,transform:h,transition:p,isDragging:b}=s.useSortable({id:t.id,disabled:c}),[f,j]=k.useState(!1),N=s.useEditorStore(S=>S.card),{handleFieldClick:C}=ds(N),{handleDevModeFieldClick:L,isNumberField:A}=it(),w=()=>{if(l){const S={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description};o(S,"dashboard",t)}else r?L(t):C(t)},D={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description},g={transform:s.CSS.Transform.toString(h),transition:p},v=(()=>{if(!a||l)return{};const F={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[a.state]||{};return a.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...F},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...F},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...F}}[a.state]||F})(),R=S=>{const F=(S||"").toLowerCase(),I=s.getDataType(F);return I==="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(qe,{className:"h-3 w-3"})}):I==="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(rs,{className:"h-3 w-3"})}):I==="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"})}):I==="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($s,{className:"h-3 w-3"})}):I==="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(Us,{className:"h-3 w-3"})}):I==="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(oa,{className:"h-3 w-3"})}):I==="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(zs,{className:"h-3 w-3"})}):null};return e.jsxs("div",{ref:x,style:g,...c?{}:u,...c?{}:m,className:s.cn("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",b&&"scale-95 opacity-50",!b&&"border",v.borderColor||"border-transparent",v.bgColor||"",v.hoverBorderColor,v.hoverBgColor||"hover:bg-muted",v.opacity,v.cursor,i&&"bg-accent border-accent-foreground/20",{"cursor-pointer":r||l,"cursor-grab active:cursor-grabbing":!c&&!r&&!l}),title:a==null?void 0:a.tooltip,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:w,children:[R(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-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${f?"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(Cn,{field:t,fieldState:a})})]})}),r&&!l&&A(t)&&e.jsx("div",{onClick:S=>S.stopPropagation(),children:e.jsx(Nn,{column:D})})]}),f&&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(Gs,{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(ba,{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 wn({context:t="editor"}={}){var I,T,M,O;const[n,a]=k.useState(""),[r,l]=k.useState("all"),c=s.useEditorStore(E=>E.isDevMode),d=s.useEditorStore(E=>E.card.dataSource),o=s.useEditorStore(E=>E.card.config),i=s.useEditorStore(E=>E.card),{autoJoinMetadata:u}=s.useDashboardCardQuery(i),{columns:m=[],columnGroups:x=[],isLoading:h,error:p}=s.useColumns(),b=(d==null?void 0:d.mode)==="semanticDomain"?d.semanticDomainId:void 0,{data:f}=cs(b),j=[...(o==null?void 0:o.groupByColumns)||[],...(o==null?void 0:o.metricColumns)||[]];(T=(I=o==null?void 0:o.joinPlan)==null?void 0:I.baseEntity)==null||T.name,(O=(M=u==null?void 0:u.resolvedJoinPlan)==null?void 0:M.baseEntity)==null||O.name;const{handleShowSample:N,handleShowCount:C}=it(),L=m.filter(E=>E.name.toLowerCase().includes(n.toLowerCase())||E.dataType.toLowerCase().includes(n.toLowerCase())||E.label&&E.label.toLowerCase().includes(n.toLowerCase())||E.qualifiedEntityName&&E.qualifiedEntityName.toLowerCase().includes(n.toLowerCase())),A=E=>{if(E.dataType==="number"||E.dataType==="integer"||E.dataType==="float"||E.dataType==="decimal"||E.dataType==="currency")return"metrics";const P=s.getDataType(E.dataType);return["date","string","boolean"].includes(P)?"dimensions":P==="number"?"metrics":"dimensions"},D=(r==="all"?L:L.filter(E=>A(E)===r)).reduce((E,P)=>{const B=P.qualifiedEntityName||"Other Fields";return E[B]||(E[B]={label:s.toLabel(P.entityName),fields:[]}),E[B].fields.push(P),E},{}),y=Object.keys(D),v=L.filter(E=>A(E)==="dimensions").length,R=L.filter(E=>A(E)==="metrics").length,S=L.filter(E=>A(E)==="calculated").length,F=L.length>0;return h?e.jsx("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):p?e.jsxs("div",{className:"flex h-full 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:p.message||"Failed to load column data"})]}):!d||!d.selectedEntities||d.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:t==="filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-full 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:[c&&t!=="filter"&&m.length>0&&e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:h,onClick:N,size:"sm",variant:"secondary",className:"grow",children:[h?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(la,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:h,onClick:C,size:"sm",variant:"secondary",className:"grow",children:[h?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(pa,{className:"mr-2 size-4"}),"Count"]})]}),m.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:n,onChange:E=>a(E.target.value)}),n&&e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>a(""),type:"button",children:e.jsx(s.X,{className:"size-3.5"})})]}),F&&e.jsx(s.Tabs,{defaultValue:"all",value:r,onValueChange:E=>l(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:L.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:v})]}),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:R})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(zs,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:S})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:y,className:"space-y-2",children:Object.entries(D).map(([E,P])=>{const B=x.find(q=>q.entityName===E)||{entityName:E,label:P.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:B.label||B.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:B.label||B.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:P.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:P.fields.map(q=>{const Y=s.calculateFieldState(q,{joinabilityMap:(f==null?void 0:f.joinabilityMap)||null,selectedFields:j,cardConfig:o,autoJoinMetadata:u});return e.jsx(Sn,{field:q,context:t,fieldState:Y},q.id)})})})]},E)})}),Object.keys(D).length===0&&m.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:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(D).length===0&&m.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 dt({context:t="editor"}={}){return e.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",e.jsx(wn,{context:t})," "]})}function Dn({initialJoinPlan:t,availableDataSources:n}){const[a,r]=k.useState(t),[l,c]=k.useState(new Set),d=()=>{const D=a.joins.length>0?Math.max(...a.joins.map(y=>y.sequence))+1:1,g={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,g]}),c(new Set([...l,g.id]))},o=D=>{r({...a,joins:a.joins.filter(g=>g.id!==D)}),c(new Set([...l].filter(g=>g!==D)))},i=(D,g)=>{var S,F;const y=a.joins.find(I=>I.id===D);if(!y)return;const v={...y,...g},R=a.joins.map(I=>I.id===D?v:I);if((S=v.source)!=null&&S.name&&((F=v.target)!=null&&F.name)&&v.joinKeyGroups[0].keys.length===0){const I=n.find(E=>{var P;return E.name===((P=v.source)==null?void 0:P.name)}),T=n.find(E=>{var P;return E.name===((P=v.target)==null?void 0:P.name)}),M={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},operator:"="},O=[...v.joinKeyGroups];O[0]={...O[0],keys:[M]},v.joinKeyGroups=O,R[R.findIndex(E=>E.id===D)]=v}r({...a,joins:R})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:d,removeJoin:o,updateJoin:i,moveJoinUp:D=>{const g=a.joins.findIndex(y=>y.id===D);if(g>0){const y=[...a.joins],v={...y[g]},R={...y[g-1]};y[g]=R,y[g-1]=v,y.forEach((F,I)=>{F.sequence=I+1});const S={...a,joins:y};r(S)}},moveJoinDown:D=>{const g=a.joins.findIndex(y=>y.id===D);if(g<a.joins.length-1){const y=[...a.joins],v={...y[g]},R={...y[g+1]};y[g]=R,y[g+1]=v,y.forEach((F,I)=>{F.sequence=I+1});const S={...a,joins:y};r(S)}},toggleJoinExpansion:D=>{const g=new Set(l);g.has(D)?g.delete(D):g.add(D),c(g)},getAvailableSourceEntities:D=>{if(a.joins.length===0)return n;const g=a.joins.findIndex(v=>v.id===D);if(g===0)return n;const y=new Set;return a.baseEntity.name&&y.add(a.baseEntity.name),a.joins.slice(0,g).forEach(v=>{y.add(v.source.name),y.add(v.target.name)}),n.filter(v=>y.has(v.name))},getAvailableTargetEntities:D=>n.filter(g=>g.name!==D),addJoinKeyGroup:D=>{const g=a.joins.find(v=>v.id===D);if(!g)return;const y=[...g.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];i(D,{joinKeyGroups:y})},updateGroupOperator:(D,g,y)=>{const v=a.joins.find(S=>S.id===D);if(!v)return;const R=[...v.joinKeyGroups];R[g]={...R[g],operator:y},i(D,{joinKeyGroups:R})},removeJoinKeyGroup:(D,g)=>{const y=a.joins.find(R=>R.id===D);if(!y)return;const v=[...y.joinKeyGroups];v.splice(g,1),i(D,{joinKeyGroups:v})},addJoinKey:(D,g)=>{const y=a.joins.find(I=>I.id===D);if(!y)return;const v=n.find(I=>I.name===y.source.name),R=n.find(I=>I.name===y.target.name),S=[...y.joinKeyGroups],F={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(v==null?void 0:v.name)||"",entityName:(v==null?void 0:v.name)||"",entityType:(v==null?void 0:v.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(R==null?void 0:R.name)||"",entityName:(R==null?void 0:R.name)||"",entityType:(R==null?void 0:R.type)||"table"},operator:"="};S[g]={...S[g],keys:[...S[g].keys,F]},i(D,{joinKeyGroups:S})},updateJoinKey:(D,g,y,v,R)=>{const S=a.joins.find(O=>O.id===D);if(!S)return;const F=n.find(O=>O.name===S.source.name),I=n.find(O=>O.name===S.target.name),T=[...S.joinKeyGroups],M=T[g].keys[y];v==="sourceColumnName"&&F?T[g].keys[y]={...M,source:{...M.source,name:R}}:v==="targetColumnName"&&I?T[g].keys[y]={...M,target:{...M.target,name:R}}:v==="operator"&&(T[g].keys[y]={...M,operator:R}),i(D,{joinKeyGroups:T})},removeJoinKey:(D,g,y)=>{const v=a.joins.find(S=>S.id===D);if(!v)return;const R=[...v.joinKeyGroups];R[g].keys.splice(y,1),i(D,{joinKeyGroups:R})},generateSQLPreview:()=>{const D=[...a.joins].sort((v,R)=>v.sequence-R.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let y=`SELECT *
|
|
256
|
+
*/const ya=s.createLucideIcon("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);function Na(){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(ga,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(ca,{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 Ke(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 c;return{...l,cards:(c=l.cards)==null?void 0:c.map(d=>Ys(d))}})}})}}function Ys(t){return{...t,customCfg:Ca(t.customCfg),data:[]}}function Ca(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 Sa(t,n,a,r,l){if(!l)return null;const c=JSON.stringify(a),d=`${t}/v1/lens`;return await s.postRequest(d,l,{name:n,template:c,filterValues:r,operation:"create"})}async function ts(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:c,isDefault:d,shared:o}=n,i=`${t}/v1/lens`;return await s.postRequest(i,a,{lensId:r,template:l,filterValues:c,isDefault:d,shared:o,operation:"update"})}async function wa(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function Da(){const[t,n]=k.useState(""),[a,r]=k.useState(!1),l=s.useDashboardStore(j=>j.lenses),{setLenses:c,setSelectedLensId:d}=s.useDashboardActions(),[o,i]=k.useState(!1),[u,m]=k.useState(!1),x=s.useDashboardStore(j=>j.dashboard),h=s.useDashboardStore(j=>j.filterValues),{authToken:p,tokenProps:b}=s.useSemaphorContext();async function f(){i(!0);const j=Ke(x),N=await Sa(b.apiServiceUrl,t,j,h,p==null?void 0:p.accessToken);N&&(c([...l||[],N]),d(N.id),m(!1)),i(!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:f,disabled:o,children:o?"Creating...":"Add"})})]})]})}function Ta(){const[t,n]=k.useState(!1),a=s.useDashboardStore(x=>x.lenses),r=s.useDashboardStore(x=>x.selectedLensId),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),{authToken:d,tokenProps:o}=s.useSemaphorContext();async function i(x){c(x)}async function u(x){if(await wa(o.apiServiceUrl,x,d==null?void 0:d.accessToken)){const p=a==null?void 0:a.filter(b=>b.id!==x);l(p||[]),c("original")}}async function m(x){const h=a==null?void 0:a.map(f=>f.id===x.id?{...f,isDefault:!x.isDefault}:{...f,isDefault:!1});l(h||[]);const p={...x,isDefault:!x.isDefault};await ts(o.apiServiceUrl,p,d==null?void 0:d.accessToken);const b=a==null?void 0:a.find(f=>f.isDefault);if(b&&b.id!==x.id){const f={...b,isDefault:!1};await ts(o.apiServiceUrl,f,d==null?void 0:d.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(ea,{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:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(x=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:x.id,children:[e.jsx("p",{children:x.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),m(x)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!x.isDefault,"text-green-500":x.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),u(x.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},x.id))]})]})]})}function ka({iconClassName:t}){const[n,a]=k.useState(!1),[r,l]=k.useState(""),[c,d]=k.useState(!1),o=s.useDashboardStore(x=>x.isDownloadingPdf),{tokenProps:i}=s.useSemaphorContext();async function u(){const x=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(i.apiServiceUrl),s.ue.dismiss(x),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(h){s.ue.dismiss(x),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",h)}}async function m(){if(!r)return;a(!1),l(""),d(!1);const x=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(i.apiServiceUrl,r),s.ue.dismiss(x),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(h){s.ue.dismiss(x),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",h)}}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:o,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:c?"text":"password",value:r,onChange:x=>l(x.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:x=>{x.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:()=>d(!c),children:c?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 qs({triggerButtonClassName:t}){const[n,a]=k.useState(!1),r=s.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.id}),l=s.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.title}),c=s.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.sheets}),d=s.useDashboardStore(o=>o.selectedSheetId);return c==null||c.find(o=>o.id===d),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 Qe({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 Ae({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:c=!0}){var i;const d=((i=a.find(u=>u.value===t))==null?void 0:i.label)||t,o=a.filter(u=>u.value!==t);return c?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:d})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:o.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:d})}function Ks({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(c=>a(c.id)),className:"h-7 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(c=>{const d=t.find(i=>i.id===c.id),o=l(c.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[c.name,e.jsx(Ae,{currentRole:(d==null?void 0:d.role)||"VIEWER",onRoleChange:i=>r(c.id,i),roleOptions:o}),e.jsx("button",{onClick:()=>a(c.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},c.id)})}),e.jsx(s.Separator,{})]})}function Qs({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 Hs({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),c=o=>{const i=n.find(u=>u.id===o);return(i==null?void 0:i.name)||"Unknown User"},d=o=>{const i=l.find(u=>u.value===o);return(i==null?void 0:i.label)||o};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(o=>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:c(o.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:d(o.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:d(o.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(o.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id))})]})}function Ws(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=k.useRef(null);return k.useEffect(()=>{const c=d=>{const o=d.target;l.current&&l.current.contains(o)||o instanceof Element&&(o.closest("[data-radix-popper-content-wrapper]")||o.closest("[data-radix-select-content]")||o.closest("[data-radix-popover-content]")||o.closest("[data-radix-dropdown-menu-content]")||o.closest("[data-radix-tooltip-content]")||o.closest('[role="listbox"]')||o.closest('[role="option"]')||o.closest('[role="combobox"]'))||o instanceof Element&&o.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,c),()=>{document.removeEventListener(r,c)}},[t,a,r]),l}function Ne(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function Ea(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Js(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function Ia(t,n,a){const r=Js(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(o=>o.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(o=>o.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(o=>o.tenantUserId===t.id)}function Aa({user:t}){return Js(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 Ma({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:c}){if(!(n!=null&&n.role))return null;const d=Ea((r==null?void 0:r.type)||""),o=a.some(x=>x.id===t.id),i=a.find(x=>x.id===t.id),u=i?i.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:d?e.jsx(Ae,{currentRole:u,onRoleChange:x=>{c(t.id,n.role,x)},roleOptions:m,disabled:!d,allowDropdown:d,className:o?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:Ne(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function Ra({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(Ie,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function La({isUserRemoving:t,isRemoving:n}){return e.jsx(e.Fragment,{children:t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:n?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"})})}function Fa({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const d=t.shares,o=d.specificOrgUsers||[],i=d.specificTenantUsers||[],u=d.orgWide||[],m=d.orgUsersOnly||[],x=d.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:[o.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 (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((h,p)=>{var N,C;const b=((N=n.find(L=>L.id===h.orgUserId))==null?void 0:N.name)||"Unknown User",f=((C=n.find(L=>L.id===h.orgUserId))==null?void 0:C.type)||"",j=Ne(h.role,a(f));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})]},p)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),i.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 (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((h,p)=>{var N,C;const b=((N=n.find(L=>L.id===h.tenantUserId))==null?void 0:N.name)||"Unknown User",f=((C=n.find(L=>L.id===h.tenantUserId))==null?void 0:C.type)||"",j=Ne(h.role,a(f));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})]},p)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.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((h,p)=>{const b=Ne(h.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})]},p)})})]}),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((h,p)=>{const b=Ne(h.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})]},p)})})]}),x.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:x.map((h,p)=>{const b=Ne(h.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})]},p)})})]}),!o.length&&!i.length&&!u.length&&!m.length&&!x.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const d=t.shares.specificTenantUsers||[],o=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:[d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((i,u)=>{var p,b;const m=((p=n.find(f=>f.id===i.tenantUserId))==null?void 0:p.name)||"Unknown User",x=((b=n.find(f=>f.id===i.tenantUserId))==null?void 0:b.type)||"",h=Ne(i.role,a(x));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:h})]},u)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),o.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:o.map((i,u)=>{const m=Ne(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:m})]},u)})})]}),!d.length&&!o.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],d=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((o,i)=>{var h,p;const u=((h=n.find(b=>b.id===o.tenantUserId))==null?void 0:h.name)||"Unknown User",m=((p=n.find(b=>b.id===o.tenantUserId))==null?void 0:p.type)||"",x=Ne(o.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:x})]},i)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),d.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:d.map((o,i)=>{const u=Ne(o.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})]},i)})})]}),!c.length&&!d.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function Oa({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 Pa({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:c,selectedUser:d,roleOptions:o,currentUser:i,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:x,handleUpdateAccess:h,handleUserRoleChange:p}){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":c?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:c,onCheckedChange:()=>{l?a?m(t.id):x(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(Aa,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Ae,{currentRole:n==null?void 0:n.role,onRoleChange:b=>h(t.id,n.role,b),roleOptions:o,disabled:!1,allowDropdown:!0}):e.jsx(Ma,{user:t,userShare:n,usersToUpdate:u,currentUser:i,getRoleOptions:()=>o,handleUpdateAccess:h}),c&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(Ae,{currentRole:(d==null?void 0:d.role)||"VIEWER",onRoleChange:b=>p(t.id,b),roleOptions:o,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(Ra,{hasAccess:r,isUserRemoving:a,isSelected:c,hasAccessFromAPI:l}),e.jsx(La,{isUserRemoving:a,isSelected:c,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Xs({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:c,handleUserToggle:d,handleUserRoleChange:o,handleRemoveAccess:i,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),x=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate(),p=s.useShareSearchQuery(),b=s.useShareManagementActions(),f=d||(w=>{const D=m.some(y=>y.id===w),g=x.includes(w);D?b.removeSelectedUser(w):g?b.removeUserFromRemove(w):b.addSelectedUser({id:w,role:"VIEWER"})}),j=o||b.updateSelectedUserRole,N=i||b.addUserToRemove,C=u||((w,D,g)=>{b.addUserToUpdate({id:w,currentRole:D,newRole:g})}),L=l.filter(w=>w.id!==(c==null?void 0:c.id)),A=x;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 (",(L??[]).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(Fa,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:c})})]})})]}),(L==null?void 0:L.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===L.length?b.setSelectedUsers([]):b.setSelectedUsers(L.map(w=>({id:w.id,role:"VIEWER"})))},className:"h-7 text-xs",children:m.length===L.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(Oa,{isInitialLoading:n,isSearching:a,searchQuery:p,availableUsers:L||[]}),!n&&!a&&(L==null?void 0:L.length)>0&&L.map(w=>{const D=t?Ia(w,t,c):void 0,g=A.includes(w.id),y=!!D,v=y&&!g,R=m.some(I=>I.id===w.id),S=m.find(I=>I.id===w.id),F=r(w.type);return e.jsx(Pa,{user:w,userShare:D,isUserRemoving:g,hasAccess:v,hasAccessFromAPI:y,isSelected:R,selectedUser:S,roleOptions:F,currentUser:c,usersToUpdate:h,handleUserToggle:f,handleRemoveAccess:N,handleUpdateAccess:C,handleUserRoleChange:j},w.id)})]})]})}function ls({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(c=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:c.value,id:c.value,className:"peer sr-only",disabled:c.disabled}),e.jsxs(s.Label,{htmlFor:c.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 ${c.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[c.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:c.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:c.description})]})]})]},c.value))}),!l&&r.some(c=>c.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 ye=()=>[{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 Ba({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:c=!1,isUpdating:d=!1,isRemoving:o=!1}){const i=s.useShareCurrentMode(),u=ye().filter(C=>C.value==="VIEWER"||C.value==="EDITOR"||C.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",x=l?l.newRole:m,h=n.role!=="NONE"&&!c&&(!l||l.newRole===m),p=l!==null&&l.newRole!==m,b=c,f=m==="NONE"||!m,j=C=>{switch(C){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(ha,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},N=C=>{r(m,C)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",p&&!b&&!f?"border-orange-300 bg-orange-50":h?"border-green-300 bg-green-50":b||f?"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"," ",i==="allOrgUsers"?"Organization":i==="allTenantUsers"?"Tenant":i==="specificOrgUsers"?"Org":"Tenant"," ","Users",h&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),p&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(b||f)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:b||f?"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(C=>e.jsxs(s.Button,{variant:x===C.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>N(C.value),disabled:a||d||o,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(C.value),e.jsx("span",{className:"font-medium",children:C.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:C.description})]},C.value))})]})})]})})}function Zs({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:c,onRemoveAccess:d,allUsersToUpdate:o,allUsersToRemove:i}){const u=f=>f==="OWNER"?"CONTRIBUTOR":f,x=n?{role:u(n.role)}:{role:"NONE"},h=o?{currentRole:u(o.currentRole),newRole:u(o.newRole)}:null,p=(f,j)=>{c(f,j)},b=()=>{d()};return e.jsx(Ba,{currentUser:t,currentShare:x,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:p,onRemoveAccess:b,allUsersToUpdate:h,allUsersToRemove:i})}function Pe(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:c}=t,d=k.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&c?{tenantId:c}:{}}),[n,l,c]),{users:o,isLoading:i,isError:u}=s.useUnifiedUsers(d),m=s.useResourceShares(r,a);return{allUsers:o,isLoadingUsers:i,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function Va({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:c=!1,isRemoving:d=!1}){var z,J;const o=s.useShareSelectedTab(),i=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:x}=s.useShareSearchWithDebounce(),h=s.useShareSelectedUsers(),p=s.useShareUsersToRemove(),b=s.useShareUsersToUpdate(),f=s.useShareCurrentMode(),j=s.useShareOrgWideRole(),N=s.useShareManagementActions(),[C,L]=k.useState("specific_users"),A=()=>{if(o==="org")return"organization";if(o==="tenant")return"tenant"},w=()=>{if(o==="tenant"&&i)return i},{allUsers:D,existingShares:g,isLoadingUsers:y}=Pe({debouncedSearchQuery:x,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:A(),tenantId:w()});k.useEffect(()=>{N.setCurrentContext("org-tab"),N.setCurrentMode(C==="all_users"?"allOrgUsers":"specificOrgUsers")},[N,C]);const v=W=>{var te,oe;const se=W;if(L(se),r==null||r(se),N.setCurrentContext("org-tab"),se==="specific_users")N.setCurrentMode("specificOrgUsers");else if(se==="all_users"){N.setCurrentMode("allOrgUsers");const Q=(oe=(te=g==null?void 0:g.shares)==null?void 0:te.orgUsersOnly)==null?void 0:oe[0];Q&&Q.role!==void 0&&N.setOrgWideRole(Q.role)}},R=D.filter(W=>W.name.toLowerCase().includes(u.toLowerCase())||W.email.toLowerCase().includes(u.toLowerCase())),S=D.filter(W=>h.some(se=>se.id===W.id)),F=W=>{var Q,_;const se=h.some(ae=>ae.id===W),te=p.includes(W),oe=(_=(Q=g==null?void 0:g.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:_.some(ae=>ae.orgUserId===W);se?N.removeSelectedUser(W):te?N.removeUserFromRemove(W):oe||N.addSelectedUser({id:W,role:"VIEWER"})},I=(W,se)=>{N.updateSelectedUserRole(W,se)},T=W=>{N.addUserToRemove(W),N.removeSelectedUser(W)},M=W=>{N.removeUserFromRemove(W)},O=W=>{N.removeUserFromUpdate(W)},E=(W,se)=>{N.setOrgWideRole(se)},P=()=>{N.setOrgWideRole((B==null?void 0:B.role)||"NONE")},B=(J=(z=g==null?void 0:g.shares)==null?void 0:z.orgUsersOnly)==null?void 0:J[0];k.useEffect(()=>{C==="all_users"&&B&&B.role!==void 0&&N.setOrgWideRole(B.role)},[C,B,N]);const Y=y,q=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(ls,{shareType:C,onShareTypeChange:v,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??"")}]}),C==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Qe,{value:u,onChange:m}),e.jsx(Ks,{selectedUsers:h,selectedUserObjects:S,onRemove:F,onRoleChange:I,getRoleOptions:ye}),e.jsx(Qs,{usersToRemove:p,allUsers:R,onRemove:M}),e.jsx(Hs,{usersToUpdate:b,allUsers:R,onRemove:O,getRoleOptions:ye}),e.jsx(Xs,{existingShares:g,isInitialLoading:Y,isSearching:q,resource:t,onShare:()=>{},getRoleOptions:ye,allUsers:R,currentUser:a,handleUserToggle:F,handleUserRoleChange:I,handleRemoveAccess:T,handleUpdateAccess:(W,se,te)=>{N.addUserToUpdate({id:W,currentRole:se,newRole:te})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Zs,{currentUser:a,currentShare:B,isSharing:l,isUpdating:c,isRemoving:d,onUpdateAccess:E,onRemoveAccess:P,allUsersToUpdate:f==="allOrgUsers"&&j!==((B==null?void 0:B.role)||"NONE")?{currentRole:(B==null?void 0:B.role)||"NONE",newRole:j}:null,allUsersToRemove:f==="allOrgUsers"&&(B==null?void 0:B.role)===void 0})})]}):null}function za(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function Ua(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function et({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:l,currentUser:c,handleGroupToggle:d,handleGroupRoleChange:o,handleRemoveAccess:i,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),p=s.useShareManagementActions(),b=l(c==null?void 0:c.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(f=>{const j=n==null?void 0:n.find(g=>g.groupId===f.id),N=m.some(g=>g.id===f.id),C=x.includes(f.id),L=h.find(g=>g.id===f.id),A=!!j&&!C;let D=(j==null?void 0:j.role)||"VIEWER";if(N){const g=m.find(y=>y.id===f.id);D=(g==null?void 0:g.role)||"VIEWER"}else L&&(D=L.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",A&&!C?"border border-green-200 bg-green-50":C?"border border-red-200 bg-red-50":N?"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-${f.id}`,checked:A?!C:N,disabled:!1,onCheckedChange:()=>{A?C?p.removeGroupFromRemove(f.id):i==null||i(f.id):d==null||d(f.id)}}),e.jsxs("label",{htmlFor:`group-${f.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:f.name}),f.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:[f.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",Ua(f.type)),children:za(f.type)}),f.type==="TENANT_GROUP"&&f.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",f.tenantName]})]}),f.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:f.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[A&&!C?e.jsx(Ae,{currentRole:D,onRoleChange:g=>{j&&g!==j.role&&(u==null||u(f.id,j.role,g))},roleOptions:b,disabled:!1,allowDropdown:!0,className:L?"border-orange-300 bg-orange-100":""}):N&&!A&&e.jsx(Ae,{currentRole:D,onRoleChange:g=>o==null?void 0:o(f.id,g),roleOptions:b,disabled:!1}),A&&!C&&!L&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i==null?void 0:i(f.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),C&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p.removeGroupFromRemove(f.id),children:"Undo"}),L&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p.removeGroupFromUpdate(f.id),children:"Cancel"})]})]},f.id)})})]})}function st({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){if(t.length===0)return null;const c=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(d=>{const o=n.find(i=>i.id===d.id);return o?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:[o.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:o.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[o.memberCount," members"]}),o.type==="TENANT_GROUP"&&o.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",o.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ae,{currentRole:d.role,onRoleChange:i=>r(d.id,i),roleOptions:c}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(d.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},d.id):null})})]})}function ws({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:c=!1,isRemoving:d=!1}){var G;const{searchQuery:o,debouncedSearchQuery:i,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),x=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate(),p=s.useShareSelectedGroups(),b=s.useShareGroupsToRemove(),f=s.useShareGroupsToUpdate(),j=s.useShareCurrentMode(),N=s.useShareTenantWideRole(),C=s.useShareAllTenantsRole(),L=s.useShareSelectedTenant(),A=s.useShareManagementActions(),{data:w,isLoading:D}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:g,isLoading:y}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||L),[v,R]=k.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");k.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(A.setCurrentContext("tenant-dialog"),A.setCurrentMode("specificTenantUsers")):(A.setCurrentContext("tenant-tab"),A.setCurrentMode("allTenants"))},[A,a==null?void 0:a.type]);const S=V=>{var le,de,ne,me;R(V);let Z;if(V==="specific_tenant_users"?Z="specific_users":V==="all_tenant_users"||V==="all_tenants"?Z="all_users":V==="groups"?Z="groups":Z="specific_users",r==null||r(Z),V==="groups"?(A.setCurrentContext("group-share"),A.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(A.setCurrentContext("tenant-dialog"),V==="specific_tenant_users"?A.setCurrentMode("specificTenantUsers"):V==="all_tenant_users"&&(A.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&A.setSelectedTenant(a.tenantId))):(A.setCurrentContext("tenant-tab"),V==="specific_tenant_users"?A.setCurrentMode("specificTenantUsers"):V==="all_tenant_users"?A.setCurrentMode("allTenantUsers"):V==="all_tenants"&&A.setCurrentMode("allTenants")),V==="all_tenant_users"){const je=(de=(le=T==null?void 0:T.shares)==null?void 0:le.tenantWide)==null?void 0:de[0];je&&je.role!==void 0&&A.setTenantWideRole(je.role)}else if(V==="all_tenants"){const je=(me=(ne=T==null?void 0:T.shares)==null?void 0:ne.allTenantsOnly)==null?void 0:me[0];je&&je.role!==void 0&&A.setAllTenantsRole(je.role)}},F=V=>{A.setSelectedTenant(V)},{allUsers:I,existingShares:T,isLoadingUsers:M,isErrorLoadingUsers:O,isLoadingShares:E,isErrorLoadingShares:P}=Pe({debouncedSearchQuery:i,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:L}),B=V=>{var ne,me;const Z=m.some(je=>je.id===V),le=x.includes(V),de=(me=(ne=T==null?void 0:T.shares)==null?void 0:ne.specificTenantUsers)==null?void 0:me.some(je=>je.tenantUserId===V);Z?A.removeSelectedUser(V):le?A.removeUserFromRemove(V):de||A.addSelectedUser({id:V,role:"VIEWER"})},Y=(V,Z)=>{A.updateSelectedUserRole(V,Z)},q=V=>{A.addUserToRemove(V),A.removeSelectedUser(V)},z=V=>{A.removeUserFromRemove(V)},J=V=>{A.removeUserFromUpdate(V)},W=(V,Z,le)=>{A.addUserToUpdate({id:V,currentRole:Z,newRole:le})},se=(V,Z)=>{v==="all_tenant_users"?A.setTenantWideRole(Z):v==="all_tenants"&&A.setAllTenantsRole(Z)},te=()=>{v==="all_tenant_users"?A.setTenantWideRole("VIEWER"):v==="all_tenants"&&A.setAllTenantsRole("VIEWER")},Q=(()=>{var V,Z,le,de;return j==="allTenants"?(Z=(V=T==null?void 0:T.shares)==null?void 0:V.allTenantsOnly)==null?void 0:Z[0]:j==="allTenantUsers"?(de=(le=T==null?void 0:T.shares)==null?void 0:le.tenantWide)==null?void 0:de[0]:null})();k.useEffect(()=>{var V,Z,le,de;if(v==="all_tenant_users"){const ne=(Z=(V=T==null?void 0:T.shares)==null?void 0:V.tenantWide)==null?void 0:Z[0];ne&&ne.role!==void 0&&A.setTenantWideRole(ne.role)}else if(v==="all_tenants"){const ne=(de=(le=T==null?void 0:T.shares)==null?void 0:le.allTenantsOnly)==null?void 0:de[0];ne&&ne.role!==void 0&&A.setAllTenantsRole(ne.role)}},[v,T,A]);const _=I.filter(V=>m.some(Z=>Z.id===V.id)),ae=V=>{const Z=p.some(ne=>ne.id===V),le=b.includes(V),de=X==null?void 0:X.some(ne=>ne.groupId===V);Z?A.removeSelectedGroup(V):le?A.removeGroupFromRemove(V):de||A.addSelectedGroup({id:V,role:"VIEWER"})},H=(V,Z)=>{A.updateSelectedGroupRole(V,Z)},re=V=>{A.addGroupToRemove(V),A.removeSelectedGroup(V)},ie=(V,Z,le)=>{A.addGroupToUpdate({id:V,currentRole:Z,newRole:le})},ue=g.filter(V=>p.some(Z=>Z.id===V.id)),U=k.useMemo(()=>v!=="groups"?[]:g.filter(V=>V.type!=="TENANT_GROUP"?!1:V.name.toLowerCase().includes(o.toLowerCase())||V.description&&V.description.toLowerCase().includes(o.toLowerCase())),[g,v,o]),X=k.useMemo(()=>{var Z,le;const V=((Z=T==null?void 0:T.shares)==null?void 0:Z.specificGroups)||((le=T==null?void 0:T.shares)==null?void 0:le.groups)||[];return!V||V.length===0?[]:V.filter(de=>{const ne=g.find(me=>me.id===de.groupId);return(ne==null?void 0:ne.type)==="TENANT_GROUP"})},[T,g]),xe=M||E||v==="groups"&&y,ce=O||P,K=()=>(a==null?void 0:a.type)==="tenant"||v==="all_tenants"||v==="groups"?!0:L&&(v==="specific_tenant_users"||v==="all_tenant_users");return e.jsxs(e.Fragment,{children:[ce&&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"})]})}),!ce&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(ls,{shareType:v,onShareTypeChange:S,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(ys,{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"&&(v==="specific_tenant_users"||v==="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:L||"",onValueChange:F,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:(G=w==null?void 0:w.tenants)==null?void 0:G.map(V=>e.jsx(s.SelectItem,{value:V.id,children:V.name},V.id))})]})]}),K()?e.jsx(e.Fragment,{children:v==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Qe,{value:o,onChange:u}),e.jsx(Ks,{selectedUsers:m,selectedUserObjects:_,onRemove:V=>B(V),onRoleChange:Y,getRoleOptions:ye}),e.jsx(Qs,{usersToRemove:x,allUsers:I,onRemove:z}),e.jsx(Hs,{usersToUpdate:h,allUsers:I,onRemove:J,getRoleOptions:ye}),e.jsx(Xs,{existingShares:T,isInitialLoading:!!xe,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:ye,allUsers:I,currentUser:a,handleUserToggle:B,handleUserRoleChange:Y,handleRemoveAccess:q,handleUpdateAccess:W})]}):v==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Qe,{value:o,onChange:u,placeholder:"Search groups..."}),e.jsx(st,{selectedGroups:p,groupObjects:ue,onRemove:ae,onRoleChange:H,getRoleOptions:ye}),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"})]}),f.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 (",f.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(et,{groups:U,existingGroupShares:X,isLoading:y,resource:t,getRoleOptions:ye,currentUser:a,handleGroupToggle:ae,handleGroupRoleChange:H,handleRemoveAccess:re,handleUpdateAccess:ie})]}):v==="all_tenant_users"||v==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Zs,{currentUser:a,currentShare:Q,isSharing:l,isUpdating:c,isRemoving:d,onUpdateAccess:se,onRemoveAccess:te,allUsersToUpdate:j==="allTenantUsers"&&((Q==null?void 0:Q.role)===void 0||N!==Q.role)||j==="allTenants"&&((Q==null?void 0:Q.role)===void 0||C!==Q.role)?{currentRole:(Q==null?void 0:Q.role)||"VIEWER",newRole:j==="allTenantUsers"?N:C}:null,allUsersToRemove:j==="allTenantUsers"&&(Q==null?void 0:Q.role)===void 0||j==="allTenants"&&(Q==null?void 0:Q.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(v==="specific_tenant_users"||v==="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(ys,{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 _a({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:c=!1,isRemoving:d=!1}){var O,E;const{searchQuery:o,setSearchQuery:i}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),h=s.useShareManagementActions(),[p,b]=k.useState("org_groups"),[f,j]=k.useState(""),{data:N,isLoading:C}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&p==="tenant_groups"}),L=Array.isArray(N)?N:(N==null?void 0:N.tenants)||[],A=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:w,isLoading:D}=s.useShareableGroups(A(),p==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?f:a==null?void 0:a.tenantId),{existingShares:g}=Pe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),y=w.filter(P=>p==="org_groups"&&P.type!=="ORG_GROUP"||p==="tenant_groups"&&P.type!=="TENANT_GROUP"||p==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!f||P.tenantId&&P.tenantId!==f)?!1:P.name.toLowerCase().includes(o.toLowerCase())||P.description&&P.description.toLowerCase().includes(o.toLowerCase())),v=((O=g==null?void 0:g.shares)==null?void 0:O.specificGroups)||((E=g==null?void 0:g.shares)==null?void 0:E.groups)||[];k.useEffect(()=>{h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},[h]);const R=P=>{const B=P;b(B),B==="org_groups"&&j(""),r==null||r(B==="org_groups"?"specific_groups":"all_groups"),h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},S=w.filter(P=>u.some(B=>B.id===P.id)),F=P=>{const B=u.some(z=>z.id===P),Y=m.includes(P),q=v==null?void 0:v.some(z=>z.groupId===P);B?h.removeSelectedGroup(P):Y?h.removeGroupFromRemove(P):q||h.addSelectedGroup({id:P,role:"VIEWER"})},I=(P,B)=>{h.updateSelectedGroupRole(P,B)},T=P=>{h.addGroupToRemove(P),h.removeSelectedGroup(P)},M=(P,B,Y)=>{h.addGroupToUpdate({id:P,currentRole:B,newRole:Y})};return a?e.jsxs(e.Fragment,{children:[e.jsx(ls,{shareType:p,onShareTypeChange:R,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"})}]}),p==="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:f,onValueChange:j,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:L.map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.id,children:P.name},P.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:p==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!f?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(Qe,{value:o,onChange:i,placeholder:"Search groups..."}),e.jsx(st,{selectedGroups:u,groupObjects:S,onRemove:F,onRoleChange:I,getRoleOptions:ye}),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"})]}),x.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 (",x.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(et,{groups:y,existingGroupShares:v,isLoading:D,resource:t,getRoleOptions:ye,currentUser:a,handleGroupToggle:F,handleGroupRoleChange:I,handleRemoveAccess:T,handleUpdateAccess:M})]})})]}):null}const tt=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),c=s.useShareSelectedGroups(),d=s.useShareGroupsToRemove(),o=s.useShareGroupsToUpdate(),i=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),x=s.useShareTenantWideRole(),h=s.useShareGroupWideRole(),p=k.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedGroups:c,groupsToRemove:d,groupsToUpdate:o,selectedTenant:i,orgWideRole:u,allTenantsRole:m,tenantWideRole:x}),[t,n,a,r,l,c,d,o,i,u,m,x,h]),b=k.useMemo(()=>j=>s.validateShareData(j),[]),f=k.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(!i)return!1}else if(n==="specificTenantUsers")return i?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"?c.length>0||d.length>0||o.length>0:!0}return!1},[t,n,a,r,l,c,d,o,i]);return{buildShareData:p,validateShareData:b,isCurrentStateValid:f,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:i,orgWideRole:u,allTenantsRole:m,tenantWideRole:x}};function Ds({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:d,shareTabType:o,currentAllUsersShare:i,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),x=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate(),p=s.useShareSelectedTenant(),b=s.useShareOrgWideRole(),f=s.useShareAllTenantsRole(),j=s.useShareTenantWideRole(),{buildShareData:N,validateShareData:C,isCurrentStateValid:L}=tt(),A=a||r||l,w=()=>{var R,S,F,I;if(A)return"Updating...";if(o==="specific_users"){if(m.length===0&&x.length===0&&h.length===0)return"Select users to share with";const T=m.length+x.length+h.length;return T===0?"Select users to share with":m.length>0&&x.length>0?`Update access for ${T} user${T!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Remove access for ${x.length} user${x.length!==1?"s":""}`:m.length>0&&x.length===0&&h.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${T} user${T!==1?"s":""}`}else if(o==="all_users"){if(!i||i.role===void 0)return"Share with All Users";const T=i.role;return b===T?"Remove Access":"Update Access"}else if(o==="all_tenants"){const T=(S=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0)return"Share with All Tenants";const M=T.role;return f===M?"Remove Access":"Update Access"}else if(o==="all_tenant_users"){const T=(I=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:I[0];if(!T||T.role===void 0)return"Share with All Tenant Users";const M=T.role;return j===M?"Remove Access":"Update Access"}else if(o==="specific_tenant_users"){if(m.length===0&&x.length===0&&h.length===0)return"Select users to share with";const T=m.length+x.length+h.length;return T===0?"Select users to share with":m.length>0&&x.length>0?`Update access for ${T} user${T!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Remove access for ${x.length} user${x.length!==1?"s":""}`:m.length>0&&x.length===0&&h.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${T} user${T!==1?"s":""}`}return"Share"},D=()=>A||!t||o==="all_tenant_users"&&!p||o==="specific_tenant_users"&&!p?!0:!L,g=()=>{const R=N();R&&C(R)&&c(R)},y=()=>{var R,S,F,I;if(o==="all_users")if(!i||i.role===void 0){const T=N();T&&C(T)&&c(T)}else{const T=i.role;if(b===T)u==null||u();else{const O=N();if(O&&C(O)){const E={...O,updateAccess:!0};c(E)}}}else if(o==="all_tenants"){const T=(S=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0){const M=N();M&&C(M)&&c(M)}else{const M=T.role;if(f===M)u==null||u();else{const E=N();if(E&&C(E)){const P={...E,updateAccess:!0};c(P)}}}}else if(o==="all_tenant_users"){const T=(I=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:I[0];if(!T||T.role===void 0){const M=N();M&&C(M)&&c(M)}else{const M=T.role;if(j===M)u==null||u();else{const E=N();if(E&&C(E)){const P={...E,updateAccess:!0};c(P)}}}}},v=()=>{var R,S,F,I;if(o==="all_users"){if(!i||i.role===void 0)return"default";const T=i.role;return b===T?"destructive":"default"}else if(o==="all_tenants"){const T=(S=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0)return"default";const M=T.role;return f===M?"destructive":"default"}else if(o==="all_tenant_users"){const T=(I=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:I[0];if(!T||T.role===void 0)return"default";const M=T.role;return j===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsxs(s.Button,{variant:"outline",onClick:d,disabled:A,children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),(o==="specific_users"||o==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||x.length>0||h.length>0)&&e.jsxs(s.Button,{onClick:g,disabled:!t||A,variant:"default",children:[A?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),!A&&w()]})}),(o==="all_users"||o==="all_tenants"||o==="all_tenant_users")&&e.jsxs(s.Button,{onClick:y,disabled:D(),variant:v(),children:[A?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"}),!A&&w()]})]})}function Ga({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:c,shareTabType:d,currentAllUsersShare:o}){const i=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),x=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const b=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:j,isCurrentStateValid:N}=tt(),C=n||a||r,L=()=>{if(C)return"Updating...";if(d==="specific_users"){if(i.length===0&&u.length===0&&m.length===0)return"Select users to share with";const v=i.length+u.length+m.length;return v===0?"Select users to share with":i.length>0&&u.length>0?`Update access for ${v} user${v!==1?"s":""}`:u.length>0&&i.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:i.length>0&&u.length===0&&m.length===0?`Share with ${i.length} user${i.length!==1?"s":""}`:m.length>0&&i.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${v} user${v!==1?"s":""}`}else if(d==="groups"){if(x.length===0&&h.length===0&&p.length===0)return"Select groups to share with";const v=x.length+h.length+p.length;return v===0?"Select groups to share with":x.length>0&&h.length>0?`Update access for ${v} group${v!==1?"s":""}`:h.length>0&&x.length===0&&p.length===0?`Remove access for ${h.length} group${h.length!==1?"s":""}`:x.length>0&&h.length===0&&p.length===0?`Share with ${x.length} group${x.length!==1?"s":""}`:p.length>0&&x.length===0&&h.length===0?`Update access for ${p.length} group${p.length!==1?"s":""}`:`Update access for ${v} group${v!==1?"s":""}`}else if(d==="all_users"){if(!o||o.role==="NONE")return"Share with All Users";const v=o.role;return b===v?"Remove Access":"Update Access"}return"Share"},A=()=>C||!t?!0:!N,w=()=>{const v=f();v&&j(v)&&l(v)},D=()=>{const v=f();v&&j(v)&&l(v)},g=()=>{if(!o||o.role==="NONE"){const v=f();v&&j(v)&&l(v)}else{const v=o.role;if(b===v){const S=f();if(S&&j(S)){const F={...S,removeAccess:!0};l(F)}}else{const S=f();if(S&&j(S)){const F={...S,updateAccess:!0};l(F)}}}},y=()=>!o||o.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsxs(s.Button,{variant:"outline",onClick:c,disabled:C,children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),d==="specific_users"&&e.jsx(e.Fragment,{children:(i.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:w,disabled:!t||C,variant:"default",children:[C?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),!C&&L()]})}),d==="groups"&&e.jsx(e.Fragment,{children:(x.length>0||h.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:D,disabled:!t||C,variant:"default",children:[C?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),!C&&L()]})}),d==="all_users"&&e.jsxs(s.Button,{onClick:g,disabled:A(),variant:y(),children:[C?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),!C&&L()]})]})}function $a({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:d,shareTabType:o,currentAllGroupsShare:i,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const p=()=>{c({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:x,groupsToUpdate:h})},b=()=>m.length>0||x.length>0||h.length>0,f=()=>x.length>0&&m.length===0&&h.length===0?"Remove Access":h.length>0&&m.length===0&&x.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"]}),x.length>0&&e.jsxs("span",{className:"ml-2 text-destructive",children:["• ",x.length," to remove"]}),h.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",h.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:d,disabled:j,children:"Cancel"}),e.jsxs(s.Button,{onClick:p,disabled:!b()||j,children:[j&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),f()]})]})]})}function ve(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Ce(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Ya(t,n,a){const{resourceType:r,resourceId:l,shareMutation:c,removeMutation:d,existingShares:o,resetUserSelections:i}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=ve(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:x}=t;if(u&&u.length>0){const h=ve(r,l,u.map(p=>({scope:"specific_org_user",orgUserId:p.id,role:p.role})));c(h,{onSuccess:()=>{i()}})}if(m&&m.length>0){const h=Ce(r,l,m.map(p=>{var f,j;const b=(j=(f=o==null?void 0:o.shares)==null?void 0:f.specificOrgUsers)==null?void 0:j.find(N=>N.orgUserId===p);return{scope:"specific_org_user",orgUserId:p,role:(b==null?void 0:b.role)||"VIEWER"}}));d(h,{onSuccess:()=>{i()}})}x&&x.length>0&&x.forEach(h=>{const p=ve(r,l,[{scope:"specific_org_user",orgUserId:h.id,role:h.newRole}]);c(p,{onSuccess:()=>{i()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=ve(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="allTenantUsers"){const u=ve(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:x,tenantId:h}=t;if(m&&m.length>0){const p=Ce(r,l,m.map(b=>{var j,N;const f=(N=(j=o==null?void 0:o.shares)==null?void 0:j.specificTenantUsers)==null?void 0:N.find(C=>C.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,tenantId:h,role:(f==null?void 0:f.role)||"VIEWER"}}));d(p,{onSuccess:()=>{i()}})}if(x&&x.length>0&&x.forEach(p=>{const b=ve(r,l,[{scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.newRole}]);c(b,{onSuccess:()=>{i()}})}),u&&u.length>0){const p=ve(r,l,u.map(b=>({scope:"specific_tenant_user",tenantUserId:b.id,tenantId:h,role:b.role})));c(p,{onSuccess:()=>{i()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=Ce(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);d(u,{onSuccess:()=>{i()}})}else if(t.updateAccess){const u=ve(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);c(u,{onSuccess:()=>{i()}})}else{const u=ve(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:x}=t;if(u&&u.length>0){const h=ve(r,l,u.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,role:p.role})));c(h,{onSuccess:()=>{i()}})}if(m&&m.length>0){const h=Ce(r,l,m.map(p=>{var f,j;const b=(j=(f=o==null?void 0:o.shares)==null?void 0:f.specificTenantUsers)==null?void 0:j.find(N=>N.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,role:(b==null?void 0:b.role)||"VIEWER"}}));d(h,{onSuccess:()=>{i()}})}x&&x.length>0&&x.forEach(h=>{const p=ve(r,l,[{scope:"specific_tenant_user",tenantUserId:h.id,role:h.newRole}]);c(p,{onSuccess:()=>{i()}})})}break;case"group-share":if(t.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:m,groupsToUpdate:x}=t;if(u&&u.length>0){const h=ve(r,l,u.map(p=>({scope:"group",groupId:p.id,role:p.role})));c(h,{onSuccess:()=>{var p;i(),(p=n.resetGroupSelections)==null||p.call(n),s.ue.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(m&&m.length>0){const h=Ce(r,l,m.map(p=>({scope:"group",groupId:p,role:"VIEWER"})));d(h,{onSuccess:()=>{var p;i(),(p=n.resetGroupSelections)==null||p.call(n),s.ue.success(`Removed access from ${m.length} group${m.length!==1?"s":""}`)}})}x&&x.length>0&&x.forEach(h=>{const p=ve(r,l,[{scope:"group",groupId:h.id,role:h.newRole}]);c(p,{onSuccess:()=>{var b;i(),(b=n.resetGroupSelections)==null||b.call(n),s.ue.success("Updated access for group")}})})}break}}function qa(t,n,a,r){var u,m,x,h,p,b;const{resourceType:l,resourceId:c,removeMutation:d,existingShares:o,resetUserSelections:i}=r;if(c)if(t.length>0){const f=Ce(l,c,t.map(j=>{var C,L;const N=(L=(C=o==null?void 0:o.shares)==null?void 0:C.specificTenantUsers)==null?void 0:L.find(A=>A.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,role:(N==null?void 0:N.role)||"VIEWER"}}));d(f,{onSuccess:()=>{i()},onError:j=>{console.error("Remove access failed:",j)}})}else{const f=n==="tenant"&&a==="allTenants",j=n==="tenant"&&a==="allTenantUsers";if(f){const N=(m=(u=o==null?void 0:o.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(N){const C=Ce(l,c,[{scope:"all_tenants_only",role:N.role}]);d(C,{onSuccess:()=>{i()},onError:L=>{console.error("Remove all-tenants access failed:",L)}})}}else if(j){const N=(h=(x=o==null?void 0:o.shares)==null?void 0:x.tenantWide)==null?void 0:h[0];if(N){const C=Ce(l,c,[{scope:"all_tenant_users",role:N.role}]);d(C,{onSuccess:()=>{i()},onError:L=>{console.error("Remove all-tenant-users access failed:",L)}})}}else{const N=(b=(p=o==null?void 0:o.shares)==null?void 0:p.orgUsersOnly)==null?void 0:b[0];if(N){const C=Ce(l,c,[{scope:"org_users_only",role:N.role}]);d(C,{onSuccess:()=>{i()},onError:L=>{console.error("Remove org-wide access failed:",L)}})}}}}function Ka(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),d=s.useShareCurrentMode(),{currentUser:o}=s.useCurrentUserInfo(),{existingShares:i}=Pe({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=k.useCallback(()=>{r.resetUserSelections()},[r]),m=k.useCallback(()=>{r.resetGroupSelections()},[r]),x=k.useCallback(p=>{if(!t)return;const b={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:i,resetUserSelections:u,resetGroupSelections:m};Ya(p,b,o)},[t,n,a,i,u,m,o]),h=k.useCallback(()=>{if(!t)return;const p={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:i,resetUserSelections:u};qa(l,c||"",d||"",p)},[t,n,a,i,u,m,l,c,d]);return{handleShareSubmit:x,handleRemoveAccess:h}}function We({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var I,T,M,O,E,P,B,Y;const{currentUser:c}=s.useCurrentUserInfo(),[d,o]=k.useState("specific_users"),[i,u]=k.useState("specific_users"),[m,x]=k.useState("specific_groups"),h=s.useShareManagementActions(),p=s.useShareSelectedTab(),b=s.useShareCurrentMode(),f=s.useShareResource(),j=s.useRemoveResourceShares(),{handleShareSubmit:N,handleRemoveAccess:C}=Ka(t.id,(q,z)=>{f.mutate(q,{...z,onSuccess:()=>{var J;(J=z==null?void 0:z.onSuccess)==null||J.call(z),r==null||r()}})},(q,z)=>{j.mutate(q,{...z,onSuccess:()=>{var J;(J=z==null?void 0:z.onSuccess)==null||J.call(z),l==null||l()}})}),L=f.isPending,A=j.isPending,w=f.isPending,{existingShares:D}=Pe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:g}=Pe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),y=(T=(I=D==null?void 0:D.shares)==null?void 0:I.tenantWide)==null?void 0:T[0],v=(O=(M=g==null?void 0:g.shares)==null?void 0:M.orgUsersOnly)==null?void 0:O[0],R=()=>{if(p==="org")return i;switch(b){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},S=k.useCallback(()=>{h.resetShareState(),a()},[h,a]),F=(c==null?void 0:c.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:S,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(Ie,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:F?"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."})]}),F?e.jsxs(s.Tabs,{value:p,onValueChange:q=>{const z=q;h.setSelectedTab(z),h.resetUserSelections(),h.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(Va,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:u,isSharing:L,isUpdating:w,isRemoving:A})})}),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(ws,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:q=>o(q),isSharing:L,isUpdating:w,isRemoving:A})})}),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(_a,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:x,isSharing:L,isUpdating:w,isRemoving:A})})})]}):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(ws,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:q=>o(q),isSharing:L,isUpdating:w,isRemoving:A})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:F?p==="org"?e.jsx(Ds,{resource:t,existingShares:g,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:i,currentAllUsersShare:v,onRemoveAccess:C}):p==="tenant"?e.jsx(Ds,{resource:t,existingShares:D,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:R(),currentAllUsersShare:y,onRemoveAccess:C}):e.jsx($a,{resource:t,existingShares:g,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:m,currentAllGroupsShare:(c==null?void 0:c.type)==="organization"?(P=(E=g==null?void 0:g.shares)==null?void 0:E.allOrgGroups)==null?void 0:P[0]:(Y=(B=D==null?void 0:D.shares)==null?void 0:B.allTenantGroups)==null?void 0:Y[0],onRemoveAccess:C}):e.jsx(Ga,{resource:t,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:d,currentAllUsersShare:y,onRemoveAccess:C})})]})})}function at({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(u=>u.selectedFrameId),l=s.useManagementStore(u=>u.selectedVisual),c=s.useEditorStore(u=>u.frame);let d;if(t)d=t;else if(n!==void 0)d=n?"linked":"library";else if(!!!(c!=null&&c.visualId||l!=null&&l.id)&&r)d="local";else if(l&&!r)d="library";else if(c!=null&&c.visualId&&r)d="linked";else if(l!=null&&l.id&&r)d="library";else return null;const o={local:"bg-gray-100 text-gray-700",linked:"bg-purple-100 text-purple-700",library:"bg-blue-100 text-blue-700"},i={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",o[d],a),children:i[d]})}const Qa=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},Ha=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 c=await l.text();throw new Error(c||"Failed to delete group")}},Wa=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},Ja=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,c=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!c.ok){const d=await c.text();throw new Error(d||"Failed to remove group members")}};function Xa(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Qa(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 Za(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Ha(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 en(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Wa(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 sn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Ja(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 tn({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=k.useState(""),[c,d]=k.useState(""),[o,i]=k.useState({}),u=Xa(),m=()=>{const h={};return r.trim()?r.length<3?h.name="Group name must be at least 3 characters":r.length>50&&(h.name="Group name must be less than 50 characters"):h.name="Group name is required",c&&c.length>200&&(h.description="Description must be less than 200 characters"),i(h),Object.keys(h).length===0},x=async h=>{if(h.preventDefault(),!m())return;const p={name:r.trim(),description:c.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(p),l(""),d(""),i({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:x,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:h=>{l(h.target.value),o.name&&i(p=>({...p,name:""}))},className:o.name?"border-destructive":"",disabled:u.isPending}),o.name&&e.jsx("p",{className:"text-sm text-destructive",children:o.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:c,onChange:h=>{d(h.target.value),o.description&&i(p=>({...p,description:""}))},className:o.description?"border-destructive":"",disabled:u.isPending,rows:3}),o.description&&e.jsx("p",{className:"text-sm text-destructive",children:o.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.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(""),d(""),i({})},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,c]=k.useState("members"),[d,o]=k.useState(""),[i,u]=k.useState([]),[m,x]=k.useState([]),{data:h,isLoading:p,refetch:b}=s.useGroupMembers(a.id),f=a.type==="TENANT_GROUP"?"tenant":"organization",{users:j,isLoading:N}=s.useUnifiedUsers({type:f,tenantId:a.tenantId||void 0,active:!0,limit:100}),C=en(),L=sn(),A=(h==null?void 0:h.members)||[],w=k.useMemo(()=>new Set(A.map(I=>I.userId)),[A]),D=k.useMemo(()=>j.filter(I=>!w.has(I.id)),[j,w]),g=k.useMemo(()=>{if(!d)return D;const I=d.toLowerCase();return D.filter(T=>{var M,O;return((M=T.name)==null?void 0:M.toLowerCase().includes(I))||((O=T.email)==null?void 0:O.toLowerCase().includes(I))})},[D,d]),y=k.useMemo(()=>{if(!d)return A;const I=d.toLowerCase();return A.filter(T=>{var M,O,E,P;return((O=(M=T.user)==null?void 0:M.name)==null?void 0:O.toLowerCase().includes(I))||((P=(E=T.user)==null?void 0:E.email)==null?void 0:P.toLowerCase().includes(I))})},[A,d]),v=async()=>{if(i.length!==0)try{await C.mutateAsync({groupId:a.id,data:{userIds:i,userType:f==="tenant"?"tenant":"org"}}),u([]),c("members"),b(),r==null||r()}catch(I){console.error("Failed to add members:",I)}},R=async()=>{if(m.length!==0)try{await L.mutateAsync({groupId:a.id,data:{userIds:m}}),x([]),b(),r==null||r()}catch(I){console.error("Failed to remove members:",I)}},S=I=>{u(T=>T.includes(I)?T.filter(M=>M!==I):[...T,I])},F=I=>{x(T=>T.includes(I)?T.filter(M=>M!==I):[...T,I])};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:[A.length," ",A.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:I=>{c(I),o(""),x([])},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:d,onChange:I=>o(I.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:p?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):y.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:d?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:d?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:y.map(I=>e.jsx(nn,{member:I,selected:m.includes(I.userId),onToggle:()=>F(I.userId)},I.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:R,disabled:L.isPending,children:L.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:d,onChange:I=>o(I.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:N?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):g.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:d?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:g.map(I=>e.jsx(rn,{user:I,selected:i.includes(I.id),onToggle:()=>S(I.id)},I.id))})}),i.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:[i.length," user",i.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:v,disabled:C.isPending,children:C.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 nn({member:t,selected:n,onToggle:a}){var l,c,d,o;const r=((c=(l=t.user)==null?void 0:l.name)==null?void 0:c.split(" ").map(i=>i[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:((d=t.user)==null?void 0:d.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(o=t.user)==null?void 0:o.email})]})]})}function rn({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(c=>c[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 ln({open:t,onOpenChange:n}){const[a,r]=k.useState("groups"),[l,c]=k.useState(""),[d,o]=k.useState(null),[i,u]=k.useState(!1),[m,x]=k.useState(null),{tokenProps:h}=s.useSemaphorContext(),{currentUser:p}=s.useCurrentUserInfo(),b=Za(),f=(p==null?void 0:p.type)==="tenant",j=h==null?void 0:h.tenantId,{groups:N,isLoading:C,refetch:L}=s.useGroups({type:f?"TENANT_GROUP":"all",tenantId:f?j:void 0,includeMembers:!1}),A=N.filter(y=>{var v;return y.name.toLowerCase().includes(l.toLowerCase())||((v=y.description)==null?void 0:v.toLowerCase().includes(l.toLowerCase()))}),w=async()=>{if(m)try{await b.mutateAsync(m.id),x(null),L()}catch(y){console.error("Failed to delete group:",y)}},D=y=>{o(y),u(!0)},g=()=>{r("groups"),L()};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:y=>c(y.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:C?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(y=>e.jsx(s.Skeleton,{className:"h-24 w-full"},y))}):A.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:A.map(y=>e.jsx(on,{group:y,onManageMembers:()=>D(y),onDelete:()=>x(y),currentUserId:p==null?void 0:p.id},y.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(tn,{onSuccess:g,tenantId:j,isTenantUser:f})})]})]})}),d&&e.jsx(an,{open:i,onOpenChange:u,group:d,onUpdate:()=>L()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>x(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:w,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 os(t){const[n,a]=k.useState(null),[r,l]=k.useState(null);return k.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 o=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(o,{method:"HEAD"})).ok)throw new Error(`Module not found at ${o}`)}catch{}const i=await import(o);if(typeof i.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>i.useChartStore),l(null)}catch(d){const o=d instanceof Error?d.message:"Unknown error";console.error("Failed to load remote chart store:",o),l(o),a(null)}})()},[t]),n}function cn(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 c=t.length;if(l!==-1&&(c=l),r!==-1&&r<c&&(c=r),n!==-1){const d=t.substring(0,n),o=t.substring(n);return`${d} {{ filters | where }} AND ${o.substring(6)}`}else if(a!==-1){const d=t.substring(0,a),o=t.substring(a);return`${d} {{ filters | where }} ${o}`}else{const d=t.substring(0,c),o=t.substring(c);return console.log("beforeClause",d),console.log("afterClause",o),o?`${d} {{ filters | where }} ${o}`:`${d.replace(/;$/,"")} {{ filters | where }}`}}function dn(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 c=r.split("__")[0],d=t.find(o=>o.tabTitle===c);return d?d.id:t[0].id}return n}}return t[0].id}async function Ts(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],c=r.getQueryData(l);if(c)return console.log("Using cached visual data for:",a),{data:c,fromCache:!0};console.log("Fetching visual data from network for:",a);const d=s.ue.loading("Loading visual...",{position:"top-center"});try{const o=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!o.ok)throw new Error("Failed to load visual");const i=await o.json();return r.setQueryData(l,i),s.ue.dismiss(d),{data:i,fromCache:!1}}catch(o){throw s.ue.dismiss(d),o}}function nt(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function un(t,n){var c,d;const a=(t==null?void 0:t.frameObject)??((c=t==null?void 0:t.visual)==null?void 0:c.frameObject);if(!a)return!1;const r=nt(a);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(d=r.cards)==null?void 0:d.find(o=>o.id===r.activeCardId);return l?(s.setupEditorWithCard({...n,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function mn(){var h;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(p=>p.frame),a=s.useEditorStore(p=>p.card),r=os(((h=a.customCardPreferences)==null?void 0:h.url)||""),l=s.useEditorStore(p=>p.selectedSchemaName),c=s.useEditorStore(p=>p.selectedDatamodelId),d=s.useEditorStore(p=>p.selectedDatabaseName),o=s.useEditorStore(p=>p.selectedTableName),i=s.useEditorStore(p=>p.selectedConnectionId),u=s.useEditorStore(p=>p.isShowingVisual),m=a.sql;return{getUpdatedFrame:k.useCallback(()=>{var N;let p=m;m&&!m.includes("{{")&&(p=cn(m),t(p));const b=(N=r==null?void 0:r.getState())==null?void 0:N.settings,f={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:c,lastSelectedDatabase:d,lastSelectedTable:o,connectionId:i,sql:p,customCfg:u?a.customCfg:null,preferences:a.preferences,...b&&{customCardPreferences:{...a.customCardPreferences,settings:b}}},j=n.cards.map(C=>C.id===a.id?f:C);return{...n,cards:j,activeCardId:dn(j,n.activeCardId)}},[a,n,u,l,c,d,o,i,t,r,m])}}function Me(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:c,setCard:d,setIsDevMode:o,setActiveTabCardId:i,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:x,setSelectedDatabaseName:h,setSelectedSchemaName:p,setSelectedTableName:b,setSelectedDatamodelId:f,setFilterValues:j,setApplyFilters:N}=s.useEditorActions(),{setIsDashboardEditing:C,setIsVisualEditing:L,setSelectedFrameId:A,clearSelectedFrameId:w,addFrame:D,setIsDashboardPanelOpen:g}=s.useDashboardActions(),y=s.useDashboardStore(M=>M.selectedSheetId),v=s.useDashboardStore(M=>M.selectedFrameId),R=s.useDashboardStore(M=>M.dashboard),S=s.useDashboardStore(M=>M.filterValues),F=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),I=k.useCallback(async M=>{try{l(M),w();const{data:O,fromCache:E}=await Ts(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a);if(!un(O,{setFrame:c,setCard:d,setIsDevMode:o,setActiveTabCardId:i,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:x,setSelectedDatabaseName:h,setSelectedSchemaName:p,setSelectedTableName:b,setSelectedDatamodelId:f,setFilterValues:j,setApplyFilters:N,setIsDashboardEditing:C,setIsVisualEditing:L,dashboard:R,selectedSheetId:y,selectedFrameId:v,filterValues:S}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:E}}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,c,d,C,L,o,i,u,m,x,h,p,b,f,j,N,w,R,y,v,S]),T=k.useCallback(async M=>{var O;try{if(l(M),!y)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:E,fromCache:P}=await Ts(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a),B=(E==null?void 0:E.frameObject)??((O=E==null?void 0:E.visual)==null?void 0:O.frameObject);if(!B)return{success:!1,error:"Visual has no frame data"};const Y=nt(B);if(!(Y!=null&&Y.cards)||Y.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const q={...Y,id:s.v4(),visualId:M.id};return D(y,q,"end"),C(!0),A(q.id),g(!1),{success:!0,fromCache:P}}catch(E){return console.error("Error adding visual:",E),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,y,D,C,A,g]);return{visual:F.data,isLoading:F.isLoading,isError:F.isError,error:F.error,handleEditLibraryVisual:I,handleAddLibraryVisual:T,getUpdatedFrame:mn().getUpdatedFrame,refetch:F.refetch}}function hn({open:t,onOpenChange:n,isLibraryVisual:a,currentVisualName:r,isSaving:l=!1,onConfirm:c}){const[d,o]=k.useState(a&&r?`Copy of ${r}`:r||""),[i,u]=k.useState(""),[m,x]=k.useState(!a),[h,p]=k.useState(!0);k.useEffect(()=>{t&&(o(a&&r?`Copy of ${r}`:r||""),u(""),x(!a),p(!0))},[t,a,r]);const b=()=>{d.trim()&&(!m&&!h||c({name:d.trim(),description:i.trim()||void 0,saveToLibrary:m,saveToCurrentDashboard:h}))},f=d.trim()&&(m||h);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:d,onChange:j=>o(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:i,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:h,onCheckedChange:j=>p(!!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=>x(!!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&&!h&&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:!f||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function xn({className:t,variant:n="outline"}){var o;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const r=s.useEditorStore(i=>i.card);os(((o=r.customCardPreferences)==null?void 0:o.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),r.sql;const l=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:c}=Me();function d(){const i=c();l==null||l(i)}return e.jsxs(s.Button,{onClick:d,className:s.cn("h-8",t),size:"sm",variant:n,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function pn({className:t,variant:n="default"}){const a=s.useQueryClient(),[r,l]=k.useState(!1),c=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),{setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:o}=Me(),i=s.useSelectedVisual(),u=s.useEditorStore(h=>h.frame),m=s.useUpdateVisualMutation(),x=()=>{const h=o(),p=(u==null?void 0:u.visualId)||(i==null?void 0:i.id);if(!p){s.ue.error("No visual to save");return}l(!0),m.mutate({visualId:p,data:{frameObject:h}},{onSuccess:()=>{l(!1),c(!0),s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["resource-by-id","visual",p],exact:!0})},onError:()=>{l(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:x,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(Oe,{className:"mr-2 size-4 font-bold"}),"Save to Library"]})]})}function fn({className:t}){const n=s.useQueryClient(),[a,r]=k.useState(!1),l=s.useSelectedVisual(),c=s.useEditorStore(h=>h.frame),d=s.useDashboardStore(h=>h.selectedSheetId),{updateFrame:o,setIsVisualEditing:i}=s.useDashboardActions(),{getUpdatedFrame:u}=Me(),m=s.useUpdateVisualMutation(),x=async()=>{if(!d){s.ue.error("No sheet selected");return}const h=(c==null?void 0:c.visualId)||(l==null?void 0:l.id);if(!h){s.ue.error("No visual to update");return}r(!0);try{const p=u();await m.mutateAsync({visualId:h,data:{frameObject:p}});const b={...p,visualId:h};o(d,b),n.invalidateQueries({queryKey:["visuals"]}),n.invalidateQueries({queryKey:["visual",h]}),s.ue.success("Saved to library and applied locally"),setTimeout(()=>{i(!1)},300)}catch(p){console.error("Failed to save and apply:",p),s.ue.error("Failed to save and apply changes")}finally{r(!1)}};return e.jsx(s.Button,{onClick:x,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(Oe,{className:"mr-2 size-4 font-bold"}),"Save & Apply"]})})}function gn({className:t}){const{getUpdatedFrame:n}=Me();s.useEditorStore(i=>i.frame);const a=s.useDashboardStore(i=>i.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[c,d]=k.useState(!1),o=()=>{if(!a){s.ue.error("No sheet selected");return}d(!0);const u={...n(),visualId:void 0};r(a,u),setTimeout(()=>{d(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:o,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[c&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!c&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function jn({className:t}){const{setTempQueryData:n,setSqlGen:a}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),c=s.useEditorStore(u=>u.onClose),d=s.useEditorStore(u=>u.card),{queryKey:o}=s.useDashboardCardQuery(d);function i(){if(l){const{queryKey:u,queryData:m}=l;u&&m&&r.setQueryData(u,m)}a({}),c==null||c()}return e.jsxs(s.Button,{onClick:i,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function is(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient();s.useEditorStore(f=>f.isDevMode);const a=s.useEditorStore(f=>f.tempQueryData),r=s.useEditorStore(f=>f.card),{queryKey:l}=s.useDashboardCardQuery(r),{setCardSql:c,setSqlGen:d,setCardPython:o,setCardCustomCfg:i,setCardPreferences:u,updateDataSource:m,clearQueryConfig:x,setCardConfig:h,setCardType:p}=s.useEditorActions();function b(){const f=n.getQueryData(l);a!=null&&a.queryData||t({queryKey:l,queryData:f}),n.setQueryData(l,null),n.removeQueries({queryKey:l,exact:!0}),c(""),d({}),x(),h(void 0),o(""),i(""),u({}),p("bar")}return e.jsxs(s.Button,{onClick:b,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(Qt,{className:"mr-2 size-4"}),"Clear"]})}function bn(){const[t,n]=k.useState(!1),[a,r]=k.useState(!1),[l,c]=k.useState(null),d=s.useEditorStore(A=>A.frame),o=s.useEditorStore(A=>A.card),i=s.useSelectedVisual(),u=s.useDashboardStore(A=>A.selectedSheetId),m=s.useDashboardStore(A=>A.actions.setIsDashboardPanelOpen),{getUpdatedFrame:x}=Me(),{selectVisual:h}=s.useManagementActions(),{addFrame:p,setSelectedFrameId:b,setIsVisualEditing:f}=s.useDashboardActions(),j=!!(d!=null&&d.visualId),N=(i==null?void 0:i.title)||(o==null?void 0:o.title)||"Untitled Visual",C=s.useCreateVisualWithFrame(A=>{if(A!=null&&A.id){if(h(A),a&&l&&u){const w={...l,id:s.v4(),visualId:A.id};p(u,w,"end"),b(w.id),r(!1),c(null),f(!1)}m(!0),n(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:n,handleSaveAs:async A=>{if(!u){s.ue.error("No sheet selected");return}const w=x();if(A.saveToLibrary){r(A.saveToCurrentDashboard),c(w);const D={title:A.name,description:A.description,frameObject:w,isPrivate:!1};C.mutate(D)}else if(A.saveToCurrentDashboard){const D={...w,id:s.v4(),visualId:void 0,cards:w.cards.map(g=>({...g,title:g.id===o.id?A.name:g.title}))};p(u,D,"end"),b(D.id),s.ue.success("Visual saved to dashboard"),n(!1),f(!1)}},isLibraryVisual:j,currentVisualName:N,isSaving:C.isPending}}function rt({className:t}){const n=s.useEditorStore(C=>C.frame),a=s.useEditorStore(C=>C.card),r=s.useManagementStore(C=>C.selectedVisual),l=s.useDashboardStore(C=>C.selectedFrameId),c=s.useDashboardStore(C=>C.selectedSheetId),{setIsVisualEditing:d}=s.useDashboardActions(),o=!!(n!=null&&n.visualId||r!=null&&r.id),i=!!(n!=null&&n.visualId&&l),u=o&&!i,{saveAsDialogOpen:m,setSaveAsDialogOpen:x,handleSaveAs:h,isLibraryVisual:p,currentVisualName:b,isSaving:f}=bn(),{handleAddLibraryVisual:j}=Me(),N=async()=>{if(!c){s.ue.error("No dashboard sheet selected");return}if(!r){s.ue.error("No visual selected");return}const C=await j(r);C.success?(s.ue.success("Visual added to dashboard"),d(!1)):s.ue.error(C.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[!o&&e.jsx(xn,{className:t,variant:"default"}),o&&e.jsxs(e.Fragment,{children:[i&&e.jsx(gn,{className:t}),u&&c&&a&&(a.sql||s.hasValidCardConfig(a.config))&&e.jsxs(s.Button,{onClick:N,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(Gt,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),u&&e.jsx(pn,{className:t,variant:"default"}),i&&e.jsx(fn,{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:C=>{C.stopPropagation(),x(!0)},children:[e.jsx(Oe,{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:()=>x(!0),children:[e.jsx(Oe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(jn,{className:t}),e.jsx(hn,{open:m,onOpenChange:C=>{f||x(C)},isLibraryVisual:p,currentVisualName:b,isSaving:f,onConfirm:h})]})}function lt({className:t,labelClassName:n,switchClassName:a}){const r=s.useEditorStore(i=>i.isDevMode),l=s.useDashboardStore(i=>i.isVisualEditing),{setIsDevMode:c}=s.useEditorActions(),{config:d}=k.useContext(s.SemaphorContext).tokenProps,o=(d==null?void 0:d.showAdvancedMode)!==!1;return!l||!o?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:()=>c(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:s.cn("text-sm font-medium",n),children:"Advanced Mode"})]})}function vn(){var xe,ce,K;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:c}=s.useRoleAwareDisplayPreferences(),d=s.useHasDashboardId();s.useDashboardStore(G=>G.theme);const o=s.useDashboardStore(G=>G.lenses),i=s.useDashboardStore(G=>G.selectedLensId),u=o==null?void 0:o.find(G=>G.id===i),m=s.useDashboardStore(G=>G.dashboard);s.useDashboardStore(G=>G.selectedSheetId);const x=s.useDashboardStore(G=>G.isDashboardEditing),[h,p]=k.useState(!1),[b,f]=k.useState(!1),[j,N]=k.useState(!1),C=s.useDashboardStore(G=>G.isDashboardPanelOpen),L=s.useDashboardStore(G=>G.actions.setIsDashboardPanelOpen),A=s.useDashboardStore(G=>G.filterValues),w=s.useDashboardStore(G=>G.isVisualEditing),D=s.useEditorStore(G=>G.card),g=s.useManagementStore(G=>G.selectedDashboard),y=s.useManagementStore(G=>G.initialDashboard),v=s.useManagementStore(G=>G.selectedVisual);s.useDashboardStore(G=>G.selectedFrameId),s.useEditorStore(G=>G.frame);const R=g?(ce=g==null?void 0:g.permissions)==null?void 0:ce.canEdit:(xe=y==null?void 0:y.permissions)==null?void 0:xe.canEdit,S=s.useDashboardStore(G=>G.showFilters),F=s.useDashboardStore(G=>G.showDashboardJSON),I=s.useDashboardStore(G=>G.onSaveFunction),T=s.useDashboardStore(G=>G.actions.setShowFilters),{setIsDashboardEditing:M,setShowDashboardJSON:O}=s.useDashboardStore(G=>G.actions),{setInitialDashboard:E,clearSelectedDashboard:P}=s.useManagementStore(G=>G.actions),{resources:B}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:Y}=s.useCurrentUserInfo(),q=s.canUserManageGroups(Y),z=g||y,J=z?{id:z.id,title:(m==null?void 0:m.title)||z.title||"Dashboard"}:null,{handleAddNewFrame:W}=s.useAddNewFrame(),[se,te]=k.useState(!1),oe=s.useUpdateResource(s.ResourceType.DASHBOARD);k.useEffect(()=>{if(B&&B.length>0){const G=m==null?void 0:m.id;if(G){const V=B.find(Z=>Z.id===G);V&&E(V)}}},[B,m==null?void 0:m.id,E]);const Q=n.orgUserId||n.tenantId,_=x&&!w&&Q&&R,ae=()=>{M(!0)};async function H(){const G=Ke(m);te(!0);const V={template:G};oe.mutate({resourceId:G.id,data:V},{onSuccess:()=>{te(!1),s.ue.success("Dashboard saved!")},onError:()=>{te(!1),s.ue.error("Failed to save dashboard")}})}async function re(){if(p(!0),!i||!u)return;const G=Ke(m),V=JSON.stringify(G),Z={...u,template:V,filterValues:A};await ts(n.apiServiceUrl,Z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),I==null||I(G),p(!1)}const ie=(u==null?void 0:u.name)||m.title,U=B&&B.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),X=g&&!(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-2",children:[U&&e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>{L(!C)},className:"h-7 p-2",children:e.jsx(ia,{className:"h-4 w-4"})}),X&&!w&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Dashboard Hub",onClick:()=>P(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})})]}),!w&&d&&e.jsx(s.Label,{children:ie}),w&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm font-medium",children:(v==null?void 0:v.title)||(D==null?void 0:D.title)||"Untitled Visual"}),e.jsx(at,{})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[w&&e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"mr-2"}),e.jsx(rt,{className:"h-7"})]}),r&&!w&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(xa,{className:"h-4 w-4"})}),!w&&d&&e.jsx(ka,{}),!w&&d&&e.jsx(qs,{}),!w&&d&&q&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>N(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!w&&d&&((K=z==null?void 0:z.permissions)==null?void 0:K.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(Ie,{className:"h-4 w-4"})}),!S&&!w&&x&&c.canUseFilters&&d&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>T(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),x&&!w&&Q&&r&&d&&e.jsx(Da,{}),!w&&Q&&r&&d&&e.jsx(Ta,{}),x&&!w&&Q&&u&&r&&d&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:h,onClick:re,size:"sm",children:[e.jsx(Oe,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),x&&!w&&d&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!x,onClick:()=>W(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!w&&!x&&c.canEdit&&d&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:ae,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),_&&d&&e.jsxs(s.Button,{className:"h-7 p-2",disabled:se,onClick:H,size:"sm",children:[se?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Oe,{className:"mr-2 h-4 w-4"}),se?"Saving...":"Save"]}),!w&&x&&r&&d&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>O(!F),size:"sm",variant:"ghost",children:e.jsx(Us,{className:"h-4 w-4"})})}),!w&&r&&e.jsx(Na,{}),x&&!w&&d&&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"]}),b&&J&&e.jsx(We,{resource:J,resourceType:s.ResourceType.DASHBOARD,onClose:()=>f(!1)}),e.jsx(ln,{open:j,onOpenChange:N})]})]})}function cs(t){const{tokenProps:n,authToken:a}=s.useSemaphorContext(),r=n==null?void 0:n.apiServiceUrl;return s.useQuery({queryKey:["joinability-map",t],queryFn:async()=>{if(!t||!(a!=null&&a.accessToken))return null;const l=`${r}/v1/domains/${t}/joinability`;return s.getRequest(l,a.accessToken)},enabled:!!t&&!!(a!=null&&a.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:l=>Math.min(1e3*2**l,3e4)})}function Ve(t,n,a){if(n==="source")return{isValid:!0};const r=s.getDataType(t.dataType);if(a==="kpi"){if(n==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(n==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function as(t,n,a,r,l){if(t!=="kpi"||l.length<3)return;const c=(n==null?void 0:n.groupByColumns)&&n.groupByColumns.length>0,d=(n==null?void 0:n.comparisonType)==="none";!c&&d||a(r,{groupByColumns:[],comparisonType:"none"})}const ds=t=>{var I;const n=(I=t==null?void 0:t.dataSource)==null?void 0:I.semanticDomainId,{data:a}=cs(n),{updateCardConfig:r,updateGroupByColumn:l,updateMetricColumn:c,updatePivotByColumn:d,updateSortByColumn:o,removeGroupByColumn:i,removeMetricColumn:u,removePivotByColumn:m,removeSortByColumn:x}=s.useEditorActions(),h=s.useEditorStore(T=>T.card.type),p=t==null?void 0:t.id,b=k.useCallback(T=>{if(!(t!=null&&t.config))return[];switch(T){case"groupBy":return(t.config.groupByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,dateFormat:M.dateFormat,customFormat:M.customFormat,granularity:M.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,direction:M.direction}));case"source":return[];default:return[]}},[t]),f=k.useCallback((T,M)=>{if(p)switch(T){case"groupBy":{r(p,{groupByColumns:M});break}case"metrics":{r(p,{metricColumns:M});break}case"pivotBy":{r(p,{pivotByColumns:M});break}case"sortBy":{r(p,{sortByColumns:M});break}}},[p,r]),j=k.useCallback((T,M,O)=>{if(!p)return;const P=b(T)[M];if(P)switch(T){case"groupBy":l(p,P.id,{label:O});break;case"metrics":c(p,P.id,{label:O});break;case"pivotBy":d(p,P.id,{label:O});break;case"sortBy":o(p,P.id,{label:O});break}},[p,b,l,c,d,o]),N=k.useCallback((T,M)=>{if(!p)return;const E=b("metrics")[T];E&&c(p,E.id,{aggregate:M,label:s.getAggregationLabel(E.name,M)})},[p,b,c]),C=k.useCallback((T,M,O)=>{if(!p)return;const P=b("groupBy")[T];if(!P)return;const B={dateFormat:M};M==="custom"&&O?B.customFormat=O:B.customFormat=void 0,l(p,P.id,B)},[p,b,l]),L=k.useCallback((T,M)=>{if(!p)return;const E=b("groupBy")[T];E&&l(p,E.id,{granularity:M})},[p,b,l]),A=k.useCallback((T,M)=>{if(!p)return;const E=b("metrics")[T];E&&c(p,E.id,{aliasTemplate:M})},[p,b,c]),w=k.useCallback((T,M)=>{if(console.log("handleValueAliasesChange",T,M),!p)return;console.log("handleValueAliasesChange",T,M);const E=b("metrics")[T];E&&(console.log("handleValueAliasesChange",M),c(p,E.id,{valueAliases:M}))},[p,b,c]),D=k.useCallback(T=>{if(!p)return;if(b("metrics").length===0){s.ue.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:T})},[p,r,b]),g=k.useCallback(T=>{p&&r(p,{showTrendline:T})},[p,r]),y=k.useCallback(T=>{p&&r(p,{trendlineWindow:T})},[p,r]),v=k.useCallback(T=>{p&&r(p,{trendlineGranularity:T})},[p,r]),R=k.useCallback(T=>{p&&r(p,{targetValue:T})},[p,r]),S=k.useCallback(T=>{var q;if(!p)return;const M=[...b("groupBy"),...b("pivotBy"),...b("metrics"),...b("sortBy")],O=s.validateEntityConsistency(T,M,{joinPlan:(q=t==null?void 0:t.config)==null?void 0:q.joinPlan,joinabilityMap:a==null?void 0:a.joinabilityMap,semanticDomainId:n});if(!O.isValid){O.showError&&s.showJoinRequiredNotification();return}const E=s.getSmartContainerForField(T,M,h);if(!E){s.ue.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const P=Ve(T,E,h);if(!P.isValid){s.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3});return}const B=b(E);if(s.fieldAlreadyExists(T,B))return;const Y=s.getNewField(T,E,B);if(Y){const z=[...B,Y];f(E,z),E==="metrics"&&as(h,t==null?void 0:t.config,r,p,z)}},[p,t==null?void 0:t.config,b,f,n,a,h,r]),F=k.useCallback((T,M)=>{if(!p)return;const E=b(T)[M];if(E){if(T!=="sortBy"){const P=b("sortBy"),B=P.filter(Y=>!(Y.name===E.name&&Y.qualifiedEntityName===E.qualifiedEntityName));B.length!==P.length&&r(p,{sortByColumns:B})}switch(T){case"groupBy":i(p,E.id);break;case"metrics":u(p,E.id);break;case"pivotBy":m(p,E.id);break;case"sortBy":x(p,E.id);break}}},[p,b,i,u,m,x,r]);return{getFieldsForContainer:b,setFieldsForContainer:f,updateLabel:j,handleAggregationChange:N,handleDateFormatChange:C,handleGranularityChange:L,handleAliasTemplateChange:A,handleValueAliasesChange:w,removeField:F,handleFieldClick:S,handleKpiComparisonTypeChange:D,handleKpiShowTrendlineChange:g,handleKpiTrendlineWindowChange:y,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:R,cardType:h}};function _e(t){return`${t}-${s.v4()}`}function ks(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 yn(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 us(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:t==null?void 0:t.connectionId,connectionType:t==null?void 0:t.connectionType};const n=t.selectedEntities[0];return{tableName:n==null?void 0:n.name,schemaName:n==null?void 0:n.schema,databaseName:n==null?void 0:n.database,connectionId:t.connectionId,connectionType:t.connectionType}}function ot(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return!1;const n=t.selectedEntities[0];return!!(n!=null&&n.name)}function it(){const t=s.useEditorStore(D=>D.sqlGen),n=s.useEditorStore(D=>D.isDevMode),a=s.useEditorStore(D=>D.card.dataSource),r=s.useEditorStore(D=>{var g,y;return(y=(g=D.card)==null?void 0:g.queryConfig)==null?void 0:y.metricColumns}),{tableName:l,schemaName:c,databaseName:d}=us(a),o=ot(a),i=s.useEditorStore(D=>D.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:m,setCardSql:x,setRunSql:h,setSqlGen:p,setIsShowingVisual:b}=s.useEditorActions(),{connectionType:f,modelItems:j,selectedDatamodelName:N}=s.useEditorAside(),C=D=>({column_name:D.name,data_type:D.dataType,label:D.label,description:D.description});return{handleDevModeFieldClick:D=>{var y;if(!n)return;const g=C(D);if(n&&o&&l){const v=s.createSqlGenConfig(g,t);p(v);const R=(y=j==null?void 0:j.find(F=>F.id===i))==null?void 0:y.name,S=s.getSql(v,s.fmt(c||""),s.fmt(l),R||"",f,d||"");S&&(x(S),h(!0))}else if(!n){if(s.isTextDataType(g.data_type))if(r&&r.length>0){const v={...g,role:"groupby",id:_e(g.column_name),name:g.column_name,type:g.data_type};m(v)}else{const v={...g,role:"metric",id:_e(g.column_name),name:g.column_name,label:ks(g.column_name,"COUNT"),type:g.data_type,aggregate:"COUNT"};u(v)}if(s.isDateDataType(g.data_type)){const v={...g,role:"groupby",id:_e(g.column_name),name:g.column_name,type:g.data_type,label:yn(g.column_name,"month"),granularity:"month"};m(v)}if(s.isNumberDataType(g.data_type)){const v={...g,role:"metric",id:_e(g.column_name),name:g.column_name,label:ks(g.column_name,"SUM"),type:g.data_type,aggregate:"SUM"};u(v)}}},handleShowSample:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const D=s.getFormattedTableNameForQuery({schemaName:c||"",tableName:l,modelName:N,connectionType:f,databaseName:d||""});b(!1);const g=f==="MSSQL"?`SELECT top 10 * FROM ${D}`:`SELECT * FROM ${D} LIMIT 10`;x(g),h(!0)},handleShowCount:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const D=s.getFormattedTableNameForQuery({schemaName:c||"",tableName:l,modelName:N,connectionType:f,databaseName:d||""});x(`SELECT COUNT(*) as count FROM ${D}`),h(!0)},isNumberField:D=>s.isNumberDataType(D.dataType)}}function ct(){const t=s.useEditorStore(p=>p.selectedConnectionId),n=s.useEditorStore(p=>p.selectedDatamodelId),a=s.useEditorStore(p=>p.selectedDatabaseName),r=s.useEditorStore(p=>p.selectedSchemaName),l=s.useEditorStore(p=>p.selectedTableName),c=s.useDashboardStore(p=>p.dashboard.filters)||[],d=s.useDashboardStore(p=>p.actions.addFilter),o=s.useDashboardStore(p=>p.actions.removeFilter),{removeFilterValues:i}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:x}=s.useEditorAside();function h(p,b="dashboard",f){var y;const j=s.fmt(p.column_name),N=s.fmt(a||""),C=s.fmt(r||""),L=s.fmt(m);let A=s.getQualifiedTableName({schemaName:C,tableName:L,connectionType:x,databaseName:N}),w=`${A}.${j}`;const D=(y=u==null?void 0:u.find(v=>v.id===n))==null?void 0:y.name;n&&n!=="none"&&(w=`${s.DATAMODEL_NAMESPCACE}.${D}.${j}`,A=`${s.DATAMODEL_NAMESPCACE}.${D}`),f!=null&&f.qualifiedFieldName&&(w=f.qualifiedFieldName),f!=null&&f.entityName&&(A=f.entityName);const g=c==null?void 0:c.find(v=>v.column===w&&v.table===L&&(v.database===N||v.database===a));if(g)i(g.id),o(g.id);else{const v=s.v4();return m==="api"&&t?(d({location:b,id:v,column:w,title:p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(p.data_type,A,j)}),v):(d({id:v,location:b,column:w,title:p.column_name,dataType:p.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(p.data_type,A,j)}),v)}}return{assignFilter:h}}function Nn({column:t}){const[n,a]=k.useState(!1),r=s.useEditorStore(N=>N.card.dataSource),{tableName:l,schemaName:c,databaseName:d}=us(r),o=s.useEditorStore(N=>N.selectedDatamodelId),i=s.useEditorStore(N=>N.sqlGen),{modelItems:u,connectionType:m}=s.useEditorAside(),x=s.useEditorStore(N=>N.actions.setSqlGen),h=s.useEditorStore(N=>N.actions.setCardSql),p=s.useEditorStore(N=>N.actions.setRunSql),b=ot(r);function f(N,C){var D;if(!b||!l){console.warn("Cannot generate SQL: missing table metadata");return}const L=s.createSqlGenConfig(N,i,C),A=(D=u==null?void 0:u.find(g=>g.id===o))==null?void 0:D.name;x(L);const w=s.getSql(L,s.fmt(c||""),s.fmt(l),A||"",m,d||"");w&&(h(w),p(!0)),a(!1)}function j(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>f(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>f(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>f(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>f(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>f(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return b?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/container:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:j()})]}):null}function Cn({field:t,fieldState:n}){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}),n&&n.tooltip&&e.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:n.tooltip})}),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 Sn({field:t,context:n="editor",fieldState:a}){const r=s.useEditorStore(S=>S.isDevMode),l=n==="filter",c=r||l||(a==null?void 0:a.state)==="unreachable"&&!l,d=s.useDashboardStore(S=>S.dashboard.filters),{assignFilter:o}=ct(),i=l&&(d==null?void 0:d.some(S=>{var F;return S.title===t.name||((F=S.column)==null?void 0:F.includes(t.name))})),{attributes:u,listeners:m,setNodeRef:x,transform:h,transition:p,isDragging:b}=s.useSortable({id:t.id,disabled:c}),[f,j]=k.useState(!1),N=s.useEditorStore(S=>S.card),{handleFieldClick:C}=ds(N),{handleDevModeFieldClick:L,isNumberField:A}=it(),w=()=>{if(l){const S={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description};o(S,"dashboard",t)}else r?L(t):C(t)},D={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description},g={transform:s.CSS.Transform.toString(h),transition:p},v=(()=>{if(!a||l)return{};const F={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[a.state]||{};return a.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...F},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...F},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...F}}[a.state]||F})(),R=S=>{const F=(S||"").toLowerCase(),I=s.getDataType(F);return I==="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(qe,{className:"h-3 w-3"})}):I==="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(rs,{className:"h-3 w-3"})}):I==="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"})}):I==="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($s,{className:"h-3 w-3"})}):I==="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(Us,{className:"h-3 w-3"})}):I==="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(oa,{className:"h-3 w-3"})}):I==="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(zs,{className:"h-3 w-3"})}):null};return e.jsxs("div",{ref:x,style:g,...c?{}:u,...c?{}:m,className:s.cn("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",b&&"scale-95 opacity-50",!b&&"border",v.borderColor||"border-transparent",v.bgColor||"",v.hoverBorderColor,v.hoverBgColor||"hover:bg-muted",v.opacity,v.cursor,i&&"bg-accent border-accent-foreground/20",{"cursor-pointer":r||l,"cursor-grab active:cursor-grabbing":!c&&!r&&!l}),title:a==null?void 0:a.tooltip,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:w,children:[R(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-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${f?"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(Cn,{field:t,fieldState:a})})]})}),r&&!l&&A(t)&&e.jsx("div",{onClick:S=>S.stopPropagation(),children:e.jsx(Nn,{column:D})})]}),f&&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(Gs,{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(ba,{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 wn({context:t="editor"}={}){var I,T,M,O;const[n,a]=k.useState(""),[r,l]=k.useState("all"),c=s.useEditorStore(E=>E.isDevMode),d=s.useEditorStore(E=>E.card.dataSource),o=s.useEditorStore(E=>E.card.config),i=s.useEditorStore(E=>E.card),{autoJoinMetadata:u}=s.useDashboardCardQuery(i),{columns:m=[],columnGroups:x=[],isLoading:h,error:p}=s.useColumns(),b=(d==null?void 0:d.mode)==="semanticDomain"?d.semanticDomainId:void 0,{data:f}=cs(b),j=[...(o==null?void 0:o.groupByColumns)||[],...(o==null?void 0:o.metricColumns)||[]];(T=(I=o==null?void 0:o.joinPlan)==null?void 0:I.baseEntity)==null||T.name,(O=(M=u==null?void 0:u.resolvedJoinPlan)==null?void 0:M.baseEntity)==null||O.name;const{handleShowSample:N,handleShowCount:C}=it(),L=m.filter(E=>E.name.toLowerCase().includes(n.toLowerCase())||E.dataType.toLowerCase().includes(n.toLowerCase())||E.label&&E.label.toLowerCase().includes(n.toLowerCase())||E.qualifiedEntityName&&E.qualifiedEntityName.toLowerCase().includes(n.toLowerCase())),A=E=>{if(E.dataType==="number"||E.dataType==="integer"||E.dataType==="float"||E.dataType==="decimal"||E.dataType==="currency")return"metrics";const P=s.getDataType(E.dataType);return["date","string","boolean"].includes(P)?"dimensions":P==="number"?"metrics":"dimensions"},D=(r==="all"?L:L.filter(E=>A(E)===r)).reduce((E,P)=>{const B=P.qualifiedEntityName||"Other Fields";return E[B]||(E[B]={label:s.toLabel(P.entityName),fields:[]}),E[B].fields.push(P),E},{}),y=Object.keys(D),v=L.filter(E=>A(E)==="dimensions").length,R=L.filter(E=>A(E)==="metrics").length,S=L.filter(E=>A(E)==="calculated").length,F=L.length>0;return h?e.jsx("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):p?e.jsxs("div",{className:"flex h-full 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:p.message||"Failed to load column data"})]}):!d||!d.selectedEntities||d.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:t==="filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-full 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:[c&&t!=="filter"&&m.length>0&&e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:h,onClick:N,size:"sm",variant:"secondary",className:"grow",children:[h?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(la,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:h,onClick:C,size:"sm",variant:"secondary",className:"grow",children:[h?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(pa,{className:"mr-2 size-4"}),"Count"]})]}),m.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:n,onChange:E=>a(E.target.value)}),n&&e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>a(""),type:"button",children:e.jsx(s.X,{className:"size-3.5"})})]}),F&&e.jsx(s.Tabs,{defaultValue:"all",value:r,onValueChange:E=>l(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:L.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:v})]}),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:R})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(zs,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:S})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:y,className:"space-y-2",children:Object.entries(D).map(([E,P])=>{const B=x.find(Y=>Y.entityName===E)||{entityName:E,label:P.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:B.label||B.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:B.label||B.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:P.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:P.fields.map(Y=>{const q=s.calculateFieldState(Y,{joinabilityMap:(f==null?void 0:f.joinabilityMap)||null,selectedFields:j,cardConfig:o,autoJoinMetadata:u});return e.jsx(Sn,{field:Y,context:t,fieldState:q},Y.id)})})})]},E)})}),Object.keys(D).length===0&&m.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:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(D).length===0&&m.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 dt({context:t="editor"}={}){return e.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",e.jsx(wn,{context:t})," "]})}function Dn({initialJoinPlan:t,availableDataSources:n}){const[a,r]=k.useState(t),[l,c]=k.useState(new Set),d=()=>{const D=a.joins.length>0?Math.max(...a.joins.map(y=>y.sequence))+1:1,g={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,g]}),c(new Set([...l,g.id]))},o=D=>{r({...a,joins:a.joins.filter(g=>g.id!==D)}),c(new Set([...l].filter(g=>g!==D)))},i=(D,g)=>{var S,F;const y=a.joins.find(I=>I.id===D);if(!y)return;const v={...y,...g},R=a.joins.map(I=>I.id===D?v:I);if((S=v.source)!=null&&S.name&&((F=v.target)!=null&&F.name)&&v.joinKeyGroups[0].keys.length===0){const I=n.find(E=>{var P;return E.name===((P=v.source)==null?void 0:P.name)}),T=n.find(E=>{var P;return E.name===((P=v.target)==null?void 0:P.name)}),M={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},operator:"="},O=[...v.joinKeyGroups];O[0]={...O[0],keys:[M]},v.joinKeyGroups=O,R[R.findIndex(E=>E.id===D)]=v}r({...a,joins:R})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:d,removeJoin:o,updateJoin:i,moveJoinUp:D=>{const g=a.joins.findIndex(y=>y.id===D);if(g>0){const y=[...a.joins],v={...y[g]},R={...y[g-1]};y[g]=R,y[g-1]=v,y.forEach((F,I)=>{F.sequence=I+1});const S={...a,joins:y};r(S)}},moveJoinDown:D=>{const g=a.joins.findIndex(y=>y.id===D);if(g<a.joins.length-1){const y=[...a.joins],v={...y[g]},R={...y[g+1]};y[g]=R,y[g+1]=v,y.forEach((F,I)=>{F.sequence=I+1});const S={...a,joins:y};r(S)}},toggleJoinExpansion:D=>{const g=new Set(l);g.has(D)?g.delete(D):g.add(D),c(g)},getAvailableSourceEntities:D=>{if(a.joins.length===0)return n;const g=a.joins.findIndex(v=>v.id===D);if(g===0)return n;const y=new Set;return a.baseEntity.name&&y.add(a.baseEntity.name),a.joins.slice(0,g).forEach(v=>{y.add(v.source.name),y.add(v.target.name)}),n.filter(v=>y.has(v.name))},getAvailableTargetEntities:D=>n.filter(g=>g.name!==D),addJoinKeyGroup:D=>{const g=a.joins.find(v=>v.id===D);if(!g)return;const y=[...g.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];i(D,{joinKeyGroups:y})},updateGroupOperator:(D,g,y)=>{const v=a.joins.find(S=>S.id===D);if(!v)return;const R=[...v.joinKeyGroups];R[g]={...R[g],operator:y},i(D,{joinKeyGroups:R})},removeJoinKeyGroup:(D,g)=>{const y=a.joins.find(R=>R.id===D);if(!y)return;const v=[...y.joinKeyGroups];v.splice(g,1),i(D,{joinKeyGroups:v})},addJoinKey:(D,g)=>{const y=a.joins.find(I=>I.id===D);if(!y)return;const v=n.find(I=>I.name===y.source.name),R=n.find(I=>I.name===y.target.name),S=[...y.joinKeyGroups],F={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(v==null?void 0:v.name)||"",entityName:(v==null?void 0:v.name)||"",entityType:(v==null?void 0:v.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(R==null?void 0:R.name)||"",entityName:(R==null?void 0:R.name)||"",entityType:(R==null?void 0:R.type)||"table"},operator:"="};S[g]={...S[g],keys:[...S[g].keys,F]},i(D,{joinKeyGroups:S})},updateJoinKey:(D,g,y,v,R)=>{const S=a.joins.find(O=>O.id===D);if(!S)return;const F=n.find(O=>O.name===S.source.name),I=n.find(O=>O.name===S.target.name),T=[...S.joinKeyGroups],M=T[g].keys[y];v==="sourceColumnName"&&F?T[g].keys[y]={...M,source:{...M.source,name:R}}:v==="targetColumnName"&&I?T[g].keys[y]={...M,target:{...M.target,name:R}}:v==="operator"&&(T[g].keys[y]={...M,operator:R}),i(D,{joinKeyGroups:T})},removeJoinKey:(D,g,y)=>{const v=a.joins.find(S=>S.id===D);if(!v)return;const R=[...v.joinKeyGroups];R[g].keys.splice(y,1),i(D,{joinKeyGroups:R})},generateSQLPreview:()=>{const D=[...a.joins].sort((v,R)=>v.sequence-R.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let y=`SELECT *
|
|
257
257
|
FROM ${g.name}`;return D.forEach(v=>{const R=n.find(I=>I.name===v.target.name);if(!R)return;const S=v.joinKeyGroups.filter(I=>I.keys&&I.keys.length>0).map(I=>{const T=I.keys.filter(M=>{var O,E,P,B;return((O=M.source)==null?void 0:O.name)&&((E=M.target)==null?void 0:E.name)&&((P=M.source)==null?void 0:P.entityName)&&((B=M.target)==null?void 0:B.entityName)}).map(M=>`${M.source.entityName}.${M.source.name} ${M.operator} ${M.target.entityName}.${M.target.name}`);return T.length>1?`(${T.join(` ${I.operator} `)})`:T[0]}).filter(Boolean),F=S.length>1?S.join(" OR "):S[0]||"condition_here";y+=`
|
|
258
258
|
${v.joinType} JOIN ${R.name}
|
|
259
259
|
ON ${F}`}),y},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(v=>!v.source.name||!v.target.name)||a.joins.some(v=>v.joinKeyGroups.some(R=>R.keys.length===0))||a.joins.some(v=>v.joinKeyGroups.some(R=>R.keys.some(S=>!S.source.name||!S.target.name||!S.operator))))}}function Tn({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:c}=s.useEditorActions();s.useEditorStore(S=>S.card.config);const{columnGroups:d}=s.useColumns(),{joinPlan:o,expandedJoins:i,setJoinPlan:u,addJoin:m,removeJoin:x,updateJoin:h,moveJoinUp:p,moveJoinDown:b,toggleJoinExpansion:f,getAvailableSourceEntities:j,getAvailableTargetEntities:N,addJoinKeyGroup:C,updateGroupOperator:L,removeJoinKeyGroup:A,addJoinKey:w,updateJoinKey:D,removeJoinKey:g,generateSQLPreview:y,isValidConfiguration:v}=Dn({initialJoinPlan:t,availableDataSources:n}),R=S=>{const F=d.find(I=>I.entityName===S);return(F==null?void 0:F.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:o.baseEntity.name,onValueChange:S=>{const F=n.find(I=>I.name===S);u({...o,baseEntity:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:S,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 base entity..."})}),e.jsx(s.SelectContent,{children:n.map(S=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:S.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:S.type}),S.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},S.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:y()})]}),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 (",o.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"]})})]}),o.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:o.joins.map(S=>{const F=n.find(M=>M.name===S.source.name),I=n.find(M=>M.name===S.target.name),T=i.has(S.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:S.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",S.sequence,F&&I&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",F.name," → ",I.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(S.id),disabled:S.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(S.id),disabled:S.sequence===o.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(S.id),children:T?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:()=>x(S.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),T&&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:S.source.name,onValueChange:M=>{const O=n.find(E=>E.name===M);h(S.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:j(S.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:S.joinType,onValueChange:M=>h(S.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:S.target.name,onValueChange:M=>{const O=n.find(E=>E.name===M);h(S.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:!S.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:S.source.name?N(S.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===S.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},M.name)):[]})]})]})]}),S.source.name&&S.target.name&&F&&I&&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:()=>C(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),S.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:S.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:E=>L(S.id,O,E),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:()=>A(S.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((E,P)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[P>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:E.source.name,onValueChange:B=>D(S.id,O,P,"sourceColumnName",B),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:R(S.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:E.operator,onValueChange:B=>D(S.id,O,P,"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:E.target.name,onValueChange:B=>D(S.id,O,P,"targetColumnName",B),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:R(S.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:()=>g(S.id,O,P),children:e.jsx(s.X,{className:"size-3.5"})})]},E.id||P))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>w(S.id,O),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},M.id))})]})]})]},S.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(o),disabled:!v(),children:"Save"})]})]})}function ns({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:c,onSave:d,onCancel:o}){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(Tn,{joinPlan:r,availableDataSources:l,onSave:d,onCancel:o,onRemove:c})]}),t]})}function kn({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((d,o)=>d.sequence-o.sequence),c=a.find(d=>d.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:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(d=>{const o=a.find(i=>i.name===d.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:d.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:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name})]})]},d.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,c)=>l.sequence-c.sequence).map((l,c)=>{const d=a.find(i=>i.name===l.source.name),o=a.find(i=>i.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:c+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[d==null?void 0:d.name," → ",o==null?void 0:o.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((i,u)=>i+u.keys.length,0)," ","condition",l.joinKeyGroups.reduce((i,u)=>i+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 En(){var x,h;const t=s.useEditorStore(p=>p.card),{autoJoinMetadata:n}=s.useDashboardCardQuery(t),a=s.useEditorStore(p=>p.actions.updateCardConfig),r=((x=t==null?void 0:t.config)==null?void 0:x.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[l,c]=k.useState(!1),d=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],o=p=>{a(t.id,{...t==null?void 0:t.config,joinPlan:p}),c(!1)},i=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},u=()=>{c(!1)},m=()=>{const p=[...r.joins].sort((j,N)=>j.sequence-N.sequence),b=r.baseEntity;if(!b.name)return"SELECT * FROM table -- Please select a base entity";let f=`SELECT *
|
|
260
260
|
FROM ${b.name}`;return p.forEach(j=>{const N=d.find(A=>A.name===j.target.name);if(!N)return;const C=j.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const w=A.keys.filter(D=>{var g,y,v,R;return((g=D.source)==null?void 0:g.name)&&((y=D.target)==null?void 0:y.name)&&((v=D.source)==null?void 0:v.entityName)&&((R=D.target)==null?void 0:R.entityName)}).map(D=>`${D.source.entityName}.${D.source.name} ${D.operator} ${D.target.entityName}.${D.target.name}`);return w.length>1?`(${w.join(` ${A.operator} `)})`:w[0]}).filter(Boolean),L=C.length>1?C.join(" OR "):C[0]||"condition_here";f+=`
|
|
261
261
|
${j.joinType} JOIN ${N.name}
|
|
262
|
-
ON ${L}`}),f};return d.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:[r.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:()=>c(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":r.joins.length>0,"text-gray-500":r.joins.length===0})}),"Join",r.joins.length>1?"s":""," (",r.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(kn,{joins:r.joins,baseEntityId:r.baseEntity.name,availableDataSources:d,generateSQLPreview:m})})]})}),(n==null?void 0:n.autoResolved)&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"h-6 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(s.Sparkles,{className:"h-3 w-3"}),"Auto"]})}),e.jsx(s.TooltipContent,{side:"right",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium",children:"Auto-resolved using relationships:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:n.relationshipsUsed.map((p,b)=>e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p},b))})]})})]})}),e.jsx(ns,{open:l,onOpenChange:c,joinPlan:r,availableDataSources:d,onSave:o,onCancel:u,onRemove:i,children:e.jsx("div",{})})]}),r.joins.length===0&&e.jsx(ns,{open:l,onOpenChange:c,joinPlan:r,availableDataSources:d,onSave:o,onCancel:u,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>c(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function In({open:t,onOpenChange:n}){const[a,r]=k.useState([]),{updateDataSource:l}=s.useEditorActions(),c=s.useDashboardStore(f=>f.dashboard.aiContext),d=(c==null?void 0:c.selectedEntities)||[];k.useEffect(()=>{t&&r([])},[t]);const o=f=>{r(j=>j.some(C=>C.name===f.name&&C.type===f.type)?j.filter(C=>!(C.name===f.name&&C.type===f.type)):[...j,f])},i=()=>{r([...d])},u=()=>{r([])},m=()=>{if(a.length===0)return;const f=a[0],j=f.connectionId||"",N=f.connectionType||"",L=a.some(w=>w.type==="dataset")?"semanticDomain":"database";l({connectionId:j,connectionType:N,mode:L,selectedEntities:a}),n(!1)},x=f=>{switch(f.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(va,{className:"h-4 w-4"});case"model":return e.jsx(Kt,{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"})}},h=f=>"label"in f&&f.label?f.label:f.name,p=f=>{if("description"in f&&f.description)return f.description;const j=[];return f.database&&j.push(f.database),f.schema&&j.push(f.schema),f.name&&j.push(f.name),j.join(".")},b=f=>a.some(j=>j.name===f.name&&j.type===f.type);return d.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:i,disabled:a.length===d.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 ",d.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:d.map((f,j)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",b(f)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:b(f),onCheckedChange:()=>o(f)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:x(f)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(f)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:p(f)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:f.type})]},`${f.type}-${f.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 An({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),c=l.find(o=>o.label==="Description"),d=l.filter(o=>o.label==="Description"?!1:!["Connection","Database","Schema"].includes(o.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)}),c&&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:c.value})]}),d.length>0&&e.jsx("div",{className:"space-y-0.5",children:d.map((o,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[o.label,":"]}),e.jsx("span",{className:"font-mono",children:o.value})]},i))})]})})}function Mn({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(d=>d.label==="Description"),c=r.filter(d=>d.label==="Description"?!1:!["Connection","Database","Schema"].includes(d.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})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((d,o)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[d.label,":"]}),e.jsx("span",{className:"font-mono",children:d.value})]},o))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function ut(){const t=s.useEditorStore(d=>d.card.dataSource),{setSelectedConnectionId:n,setSelectedDatabaseName:a,setSelectedSchemaName:r,setSelectedTableName:l,setSelectedDatamodelId:c}=s.useEditorActions();k.useEffect(()=>{var p;if(!t)return;const{tableName:d,schemaName:o,databaseName:i,connectionId:u}=us(t),m=(p=t.selectedEntities)==null?void 0:p[0],h=(m==null?void 0:m.type)==="model"&&"id"in m?m.id:"";n(u||""),a(i||""),r(o||""),l(d||""),c(h)},[t,n,a,r,l,c])}function mt({isVisible:t}){const n=s.useEditorStore(h=>h.isDevMode);ut();const[a,r]=k.useState(!1),[l,c]=k.useState(!1),[d,o]=k.useState(!0),i=s.useEditorStore(h=>h.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:u}=s.useEditorActions(),m={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},x={...m,...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:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})}),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:()=>o(!d),className:"size-6 bg-background p-1 py-1 hover:bg-accent",children:d?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 ${d?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[x.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[x.selectedEntities.slice(0,3).map((h,p)=>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:b=>{b.stopPropagation();const f=x.selectedEntities.filter(j=>!(j.name===h.name&&j.type===h.type));u({...m,...i,selectedEntities:f})},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(An,{entity:h})]},`${h.type}-${h.name}-${p}`)),x.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:["+",x.selectedEntities.length-3," more"]})}),e.jsx(Mn,{entities:x.selectedEntities.slice(3)})]})]})}),!n&&e.jsx(En,{})]})]}),e.jsx(dt,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(i==null?void 0:i.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:x}),e.jsx(In,{open:l,onOpenChange:c})]})}function ht({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:l=!0}){const[c,d]=k.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:c,onOpenChange:d,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:c?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(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:c,onOpenChange:d,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 xt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:c,setCardSql:d,setRunSql:o}=s.useEditorActions();function i(){c(!l),d(t),setTimeout(()=>{o(!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(ht,{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:i,variant:"secondary",size:"sm",children:[e.jsx(Wt,{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(sa,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Rn({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($t,{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(xt,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function Ln(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 pt(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(f=>f.theme),r=s.useEditorStore(f=>f.frame),l=s.useEditorStore(f=>f.card),c=s.useEditorStore(f=>f.activeTabCardId),d=s.Le(),{refetch:o}=s.useDashboardCardQuery(l),{updateCardTab:i,setRunSql:u}=s.useEditorActions(),m=k.useRef(),x=k.useRef({}),h=r.cards.find(f=>f.id===c),p=k.useCallback(()=>{let f="";return t==="python"&&(f=(h==null?void 0:h.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(f=(h==null?void 0:h.sql)||""),f},[t,h]);k.useEffect(()=>{if(c&&l.id&&l.id!==c){if(m.current&&d){const f=m.current.getModel();f&&(x.current[l.id]=f);let j=x.current[c];if(!j){const N=p();j=d.editor.createModel(N,t),x.current[c]=j}m.current.setModel(j)}i(c,l),u(!0)}},[c,l,i,d,u,t,p]),k.useEffect(()=>{if(!d)return;const f=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=a==="system"?f:a;d.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),d.editor.setTheme("default")},[n,a,d]),k.useEffect(()=>{const f=m.current;f&&d&&l&&f.addCommand(d.KeyMod.Shift|d.KeyCode.Enter,function(){return o(),!1})},[d,o,l]);function b(f,j){if(m.current=f,!x.current[l.id]){const N=f.getModel(),C=p();x.current[l.id]=N||(j==null?void 0:j.editor.createModel(C,t))||f.getModel()}f.setModel(x.current[l.id])}return{handleEditorDidMount:b}}function Fn(){const t=s.useEditorStore(d=>d.card.sql),n=s.useEditorStore(d=>d.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=pt("sql");function c(d){a(d),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:c,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function On(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=pt("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 Pn({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 Bn(){const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=k.useState(!1),[l,c]=k.useState(!1);s.useEditorStore(z=>z.frame);const d=s.useEditorStore(z=>z.card);s.useEditorStore(z=>z.isShowingVisual),s.useEditorStore(z=>z.selectedConnectionId),s.useEditorStore(z=>z.tempQueryData),s.useEditorStore(z=>z.selectedDatabaseName),s.useEditorStore(z=>z.selectedDatamodelId),s.useEditorStore(z=>z.selectedSchemaName);const o=s.useEditorStore(z=>z.showAIDialog);s.useEditorStore(z=>z.selectedTableName);const i=s.useEditorStore(z=>{var W;return(W=z==null?void 0:z.card)==null?void 0:W.sql}),u=s.useEditorStore(z=>{var W;return(W=z==null?void 0:z.card)==null?void 0:W.python}),{cardFilterValues:m}=s.useCardFilterValues((d==null?void 0:d.id)??""),{setCardCustomCfg:x,setQueryResultColumns:h,setCardSql:p,setTempQueryData:b,setPythonStdOut:f,setCardPreferences:j,setCardType:N,setCardPython:C,runAssistant:L,setShowAIDialog:A}=s.useEditorActions();s.useEditorStore(z=>z.onSave),s.useEditorStore(z=>z.onClose),s.useEditorStore(z=>z.actions.setSqlGen);const w=s.useEditorStore(z=>z.runSql),D=s.useEditorStore(z=>z.actions.setRunSql),g=s.useEditorStore(z=>z.actions.setIsSqlRunning),{data:y,isLoading:v,isFetching:R,isSuccess:S,isError:F,error:I,errorSql:T,queryKey:M,refetch:O,errorMessage:E}=s.useDashboardCardQuery(d);k.useEffect(()=>{if(y&&(y.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),f((y==null?void 0:y.output)||""),y.records.length>0)){const{dimensionKeys:z}=s.getKeys(y.records);h(z)}},[y,h,f]),k.useEffect(()=>{(v||R)&&g(!0),(F||S)&&g(!1),F&&(h([]),f(""))},[v,R,y,f,F,S,g,h,I]),k.useEffect(()=>{w&&(t.getQueryData(M)||O(),D(!1))},[w,O,D,M,t]);async function P(){const z=`Can you help me debug this query?
|
|
262
|
+
ON ${L}`}),f};return d.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:[r.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:()=>c(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":r.joins.length>0,"text-gray-500":r.joins.length===0})}),"Join",r.joins.length>1?"s":""," (",r.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(kn,{joins:r.joins,baseEntityId:r.baseEntity.name,availableDataSources:d,generateSQLPreview:m})})]})}),(n==null?void 0:n.autoResolved)&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"h-6 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(s.Sparkles,{className:"h-3 w-3"}),"Auto"]})}),e.jsx(s.TooltipContent,{side:"right",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium",children:"Auto-resolved using relationships:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:n.relationshipsUsed.map((p,b)=>e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p},b))})]})})]})}),e.jsx(ns,{open:l,onOpenChange:c,joinPlan:r,availableDataSources:d,onSave:o,onCancel:u,onRemove:i,children:e.jsx("div",{})})]}),r.joins.length===0&&e.jsx(ns,{open:l,onOpenChange:c,joinPlan:r,availableDataSources:d,onSave:o,onCancel:u,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>c(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function In({open:t,onOpenChange:n}){const[a,r]=k.useState([]),{updateDataSource:l}=s.useEditorActions(),c=s.useDashboardStore(f=>f.dashboard.aiContext),d=(c==null?void 0:c.selectedEntities)||[];k.useEffect(()=>{t&&r([])},[t]);const o=f=>{r(j=>j.some(C=>C.name===f.name&&C.type===f.type)?j.filter(C=>!(C.name===f.name&&C.type===f.type)):[...j,f])},i=()=>{r([...d])},u=()=>{r([])},m=()=>{if(a.length===0)return;const f=a[0],j=f.connectionId||"",N=f.connectionType||"",L=a.some(w=>w.type==="dataset")?"semanticDomain":"database";l({connectionId:j,connectionType:N,mode:L,selectedEntities:a}),n(!1)},x=f=>{switch(f.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(va,{className:"h-4 w-4"});case"model":return e.jsx(Kt,{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"})}},h=f=>"label"in f&&f.label?f.label:f.name,p=f=>{if("description"in f&&f.description)return f.description;const j=[];return f.database&&j.push(f.database),f.schema&&j.push(f.schema),f.name&&j.push(f.name),j.join(".")},b=f=>a.some(j=>j.name===f.name&&j.type===f.type);return d.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:i,disabled:a.length===d.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 ",d.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:d.map((f,j)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",b(f)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:b(f),onCheckedChange:()=>o(f)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:x(f)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(f)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:p(f)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:f.type})]},`${f.type}-${f.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 An({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),c=l.find(o=>o.label==="Description"),d=l.filter(o=>o.label==="Description"?!1:!["Connection","Database","Schema"].includes(o.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)}),c&&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:c.value})]}),d.length>0&&e.jsx("div",{className:"space-y-0.5",children:d.map((o,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[o.label,":"]}),e.jsx("span",{className:"font-mono",children:o.value})]},i))})]})})}function Mn({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(d=>d.label==="Description"),c=r.filter(d=>d.label==="Description"?!1:!["Connection","Database","Schema"].includes(d.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})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((d,o)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[d.label,":"]}),e.jsx("span",{className:"font-mono",children:d.value})]},o))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function ut(){const t=s.useEditorStore(d=>d.card.dataSource),{setSelectedConnectionId:n,setSelectedDatabaseName:a,setSelectedSchemaName:r,setSelectedTableName:l,setSelectedDatamodelId:c}=s.useEditorActions();k.useEffect(()=>{var p;if(!t)return;const{tableName:d,schemaName:o,databaseName:i,connectionId:u}=us(t),m=(p=t.selectedEntities)==null?void 0:p[0],h=(m==null?void 0:m.type)==="model"&&"id"in m?m.id:"";n(u||""),a(i||""),r(o||""),l(d||""),c(h)},[t,n,a,r,l,c])}function mt({isVisible:t}){const n=s.useEditorStore(h=>h.isDevMode);ut();const[a,r]=k.useState(!1),[l,c]=k.useState(!1),[d,o]=k.useState(!0),i=s.useEditorStore(h=>h.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:u}=s.useEditorActions(),m={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},x={...m,...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:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})}),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:()=>o(!d),className:"size-6 bg-background p-1 py-1 hover:bg-accent",children:d?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 ${d?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[x.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[x.selectedEntities.slice(0,3).map((h,p)=>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:b=>{b.stopPropagation();const f=x.selectedEntities.filter(j=>!(j.name===h.name&&j.type===h.type));u({...m,...i,selectedEntities:f})},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(An,{entity:h})]},`${h.type}-${h.name}-${p}`)),x.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:["+",x.selectedEntities.length-3," more"]})}),e.jsx(Mn,{entities:x.selectedEntities.slice(3)})]})]})}),!n&&e.jsx(En,{})]})]}),e.jsx(dt,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(i==null?void 0:i.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:x}),e.jsx(In,{open:l,onOpenChange:c})]})}function ht({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:l=!0}){const[c,d]=k.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:c,onOpenChange:d,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:c?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(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:c,onOpenChange:d,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 xt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:c,setCardSql:d,setRunSql:o}=s.useEditorActions();function i(){c(!l),d(t),setTimeout(()=>{o(!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(ht,{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:i,variant:"secondary",size:"sm",children:[e.jsx(Wt,{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(sa,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Rn({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($t,{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(xt,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function Ln(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 pt(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(f=>f.theme),r=s.useEditorStore(f=>f.frame),l=s.useEditorStore(f=>f.card),c=s.useEditorStore(f=>f.activeTabCardId),d=s.Le(),{refetch:o}=s.useDashboardCardQuery(l),{updateCardTab:i,setRunSql:u}=s.useEditorActions(),m=k.useRef(),x=k.useRef({}),h=r.cards.find(f=>f.id===c),p=k.useCallback(()=>{let f="";return t==="python"&&(f=(h==null?void 0:h.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(f=(h==null?void 0:h.sql)||""),f},[t,h]);k.useEffect(()=>{if(c&&l.id&&l.id!==c){if(m.current&&d){const f=m.current.getModel();f&&(x.current[l.id]=f);let j=x.current[c];if(!j){const N=p();j=d.editor.createModel(N,t),x.current[c]=j}m.current.setModel(j)}i(c,l),u(!0)}},[c,l,i,d,u,t,p]),k.useEffect(()=>{if(!d)return;const f=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=a==="system"?f:a;d.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),d.editor.setTheme("default")},[n,a,d]),k.useEffect(()=>{const f=m.current;f&&d&&l&&f.addCommand(d.KeyMod.Shift|d.KeyCode.Enter,function(){return o(),!1})},[d,o,l]);function b(f,j){if(m.current=f,!x.current[l.id]){const N=f.getModel(),C=p();x.current[l.id]=N||(j==null?void 0:j.editor.createModel(C,t))||f.getModel()}f.setModel(x.current[l.id])}return{handleEditorDidMount:b}}function Fn(){const t=s.useEditorStore(d=>d.card.sql),n=s.useEditorStore(d=>d.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=pt("sql");function c(d){a(d),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:c,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function On(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=pt("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 Pn({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 Bn(){const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=k.useState(!1),[l,c]=k.useState(!1);s.useEditorStore(z=>z.frame);const d=s.useEditorStore(z=>z.card);s.useEditorStore(z=>z.isShowingVisual),s.useEditorStore(z=>z.selectedConnectionId),s.useEditorStore(z=>z.tempQueryData),s.useEditorStore(z=>z.selectedDatabaseName),s.useEditorStore(z=>z.selectedDatamodelId),s.useEditorStore(z=>z.selectedSchemaName);const o=s.useEditorStore(z=>z.showAIDialog);s.useEditorStore(z=>z.selectedTableName);const i=s.useEditorStore(z=>{var J;return(J=z==null?void 0:z.card)==null?void 0:J.sql}),u=s.useEditorStore(z=>{var J;return(J=z==null?void 0:z.card)==null?void 0:J.python}),{cardFilterValues:m}=s.useCardFilterValues((d==null?void 0:d.id)??""),{setCardCustomCfg:x,setQueryResultColumns:h,setCardSql:p,setTempQueryData:b,setPythonStdOut:f,setCardPreferences:j,setCardType:N,setCardPython:C,runAssistant:L,setShowAIDialog:A}=s.useEditorActions();s.useEditorStore(z=>z.onSave),s.useEditorStore(z=>z.onClose),s.useEditorStore(z=>z.actions.setSqlGen);const w=s.useEditorStore(z=>z.runSql),D=s.useEditorStore(z=>z.actions.setRunSql),g=s.useEditorStore(z=>z.actions.setIsSqlRunning),{data:y,isLoading:v,isFetching:R,isSuccess:S,isError:F,error:I,errorSql:T,queryKey:M,refetch:O,errorMessage:E}=s.useDashboardCardQuery(d);k.useEffect(()=>{if(y&&(y.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),f((y==null?void 0:y.output)||""),y.records.length>0)){const{dimensionKeys:z}=s.getKeys(y.records);h(z)}},[y,h,f]),k.useEffect(()=>{(v||R)&&g(!0),(F||S)&&g(!1),F&&(h([]),f(""))},[v,R,y,f,F,S,g,h,I]),k.useEffect(()=>{w&&(t.getQueryData(M)||O(),D(!1))},[w,O,D,M,t]);async function P(){const z=`Can you help me debug this query?
|
|
263
263
|
|
|
264
264
|
Error:
|
|
265
265
|
|
|
@@ -275,6 +275,6 @@ ${j.joinType} JOIN ${N.name}
|
|
|
275
275
|
|
|
276
276
|
${u?`Python:
|
|
277
277
|
${u}`:""}
|
|
278
|
-
`;L(z)}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(Pn,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>c(!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 q(){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(Fn,{})}),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(On,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function Y(){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:v||R,onClick:()=>{O()},className:"h-8 shrink-0",size:"sm",children:[v||R?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(Rn,{errorSql:T,sql:y==null?void 0:y.sql,error:E,onDebugWithAssistant:P}),e.jsx(is,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:z=>r(z),className:"h-8",size:"sm",variant:"outline",children:e.jsx(Ln,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:o,onClick:()=>{A(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:o?"":"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:[q(),B()]}),Y()]})}const Vn=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:Qe}];function zn({className:t}){const n=s.useEditorStore(i=>i.card),{setCardType:a,setCard:r,updateCardInFrame:l}=s.useEditorActions(),c=["table","aggregateTable","pivotTable"].includes(n.type),d=s.hasValidCardConfig(n.config);if(!c||!d)return null;const o=i=>{var m;const u=i;if(u==="aggregateTable"&&((m=n.config)!=null&&m.pivotByColumns)&&n.config.pivotByColumns.length>0){const x={...n,type:u,config:{...n.config,pivotByColumns:[]}};r(x),l(x)}else{a(u);const x={...n,type:u};l(x)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:o,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Vn.map(i=>{const u=i.icon,m=n.type===i.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:i.value,id:`table-type-${i.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${i.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"}),i.label]})]},i.value)})})})}function Un({card:t}){var L,A,w,D,g,y,v,R,S,F,I;const[n,a]=k.useState(!1),[r,l]=k.useState([]),{authToken:c}=s.useSemaphorContext(),{theme:d}=s.useTheme(),o=s.getTokenParams(c==null?void 0:c.accessToken),i=s.useDashboardStore(T=>T.themeStyle),u={mode:d||"system",colors:((A=(L=i==null?void 0:i.chart)==null?void 0:L.dataset)==null?void 0:A.backgroundColor)||[]};(w=t.customCardPreferences)!=null&&w.inputData;const{getCard:m}=s.useCustomVisual(((D=t.customCardPreferences)==null?void 0:D.url)||""),x=((g=t.customCardPreferences)==null?void 0:g.visualType)||"single",h=s.useEditorStore(T=>T.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(t),f=k.useCallback((T,M)=>{l(O=>({...O,[T]:M}))},[]);if(!((y=t.customCardPreferences)!=null&&y.componentName))return null;const j=m((v=t.customCardPreferences)==null?void 0:v.componentName);function N(T){a(T)}const C=Object.keys(((R=t.customCardPreferences)==null?void 0:R.dataInputCardIds)||{}).map(T=>{var E,P,B;const M=(P=(E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)==null?void 0:P[T].cardId,O=(B=h==null?void 0:h.cards)==null?void 0:B.find(q=>q.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(k.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[j&&x==="single"&&e.jsx(j,{editing:!0,params:o,theme:u,settings:(S=t.customCardPreferences)==null?void 0:S.settings,onDataChange:f,data:(b==null?void 0:b.records)||[]}),j&&x==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)||{}).map(T=>{var E,P,B;const M=(P=(E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)==null?void 0:P[T].cardId,O=(B=h==null?void 0:h.cards)==null?void 0:B.find(q=>q.id===M);if(O)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:N,onDataChange:f,dataInputIndex:T,card:O},O.id+T)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(j,{theme:u,onDataChange:f,settings:C.map(T=>{var M;return(M=T==null?void 0:T.customCardPreferences)==null?void 0:M.settings}),data:C.map(T=>T!=null&&T.id?r==null?void 0:r[T.id]:[])})})]})]},(I=t.customCardPreferences)==null?void 0:I.componentName)})}function ft({className:t,...n}){var y;const a=s.useEditorStore(v=>v.card),r=s.hasValidCardConfig(a.config),l=((y=a.customCardPreferences)==null?void 0:y.showCardHeader)??!0,c=s.useEditorStore(v=>v.frame),d=s.useDashboardStore(v=>v.dashboard.filters),o=s.useEditorStore(v=>v.actions.setRunSql),{updateFilter:i}=s.useDashboardActions(),u=d==null?void 0:d.find(v=>v.id===c.filterId),{data:m,isLoading:x,isFetching:h,errorMessage:p,pagination:b}=s.useDashboardCardQuery(a),{setCard:f,updateCardInFrame:j}=s.useEditorActions(),{data:N}=s.useTopoJson(a),C=k.useMemo(()=>{var v;return a.type!=="pivotTable"||!((v=m==null?void 0:m.records)!=null&&v.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]),L=s.usePivotTableConfig(a,C),A=(v,R)=>{var F,I;const S={...a,paginationConfig:{page:v+1,pageSize:R}};f(S),j(S),a.sql&&((I=(F=a.preferences)==null?void 0:F.tablePrefs)!=null&&I.enableDevModePagination)&&o(!0)},w=k.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:N}),[a.id,m==null?void 0:m.records,a.type,a.queryConfig,a.customCfg,a.preferences,N]);function D(v){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Un,{card:v})})}function g(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!x&&!h)return p?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((x||h)&&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)&&w)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:x||h?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:w})});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:A,isLoading:x||h})});if(a.type==="pivotTable"&&L)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:L.data,options:L.options,onAggregationChange:v=>{const R=s.handleAggregationChange(v,a.config),S={...a,config:R};f(S),j(S)},onAggregationLabelChange:v=>{const R=s.handleAggregationLabelChange(v,a.config),S={...a,config:R};f(S),j(S)}})});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:A,onAggregationChange:v=>{const R=s.handleAggregationChange(v,a.config),S={...a,config:R};f(S),j(S)},isLoading:x||h})})}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:v=>f({...a,title:v}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(zn,{})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:v=>f({...a,description:v}),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:v=>i({...u,title:v}),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:g()})]})}const Xe=({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}),_n=()=>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."})]})]}),Gn=({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(Xe,{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(Xe,{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(Xe,{language:"javascript",value:t,onChange:l})})]}),$n=({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 Yn(){const[t,n]=k.useState(!1),[a,r]=k.useState(""),[l,c]=k.useState(""),[d,o]=k.useState(""),[i,u]=k.useState(""),m=s.useEditorStore(w=>w.card),x=s.useEditorStore(w=>w.card.customCfg),h=x?JSON.stringify(x,null,2):"",{data:p}=s.useDashboardCardQuery(m),{data:b}=s.useTopoJson(m),{setCardCustomCfg:f,setCustomVisualCode:j}=s.useEditorActions(),N=w=>{var D,g;return JSON.stringify({...w,data:{...w.data,datasets:(g=(D=w.data)==null?void 0:D.datasets)==null?void 0:g.map(y=>({...y,data:[]}))}},null,2)},C=()=>{var D,g;if(!((D=p==null?void 0:p.records)!=null&&D.length))return;const w=s.createChartConfig({card:m,data:p.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:b});if(w){r(N(w)),o(((g=m.preferences)==null?void 0:g.customVisualCode)||"");const y=s.merge(w,x);c(N(y))}},L=()=>{try{if(d&&j(d),l){const w=JSON.parse(l),D=s.getObjectDiff(JSON.parse(a),w);f(D),u("")}}catch{u("Invalid JSON configuration")}},A=Object.keys(x||{}).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:C,className:A?"":"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(_n,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(ft,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Gn,{customCode:d,cardCustomCfgString:h,mergedConfig:l,onConfigChange:w=>c(w??""),onCodeChange:w=>o(w??"")})]}),e.jsx($n,{error:i,hasCardCustomConfig:!!x,onReset:()=>{c(a),f(null)},onApply:L,onClose:()=>n(!1)})]})]})}function Je(t){const[n,a]=k.useState(null);return n}function gt(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{data:a,isLoading:r,isFetching:l,isError:c}=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:c}}function jt(){const{data:t,isLoading:n,isError:a}=gt(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(o=>({queryKey:["manifest",o.value],queryFn:()=>s.loadManifest(o.value),enabled:!!o.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:i=>Math.min(1e3*2**i,3e4)}))}),l=[];let c=n,d=a;return r.forEach((o,i)=>{var u;if(o.isLoading&&(c=!0),o.isError&&(d=!0),o.data&&((u=t==null?void 0:t.plugins)!=null&&u[i])){const m=t.plugins[i],x=o.data.visuals.map(h=>({name:h.name,pluginName:m.label,componentType:h.componentType,pluginType:m.type,icon:h.icon,chartType:h.chartType,url:m.value}));l.push(...x)}}),{data:l,isLoading:c,isError:d}}function qn({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:c,isLoading:d,isError:o}=jt(),i=k.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 d?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..."})})]}):o?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"})})]}):!c||c.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:c.map((u,m)=>e.jsx(Kn,{text:u.name,onClick:()=>i("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const Kn=({text:t,icon:n,onClick:a})=>{const r=Je(),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 Hn({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:c,setCustomCardPreferences:d,setQueryConfig:o}=s.useEditorActions();function i(m,x){c(null),r({}),a(m),["custom","text","map"].includes(m)&&(l(!0),o(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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>i("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:()=>i("custom"),className:"h-10 p-4",children:e.jsx(ze,{className:s.cn("size-5",n)})})]})}function Qn({chartType:t,className:n,customIcon:a,componentName:r}){const l=Je();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(qe,{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(ze,{className:n});default:return e.jsx(s.Table2,{className:n})}}function bt({variant:t="ghost"}){var c,d;const[n,a]=k.useState(!1),r=s.useEditorStore(o=>o.card),l=r.type;return s.useDashboardStore(o=>o.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(Qn,{className:"size-4",chartType:l,customIcon:(c=r.customCardPreferences)==null?void 0:c.icon,componentName:(d=r.customCardPreferences)==null?void 0:d.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:o=>o.preventDefault(),className:"z-[51] w-72 p-1",children:[e.jsx(Hn,{onChartTypeChange:()=>a(!1)}),e.jsx(qn,{onChartTypeChange:()=>a(!1)})]})]})}function Wn({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,c]=k.useState(!1),d=k.useRef(null),o=k.useRef(!1);function i(){t&&!o.current&&navigator.clipboard.writeText(t)}function u(h){(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),i())}function m(){const h=window.getSelection();if(h&&h.toString().trim()!==""){const p=h.toString();navigator.clipboard.writeText(p),c(!0),o.current=!0,setTimeout(()=>{c(!1),o.current=!1},1e3)}else o.current=!1}function x(){c(!1),o.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:d,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:i,onKeyDown:u,onMouseUp:m,onMouseDown:x,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 Jn(){const t=s.useEditorStore(c=>{var d,o;return(o=(d=c.card.preferences)==null?void 0:d.chartOptions)==null?void 0:o.indexAxis}),n=s.useEditorStore(c=>c.card.type),{setChartOrientation:a}=s.useEditorStore(c=>c.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(Cs,{className:"size-4"}):e.jsx(Ns,{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(Cs,{className:"size-4"}):e.jsx(Ns,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function Xn({className:t}){var h,p,b,f,j,N,C,L;const n=s.useEditorStore(A=>A.card),{setCardPreferences:a,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[c,d]=k.useState(!1),o=((p=(h=n.preferences)==null?void 0:h.displayOptions)==null?void 0:p.showFilterInfo)??!0,i=((f=(b=n.preferences)==null?void 0:b.displayOptions)==null?void 0:f.showCardToolbar)??!0,u=((N=(j=n.preferences)==null?void 0:j.displayOptions)==null?void 0:N.showChrome)??!0,m=((L=(C=n.preferences)==null?void 0:C.displayOptions)==null?void 0:L.allowScroll)??!0,x=(A,w)=>{var y;const D={...n.preferences,displayOptions:{...(y=n.preferences)==null?void 0:y.displayOptions,[A]:w}};a(D);const g={...n,preferences:D};l(g),r(g)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:c,onOpenChange:d,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(_s,{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:o,onCheckedChange:A=>{x("showFilterInfo",A)},onSelect:A=>A.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:i,onCheckedChange:A=>{x("showCardToolbar",A)},onSelect:A=>A.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:A=>{x("showChrome",A)},onSelect:A=>A.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:A=>{x("allowScroll",A)},onSelect:A=>A.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 vt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var d,o;return(o=(d=c.card)==null?void 0:d.preferences)==null?void 0:o.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function l(){const c=["xy","none","x","y"],o=(c.indexOf(a)+1)%c.length;r(c[o])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(Jn,{})}),!["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(Qe,{className:"size-4"}),a==="x"&&e.jsx(Yt,{className:"size-4"}),a==="y"&&e.jsx(ma,{className:"size-4"}),a==="none"&&e.jsx(fa,{className:"size-4"})]}),e.jsx(Xn,{})]})}function Zn(){const t=s.useEditorStore(b=>b.frame),n=s.useEditorStore(b=>b.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:c}=s.useEditorActions(),d=(b,f)=>{b.dataTransfer.setData("tabIndex",f.toString())},o=b=>{b.preventDefault()},i=(b,f)=>{const j=b.dataTransfer.getData("tabIndex");if(j===f.toString())return;const N=Array.from(t.cards),[C]=N.splice(parseInt(j),1);N.splice(f,0,C),a({...t,cards:N})};function u(b){const f=t.cards.filter(C=>C.id!==b),j=f[0],N={...t,cards:f,activeCardId:j.id};a(N),r(j.id),l(j)}function m(b,f){const j={...t,cards:[...t.cards,f],activeCardId:b.id};a(j),r(f.id)}function x(){const b={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};m(n,b)}function h(b){const f={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,f)}function p(b,f){return b.cards.length===1&&(f.displayTab===!0||f.displayTab===void 0)||b.activeCardId!==f.id&&(f.displayTab===!0||f.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const j=f.displayTab===void 0?!1:!f.displayTab;l({...f,displayTab:j}),c({...f,displayTab:j})},children:f.displayTab===!0||f.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(Qt,{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,f)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:j=>d(j,f),onDragOver:o,onDrop:j=>i(j,f),className:"",value:b.id,children:[p(t,b),e.jsx(s.Editable,{enabled:t.activeCardId===b.id,text:b.tabTitle||b.title,onSave:j=>{l({...n,tabTitle:j}),c({...n,tabTitle:j})},children:b.tabTitle||b.title},b.id),t.activeCardId===b.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:j=>{j.stopPropagation(),x()}}),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.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>h(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function yt(){const t=s.useEditorStore(j=>j.frame),n=s.useEditorStore(j=>j.card),a=s.useEditorStore(j=>j.isSqlRunning),r=s.useEditorStore(j=>j.isDevMode),{setFrame:l,setActiveTabCardId:c,setCard:d,setIsDevMode:o,setRunSql:i}=s.useEditorActions(),{data:u,isLoading:m,isFetching:x,isError:h}=s.useDashboardCardQuery(n);function p(j){const N=t.cards.find(C=>C.id===j);if(N!=null&&N.sql){r||o(!0),c(j);return}if(N!=null&&N.queryConfig){r&&o(!1),b(j),c(j);return}r||b(j),c(j)}function b(j){const N={...t,cards:t.cards.map(L=>L.id===n.id?n:L),activeCardId:j};l(N);const C=N.cards.find(L=>L.id===j);C.sql&&i(!0),d(C)}function f(){return n.type==="kpi"?m||x?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||x,isError:h})})}):n.type==="text"?m||x?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(ft,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:p,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(j=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:j.id,children:f()},j.id)),e.jsx(Zn,{})]})}function Es({children:t}){var D,g;s.useEditorStore(y=>y.frame);const n=s.useEditorStore(y=>y.card),a=s.useEditorStore(y=>y.isDevMode),r=s.useEditorStore(y=>y.isShowingVisual),l=s.useDashboardStore(y=>y.isVisualEditing),c=s.useEditorStore(y=>y.pythonStdOut);s.useEditorStore(y=>y.actions.setRunSql);const{setFrame:d,setCard:o,setActiveTabCardId:i,runAssistant:u,setIsDevMode:m,setCardPreferences:x}=s.useEditorActions(),{data:h,isLoading:p,isFetching:b,errorMessage:f,refetch:j}=s.useDashboardCardQuery(n),[N,C]=k.useState(!1);k.useEffect(()=>{b||C(!1)},[b]);function L(){const y=JSON.stringify(h==null?void 0:h.records,null,2),v=new Blob([y],{type:"application/json"}),R=URL.createObjectURL(v),S=document.createElement("a");S.href=R,S.download=`${n.title}.json`,S.click()}function A(){const v=[Object.keys(h==null?void 0:h.records.reduce((I,T)=>({...I,...T}),{})).join(","),...((h==null?void 0:h.records)||[]).map(I=>Object.values(I).join(","))].join(`
|
|
279
|
-
`),R=new Blob([v],{type:"text/csv"}),S=URL.createObjectURL(R),F=document.createElement("a");F.href=S,F.download=`${n.title}.csv`,F.click()}function w(){const y=`Can you get the documentation for ${n.type} chart?`;u(y)}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(bt,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:w,children:e.jsx(_t,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(Yn,{})]}),!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:A,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:L,children:e.jsx(Jt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(h==null?void 0:h.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(s.IconButton,{tooltip:"Refresh",disabled:p||b,onClick:()=>{C(!0),j()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":N})})}),e.jsx(vt,{})]}),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:((g=(D=n.preferences)==null?void 0:D.tablePrefs)==null?void 0:g.enableDevModePagination)??!1,onCheckedChange:y=>{var v;x({...n.preferences,tablePrefs:{...(v=n.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:y}}),j()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(sr,{})]}),r?e.jsx(yt,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[c&&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:c&&e.jsx(er,{})}),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":c}),children:[(h==null?void 0:h.records)&&(h==null?void 0:h.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(h==null?void 0:h.records)||[]}),f&&e.jsx(Wn,{error:f})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function er(){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 sr(){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 Se({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:c,icon:d,showPlaceholderLabel:o=!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",c),children:e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("span",{children:d}),o&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(i=>e.jsx(s.SelectItem,{value:i.value,children:i.label},i.value))]})})]})}function tr(){var f,j;const t=s.useEditorStore(N=>N.card.customCardPreferences),{data:n}=gt(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(N=>N.card),l=s.useEditorStore(N=>N.frame),c=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:d}=s.useEditorActions(),{components:o,manifest:i}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(f=i==null?void 0:i.visuals)==null?void 0:f.find(N=>N.name===(t==null?void 0:t.componentName));function m(N,C){if(!t)return;const A={...(t==null?void 0:t.dataInputCardIds)||{},[N]:{cardId:C,hookRef:null}};d({...t,dataInputCardIds:A})}function x(N){var L,A;const C=(L=l==null?void 0:l.cards)==null?void 0:L.filter(w=>{var D;return((D=w==null?void 0:w.customCardPreferences)==null?void 0:D.visualType)!=="multiple"}).map(w=>({value:w.id,label:w.tabTitle||w.title}));return e.jsx("div",{className:"space-y-2",children:(A=N==null?void 0:N.dataInputs)==null?void 0:A.map((w,D)=>{var g,y;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:w}),e.jsx(Se,{className:"col-span-6 h-8 w-full justify-between",label:"",options:C||[],value:((y=(g=t==null?void 0:t.dataInputCardIds)==null?void 0:g[D])==null?void 0:y.cardId)||"",onValueChange:v=>m(D,v)})]},D+Math.random())})})}function h(N,C,L=[],A=""){var w,D;return t?N==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((w=t==null?void 0:t.settings)==null?void 0:w[C])||A,onChange:g=>{d({...t,settings:{...t==null?void 0:t.settings,[C]:g.target.value}})}},C):N==="select"?e.jsx(Se,{className:"h-8 w-full",label:"",options:L,value:((D=t==null?void 0:t.settings)==null?void 0:D[C])||A,onValueChange:g=>{d({...t,settings:{...t==null?void 0:t.settings,[C]:g}})}}):null:null}function p(N){const C=Object.entries((N==null?void 0:N.settings)||{});return e.jsx("div",{className:"space-y-3",children:C.map(([L,A])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:A.title}),h(A.ui,L,A.options,A.defaultValue)]},L))})}function b(N){t&&d({...t,visualType:N,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(Se,{icon:e.jsx(Ut,{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:N=>d({...t||{url:"",componentName:""},url:N})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:c,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:o&&e.jsx(Se,{icon:e.jsx(qt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.filter(N=>N.type===c).map(N=>({value:N.name,label:N.name})))||[],value:t.componentName,onValueChange:N=>{console.log("changing value",N),d({...t,componentName:N})}})})]})})]}),((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:x(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:p(u)})})]})]})]})}function Me(){const[t,n]=k.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),c=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),k.useEffect(()=>{c&&n(new Array(c.length).fill(!1))},[c]);function d(u,m){var x,h;m?a!=null&&a.onClickFilter&&((x=a==null?void 0:a.onClickFilter)==null?void 0:x.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):l({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...a,onClickFilter:(h=a==null?void 0:a.onClickFilter)==null?void 0:h.filter(p=>p.columnIndex!==u)}),n(p=>{const b=[...p];return b[u]=!1,b}))}function o(u,m){var h;const x=(h=a==null?void 0:a.onClickFilter)==null?void 0:h.map(p=>p.columnIndex===u?{...p,expression:m.target.value}:p);l({...a,onClickFilter:x})}function i(u){var m,x,h,p;if(t!=null&&t[u]||(x=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(b=>b.columnIndex===u))!=null&&x.expression)return e.jsx(s.Input,{value:(p=(h=a==null?void 0:a.onClickFilter)==null?void 0:h.find(b=>b.columnIndex===u))==null?void 0:p.expression,onChange:b=>o(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:c==null?void 0:c.map((u,m)=>{var x,h;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:!!((x=a==null?void 0:a.onClickFilter)!=null&&x.find(p=>p.columnIndex===m)),onCheckedChange:p=>d(m,p)}),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:((h=a==null?void 0:a.onClickFilter)==null?void 0:h.find(p=>p.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{n(p=>{const b=[...p];return b[m]=!p[m],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),i(m)]})},u)})})}function ar({idx:t}){var o;const n=s.useEditorStore(i=>{var u;return(u=i.card)==null?void 0:u.preferences}),a=s.useEditorStore(i=>{var u;return(u=i.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(i=>i.actions.setCardPreferences),l=(o=n==null?void 0:n.chartOptions)==null?void 0:o.indexAxis,c=a==null?void 0:a.find(i=>i.idx===t);function d(i,u){(i==="end"||i==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:i!=="none",align:i,anchor:i,clamp:!0};if(!c)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:m}]});else{const x={...c};x.datalabels=m;const h=a==null?void 0:a.map(p=>p.idx===u?x:p);r({...n,datasetOptions:h})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Gs,{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:()=>d("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>d("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(aa,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>d("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ra,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>d("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(na,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function nr(){const t=s.useEditorStore(c=>c.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(c=>!s.METADATA_KEYS.includes(c));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const c=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:d}=s.getKeys(c);l=d.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function ms({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 Nt(){const t=s.useEditorStore(i=>i.card),n=s.useEditorStore(i=>{var u,m,x;return(x=(m=(u=i==null?void 0:i.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:x.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:c,transformedMetricKeys:d,keys:o}=nr();return o.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:c.map(i=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:i,children:Ct(i)},i))})]}),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:d.map((i,u)=>e.jsx(St,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:i,idx:u},i))})]})]})}function Ct(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function St({col:t,idx:n,className:a,iconClassName:r,children:l}){const c=s.useEditorStore(m=>{var x;return(x=m.card)==null?void 0:x.preferences}),d=s.useEditorStore(m=>{var x,h;return(h=(x=m.card)==null?void 0:x.preferences)==null?void 0:h.datasetOptions}),o=d==null?void 0:d.find(m=>m.idx===n),{setCardPreferences:i}=s.useEditorStore(m=>m.actions);function u(m){if(!o)i({...c,datasetOptions:[...d||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const x={...o};x.type=m==="area"?"line":m,x.fill=m==="area"?"origin":"";const h=d==null?void 0:d.map(p=>p.idx===n?x:p);i({...c,datasetOptions:h})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(ms,{className:"max-w-[100px]",title:t,children:Ct(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(ar,{idx:n})]})]})}function Pe(){const t=s.useDashboardStore(o=>o.dashboard.filters),n=s.useEditorStore(o=>o.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=ct();function c(o){const i=l(o,"frame");a({...n,filterId:i})}const d=t==null?void 0:t.find(o=>o.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(rr,{onSelect:c,columns:r}),d&&e.jsx(s.FilterHeader,{filter:d})]})}function rr({columns:t,onSelect:n}){var d;const[a,r]=ss.useState(!1),[l,c]=ss.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?(d=t.find(o=>o.column_name===l))==null?void 0:d.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(o=>e.jsxs(s.CommandItem,{value:o.column_name,onSelect:i=>{const u=i===l?"":i;c(u),r(!1),u&&n(o)},children:[o.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===o.column_name?"opacity-100":"opacity-0")})]},o.column_name))})]})]})})]})}function lr({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(Nt,{})})]}),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(Me,{}),e.jsx(Pe,{})]})]})]})})}function or({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:c=>c.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(Me,{}),e.jsx(Pe,{})]})]})]})})}function wt(){const t=s.useEditorStore(o=>o.card.type),n=s.useEditorStore(o=>o.isDevMode),a=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:r}=s.useEditorStore(o=>o.actions);function l(o){var m;const i={datalabels:{display:o!=="none",align:o,anchor:o,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(m=a==null?void 0:a.chartOptions)==null?void 0:m.plugins,...i}}};r(u)}function c(){var o,i,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=(i=(o=a==null?void 0:a.chartOptions)==null?void 0:o.plugins)==null?void 0:i.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 d(){var o,i,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(i=(o=a==null?void 0:a.chartOptions)==null?void 0:o.plugins)==null?void 0:i.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?c():d()})}const ir={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},cr={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function dr(){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:ur(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(wt,{}),e.jsx(Me,{}),e.jsx(Pe,{})]})]})}function ur(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(ir,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(cr,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 mr({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(d,o,i){const u=[...t];u[d]={...u[d],[o]:i},n(u)}function l(d){const o=[...t];o.splice(d,1),n(o)}function c(){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:c,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((d,o)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:i=>r(o,"start",i.target.value),value:d.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:d.end,onChange:i=>r(o,"end",i.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:i=>r(o,"color",i.target.value),value:d.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(o),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},o))]})}function hr(){var m,x,h,p,b;const t=s.useEditorStore(f=>f.card.preferences),n=s.useEditorStore(f=>f.actions.setCardPreferences),a=s.useEditorStore(f=>f.card),r=s.hasValidCardConfig(a.config),l=s.useEditorStore(f=>f.actions.setNumberFormat);s.useEditorStore(f=>{var j,N;return(N=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:N.decimalPlaces});const c=s.useEditorStore(f=>{var j,N;return(N=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:N.locale}),d=s.useEditorStore(f=>{var j,N;return(N=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:N.currency});s.useEditorStore(f=>f.actions.setFilterOnClickField);const o=s.useEditorStore(f=>{var j,N;return(N=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:N.colorRanges})||[],i=s.useEditorStore(f=>f.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(f=>f.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:f=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:f}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((x=t==null?void 0:t.formatNumber)==null?void 0:x.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:c||"none",onValueChange:f=>{var j,N,C;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((N=t==null?void 0:t.formatNumber)==null?void 0:N.currency)||"",f,((C=t==null?void 0:t.formatNumber)==null?void 0:C.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(f=>e.jsx(s.SelectItem,{value:f.locale,children:f.locale},f.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:d||"none",onValueChange:f=>{var j,N,C;console.log("currency",f),l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,f==="none"?"":f,((N=t==null?void 0:t.formatNumber)==null?void 0:N.locale)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.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(f=>e.jsx(s.SelectItem,{value:f,children:f},f))]})})]})]})]}),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:((p=(h=t==null?void 0:t.formatNumber)==null?void 0:h.decimalPlaces)==null?void 0:p.toString())||"0",onValueChange:f=>{var j,N,C;return l(Number(f),((j=t==null?void 0:t.formatNumber)==null?void 0:j.currency)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.locale)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.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(f=>e.jsx(s.SelectItem,{value:f,children:f},f))})]})]}),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:f=>{var j,N,C;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((N=t==null?void 0:t.formatNumber)==null?void 0:N.currency)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",f.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(mr,{colorRanges:o,setColorRanges:i})]})]})}function xr(){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(hr,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function Ze({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 pr=[{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"}],fr=["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"],gr=fr.map(t=>({label:t,value:t}));function jr(){var i,u,m,x,h,p,b,f,j,N,C,L,A,w,D,g,y,v;const t=s.useEditorStore(R=>R.card),n=(u=(i=t==null?void 0:t.preferences)==null?void 0:i.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=k.useState(((x=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:c}=s.useTopoJson(t),d=Object.keys((c==null?void 0:c.objects)||{}).map(R=>({label:R,value:R}))||[],o=[{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(Ze,{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(Ze,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Se,{className:"h-9",options:o,onValueChange:R=>{console.log("value",R),l({...t.preferences,mapVisualOptions:{topoJsonUrl:R}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:R=>{r(R.target.value)},onBlur:()=>{var R;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(R=t.preferences)==null?void 0:R.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(Se,{className:"h-9",options:d,value:((p=(h=t.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:R=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,objectKey:R}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(Se,{className:"h-9",options:pr,value:((f=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:f.projection)||"",label:"Projection",onValueChange:R=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projection:R}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(Se,{className:"h-9",options:gr,value:((N=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:N.colorScale)||"",label:"Select Color Scale",onValueChange:R=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,colorScale:R}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ze,{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:((L=(C=t.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:L.projectionScale)||1,onChange:R=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionScale:Number(R.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=(w=(A=t.preferences)==null?void 0:A.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:D[0])||0,onChange:R=>{var S,F,I,T;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[Number(R.target.value),((T=(I=(F=t.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:T[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((v=(y=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:y.projectionOffset)==null?void 0:v[1])||0,onChange:R=>{var S,F,I,T;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[((T=(I=(F=t.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:T[0])||0,Number(R.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Me,{})]})}function br(){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 Ge({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(br,{})})]}),!["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(Me,{}),e.jsx(Pe,{})]})]})]})})}function vr(){const t=s.useEditorStore(r=>{var l,c;return(c=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:c.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(Se,{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(Nt,{})]})]}),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(Me,{}),e.jsx(Pe,{})]})]})]})})}function yr({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var c;return(c=l.card)==null?void 0:c.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(Me,{}),e.jsx(Pe,{})]})]})}),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 Dt({color:t,onColorChange:n,onClose:a}){const[r,l]=k.useState(0),[c,d]=k.useState(100),[o,i]=k.useState(50),[u,m]=k.useState(t);k.useEffect(()=>{const j=Is(t);if(j){const N=As(j.r,j.g,j.b);l(N.h),d(N.s),i(N.l),m(t)}},[t]);const x=j=>{l(j),p(j,c,o)},h=j=>{const N=j.currentTarget.getBoundingClientRect(),C=Math.max(0,Math.min(1,(j.clientX-N.left)/N.width)),L=Math.max(0,Math.min(1,(j.clientY-N.top)/N.height)),A=C*100,w=(1-L)*100;d(A),i(w),p(r,A,w)},p=(j,N,C)=>{const L=Cr(j,N,C),A=Nr(L.r,L.g,L.b);m(A)},b=j=>{if(m(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const N=Is(j);if(N){const C=As(N.r,N.g,N.b);l(C.h),d(C.s),i(C.l)}}},f=()=>{/^#[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:h,onMouseMove:j=>{j.buttons===1&&h(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:`${c}%`,top:`${100-o}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>x(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:f,children:"OK"})]})]})}function Is(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 Nr(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function As(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let c=0,d=0;const o=(r+l)/2;if(r!==l){const i=r-l;switch(d=o>.5?i/(2-r-l):i/(r+l),r){case t:c=((n-a)/i+(n<a?6:0))/6;break;case n:c=((a-t)/i+2)/6;break;case a:c=((t-n)/i+4)/6;break}}return{h:Math.round(c*360),s:Math.round(d*100),l:Math.round(o*100)}}function Cr(t,n,a){t/=360,n/=100,a/=100;let r,l,c;if(n===0)r=l=c=a;else{const d=(u,m,x)=>(x<0&&(x+=1),x>1&&(x-=1),x<.16666666666666666?u+(m-u)*6*x:x<.5?m:x<.6666666666666666?u+(m-u)*(.6666666666666666-x)*6:u),o=a<.5?a*(1+n):a+n-a*n,i=2*a-o;r=d(i,o,t+1/3),l=d(i,o,t),c=d(i,o,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(c*255)}}const Sr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Tt(){var L,A,w,D,g,y,v,R,S,F;const t=s.useEditorStore(I=>I.card),n=s.useEditorStore(I=>{var T;return(T=I.card)==null?void 0:T.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[c,d]=k.useState({}),[o,i]=k.useState(null),[u,m]=k.useState(null),x=k.useMemo(()=>{var O,E,P,B,q,Y,z;if(!(l!=null&&l.records)||l.records.length===0)return[];const I=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",T=(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((I||T)&&M){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const W=new Set;return l.pivotSchema.forEach(X=>{X.alias&&W.add(X.alias)}),Array.from(W)}if(l.records.length>0){const W=l.records[0],X=Object.keys(W),se=new Set;(E=t==null?void 0:t.config)!=null&&E.groupByColumns&&t.config.groupByColumns.forEach(H=>{se.add(H.label||H.name),se.add(H.alias||H.name)});const te=new Set;return(P=t==null?void 0:t.config)!=null&&P.metricColumns&&t.config.metricColumns.forEach(H=>{const $=H.alias||H.name;te.add($),te.add(`${$}_count`),te.add(`${$}_sum`),te.add(`${$}_avg`),te.add(`${$}_min`),te.add(`${$}_max`);const ae=H.entityName||H.qualifiedEntityName;ae&&(te.add(`${ae}_${$}`),te.add(`${ae}_${$}_count`))}),X.filter(H=>!se.has(H)&&!te.has(H))}}if((T||I)&&!M&&((q=(B=t==null?void 0:t.config)==null?void 0:B.metricColumns)!=null&&q.length))return t.config.metricColumns.map(W=>W.alias||W.label||W.name);if((z=(Y=t==null?void 0:t.config)==null?void 0:Y.groupByColumns)!=null&&z.length){const W=t.config.groupByColumns[0],X=W.label||W.name,se=new Set;return l.records.forEach(te=>{const ie=te[X];ie!=null&&se.add(String(ie))}),Array.from(se)}return[]},[l,(L=t==null?void 0:t.config)==null?void 0:L.groupByColumns,(A=t==null?void 0:t.config)==null?void 0:A.pivotByColumns,(w=t==null?void 0:t.config)==null?void 0:w.metricColumns,t==null?void 0:t.type]),h=k.useMemo(()=>s.getDefaultChartColors(),[]);k.useEffect(()=>{const I={};x.forEach((T,M)=>{I[T]=s.getColorForValue(T,M,n==null?void 0:n.colorConfig)}),d(I)},[x,n==null?void 0:n.colorConfig,h]);const p=(I,T)=>{const M={...c,[I]:T};d(M);const O={...n||{},colorConfig:{segments:M}};a(O);const E={...t,preferences:O};r(E)},b=(I,T)=>{var q;const M=h[T%h.length],{[I]:O,...E}=((q=n==null?void 0:n.colorConfig)==null?void 0:q.segments)||{},P={...n||{},colorConfig:{segments:E}};a(P);const B={...t,preferences:P};r(B),d(Y=>({...Y,[I]:M}))};if(!x.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((g=(D=t==null?void 0:t.config)==null?void 0:D.groupByColumns)==null?void 0:g.length)||((v=(y=t==null?void 0:t.config)==null?void 0:y.pivotByColumns)==null?void 0:v.length):(S=(R=t==null?void 0:t.config)==null?void 0:R.groupByColumns)==null?void 0:S.length)||["table","kpi","text","custom"].includes(t.type))return null;const N=()=>{const I={...n||{},colorConfig:{segments:{}}};a(I);const T={...t,preferences:I};r(T);const M={};x.forEach((O,E)=>{M[O]=s.getColorForValue(O,E,void 0)}),d(M)},C=Object.keys(((F=n==null?void 0:n.colorConfig)==null?void 0:F.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(da,{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:C&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:N,children:[e.jsx(Ss,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:x.map((I,T)=>{const M=s.isDefaultColor(c[I],T),O=!M;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:o===I,onOpenChange:E=>i(E?I: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:c[I]}})}),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:h.slice(0,10).map((E,P)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",c[I]===E?"border-gray-900":"border-transparent"),style:{backgroundColor:E},onClick:()=>{p(I,E),i(null)},children:[P===T%h.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:E})]},`default-${P}`))})]}),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:Sr.map((E,P)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",c[I]===E?"border-2 border-gray-900":E==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:E},onClick:()=>{p(I,E),i(null)},children:e.jsx("span",{className:"sr-only",children:E})},`preset-${P}`))})]}),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:I,color:c[I]}),i(null)},children:"Custom color"}),!M&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(I,T),i(null)},children:[e.jsx(Ss,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:I}),O&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},I)})}),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(Dt,{color:u.color,onColorChange:I=>{p(u.value,I),m(null)},onClose:()=>m(null)})})]})]})})]})}function we({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[c,d]=k.useState(t??""),[o,i]=k.useState(!1);k.useEffect(()=>{d(t??"")},[t]);const u=()=>{n(c),i(!1)},m=()=>{d(t??""),i(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:o?c:t??"",onChange:x=>{d(x.target.value),i(!0)},onFocus:()=>i(!0),onClick:x=>x.stopPropagation(),className:"h-8 text-xs",onPointerDown:x=>x.stopPropagation(),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&o&&c!==t?u():x.key==="Escape"&&m()},"aria-label":a||"Edit field"}),o&&c!==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 wr=["auto","number","currency","percent","scientific","date"],Dr=[{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"}],Tr=[{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"}],kr=t=>t.charAt(0).toUpperCase()+t.slice(1);function hs({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",c=(o,i)=>{n({...t,[o]:i})},d=()=>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:o=>c("type",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:wr.map(o=>e.jsx(s.SelectItem,{value:o,className:"text-xs",children:o==="auto"?"Auto (Default)":kr(o)},o))})]})]}),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??d(),onChange:o=>c("decimalPlaces",parseInt(o.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:o=>c("currency",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Dr.map(o=>e.jsx(s.SelectItem,{value:o.value,className:"text-xs",children:o.label},o.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:o=>c("useSuffix",o)})]}),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:o=>c("locale",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Tr.map(o=>e.jsx(s.SelectItem,{value:o.value,className:"text-xs",children:o.label},o.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:o=>c("prefix",o.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:o=>c("suffix",o.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:o=>c("negativeInParentheses",o)})]}),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:o=>c("multiplyBy",o.target.value?parseFloat(o.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:o=>c("dateFormat",o.target.value),className:"h-8 text-xs"})})]})]})]})}function Ms({axis:t,label:n,type:a,config:r,onChange:l}){var x,h,p,b,f,j,N,C,L,A,w,D;const c=(g,y)=>{l({...r,[g]:y})},d=(g,y)=>{var v,R;l({...r,name:{enabled:g==="enabled"?y:((v=r==null?void 0:r.name)==null?void 0:v.enabled)??!1,text:g==="text"?y:(R=r==null?void 0:r.name)==null?void 0:R.text}})},o=(g,y)=>{var v,R;l({...r,labels:{enabled:g==="enabled"?y:((v=r==null?void 0:r.labels)==null?void 0:v.enabled)??!0,rotation:g==="rotation"?y:(R=r==null?void 0:r.labels)==null?void 0:R.rotation}})},i=(g,y)=>{l({...r,scale:{...r==null?void 0:r.scale,[g]:y===""?"auto":Number(y)}})},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:g=>c("enabled",g),onClick:g=>g.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:((x=r==null?void 0:r.name)==null?void 0:x.enabled)??!1,onCheckedChange:g=>d("enabled",g)})]}),((h=r==null?void 0:r.name)==null?void 0:h.enabled)&&e.jsx(we,{placeholder:`${n} title`,value:((p=r==null?void 0:r.name)==null?void 0:p.text)||"",onSave:g=>d("text",g),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:g=>c("position",g),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(g=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:g==="auto"?"Auto (Default)":s.titleCase(g)},g))})]})]}),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:g=>o("enabled",g)})]}),((f=r==null?void 0:r.labels)==null?void 0:f.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:g=>o("rotation",g==="auto"?"auto":Number(g)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(g=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:g==="auto"?"Auto (Default)":`${g}°`},g))})]})]})]}),a==="value"&&e.jsx(hs,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:g=>l({...r,formatOptions:g}),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:((N=r==null?void 0:r.scale)==null?void 0:N.min)==="auto"||((C=r==null?void 0:r.scale)==null?void 0:C.min)===void 0?"":String(r.scale.min),onSave:g=>i("min",g),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:((L=r==null?void 0:r.scale)==null?void 0:L.max)==="auto"||((A=r==null?void 0:r.scale)==null?void 0:A.max)===void 0?"":String(r.scale.max),onSave:g=>i("max",g),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:((w=r==null?void 0:r.scale)==null?void 0:w.stepSize)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.stepSize)===void 0?"":String(r.scale.stepSize),onSave:g=>i("stepSize",g),className:""})})]})]})]})]})]})}function kt(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.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 c=(d,o)=>{const u={...n||{},[d==="x"?"xAxisConfig":"yAxisConfig"]:o};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(_s,{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(Ms,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:d=>c("x",d)}),l.hasYAxis&&e.jsx(Ms,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:d=>c("y",d)})]})})]})}function Et(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var m,x,h,p;return(p=(h=(x=(m=u.card)==null?void 0:m.preferences)==null?void 0:x.chartOptions)==null?void 0:h.plugins)==null?void 0:p.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",c=!(t.type==="stackedBar"||t.type==="stackedLine"),d=(u,m)=>{const x={...n,[u]:m};a(x)},o=["top","bottom","left","right"],i=["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(ta,{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)??c,onCheckedChange:u=>d("display",u)})]}),((n==null?void 0:n.display)??c)&&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=>d("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:o.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=>d("align",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))})]})]})]})]})})]})}function It(){var y,v,R,S,F,I,T,M,O;const t=s.useEditorStore(E=>E.card),n=s.useEditorStore(E=>{var P,B;return(B=(P=E.card)==null?void 0:P.preferences)==null?void 0:B.dataLabelsConfig}),a=s.useEditorStore(E=>{var P;return(P=E.card)==null?void 0:P.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const c=((y=a==null?void 0:a.chartOptions)==null?void 0:y.indexAxis)==="y",d=t.type==="stackedBar"||t.type==="stackedLine",o=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",i=!o,u=(R=(v=a==null?void 0:a.chartOptions)==null?void 0:v.plugins)==null?void 0:R.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),x=(n==null?void 0:n.enabled)!==void 0?n.enabled:m,h=(E,P)=>{const B={...n,[E]:P},q={...t.preferences||{},dataLabelsConfig:B};r(q);const Y={...t,preferences:q};l(Y)},p=(E,P)=>{const B={...n,font:{...n==null?void 0:n.font,[E]:P}},q={...t.preferences||{},dataLabelsConfig:B};r(q);const Y={...t,preferences:q};l(Y)},b=(E,P)=>{const B={...n,formatOptions:{...n==null?void 0:n.formatOptions,[E]:P}},q={...t.preferences||{},dataLabelsConfig:B};r(q);const Y={...t,preferences:q};l(Y)},j=(()=>{const E=t.type;return E==="stackedBar"||E==="stackedLine"||E==="pie"||E==="doughnut"?"center":c?"right":"top"})();let N=[];d||o?N=["center"]:N=["auto",...(c?["center","left","right"]:["center","top","bottom"]).filter(P=>P!==j),"custom"];const C=()=>s.titleCase(j),L=["center","start","end"],A=["center","start","end","top","bottom"],w=i?["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"}],g=[{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(ja,{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:x,onCheckedChange:E=>h("enabled",E)})]}),x&&e.jsxs(e.Fragment,{children:[!d&&!o&&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:E=>h("position",E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(E=>e.jsx(s.SelectItem,{value:E,className:"text-xs",children:E==="auto"?C():E==="custom"?"Custom (Advanced)":s.titleCase(E)},E))})]})]}),d&&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:E=>h("showTotal",E)})]}),(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:E=>h("anchor",E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:L.map(E=>e.jsx(s.SelectItem,{value:E,className:"text-xs",children:s.titleCase(E)},E))})]})]}),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:E=>h("align",E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:A.map(E=>e.jsx(s.SelectItem,{value:E,className:"text-xs",children:s.titleCase(E)},E))})]})]})]}),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)||(i?"auto":"none"),onValueChange:E=>h("format",E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:w.map(E=>e.jsx(s.SelectItem,{value:E,className:"text-xs",children:E==="auto"&&i?"Auto (Use Axis)":E==="none"?"None (Raw Value)":s.titleCase(E)},E))})]})]}),(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(((S=n==null?void 0:n.formatOptions)==null?void 0:S.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:E=>b("decimalPlaces",Number(E)),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:((F=n==null?void 0:n.formatOptions)==null?void 0:F.currency)||"USD",onValueChange:E=>b("currency",E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:D.map(E=>e.jsx(s.SelectItem,{value:E.value,className:"text-xs",children:E.label},E.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:((I=n==null?void 0:n.formatOptions)==null?void 0:I.useSuffix)??!1,onCheckedChange:E=>b("useSuffix",E)})]}),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:((T=n==null?void 0:n.formatOptions)==null?void 0:T.locale)||"en-US",onValueChange:E=>b("locale",E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:g.map(E=>e.jsx(s.SelectItem,{value:E.value,className:"text-xs",children:E.label},E.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:E=>p("size",Number(E)),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:E=>p("weight",E),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:E=>{E==="auto"&&h("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:E=>h("rotation",Number(E)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Er(){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(Tt,{}),e.jsx(kt,{}),e.jsx(Et,{}),e.jsx(It,{})]})]})}const Ir=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."]})]}),Ar=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."]})]}),Mr=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 Rr(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=c=>r.includes(a)?c:e.jsxs(e.Fragment,{children:[c,e.jsx(Er,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(vr,{}));case"tornado":case"pyramid":return l(e.jsx(Ge,{docContent:Ir,cardType:a}));case"kpi":return e.jsx(xr,{});case"line":case"bar":return l(e.jsx(lr,{cardType:a}));case"range":return l(e.jsx(Ge,{docContent:Ar,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Ge,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(or,{cardType:a}));case"table":return e.jsx(yr,{cardType:a});case"text":return e.jsx(Ge,{docContent:Mr,cardType:a,suffix:"Visual"});case"map":return e.jsx(jr,{});case"custom":return e.jsx(tr,{});default:return l(e.jsx(dr,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Lr(){const t=k.useRef(null),n=k.useRef(null),a=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog);return k.useEffect(()=>{var l,c,d,o;r?((l=t.current)==null||l.resize(0),(c=n.current)==null||c.resize(0)):((d=t.current)==null||d.resize(25),(o=n.current)==null||o.resize(25))},[r]),e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Bn,{})}),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(Rr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Es,{})})]}):e.jsx(Es,{})})]})}function Fr(t){s.useAIInteractionStore(U=>U.currentAIContext);const[n,a]=k.useState(""),[r,l]=k.useState(null),{authToken:c,tokenProps:d}=s.useSemaphorContext(),o=s.useEditorStore(U=>{var ee;return(ee=U==null?void 0:U.card)==null?void 0:ee.sql}),i=s.useEditorStore(U=>U.isDevMode),u=s.useEditorStore(U=>{var ee;return(ee=U==null?void 0:U.card)==null?void 0:ee.python}),{setCardPython:m,setCardSql:x,setRunSql:h,switchCardType:p,setQueryConfig:b}=s.useEditorActions(),f=s.useEditorStore(U=>U.currentAssitantScope)||[],j=s.useEditorStore(U=>U.userInputForAI),N=s.useEditorStore(U=>U.triggerAIRun),C=s.useEditorStore(U=>U.card),L=s.useEditorStore(U=>U.selectedDatabaseName),A=s.useEditorStore(U=>U.selectedTableName),w=s.useEditorStore(U=>U.selectedConnectionId),D=s.useEditorStore(U=>U.selectedSchemaName),g=s.useDashboardStore(U=>U.dashboard.aiScopeTables),{errorMessage:y,refetch:v,data:R}=s.useDashboardCardQuery(C),{setTriggerAIRun:S,setCurrentAssitantScope:F,setCardConfig:I}=s.useEditorActions(),{selectedDatamodelName:T,connectionType:M,selectedDatamodelId:O}=s.useEditorAside(),{messages:E,setMessages:P,regenerate:B,error:q,sendMessage:Y,status:z,addToolResult:W,stop:X,clearError:se}=s.useChat({transport:new s.DefaultChatTransport({api:`${d.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const U=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:i,aiContext:U.currentAIContext,reasoningEffort:U.reasoningEffort,showReasoning:U.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:U,body:ee})=>({body:{...ee,messages:s.cleanupIncompleteMessages(U)}})}),onError:U=>{var ee;if(U.name==="AbortError"||(ee=U.message)!=null&&ee.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",U)},onToolCall:te,onFinish({isAbort:U,isDisconnect:ee,isError:ce}){a(""),console.log(U?"[Editor Assistant] Stream aborted by user":ee?"[Editor Assistant] Stream disconnected (network error)":ce?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});k.useEffect(()=>{N&&j&&(Y({role:"user",parts:[{type:"text",text:j}]}),S(!1))},[N,j,Y,S]);async function te({toolCall:U}){var ee,ce,le,fe,ue,K,_,V,Z,oe,de,ne,me,pe,Re,Le;if(["createChartFromSql","createForecast"].includes(U.toolName)){const De=((ee=U.input)==null?void 0:ee.sql)??((ce=U.args)==null?void 0:ce.sql),ve=((le=U.input)==null?void 0:le.python)??((fe=U.args)==null?void 0:fe.python),J=((ue=U.input)==null?void 0:ue.chartType)??((K=U.args)==null?void 0:K.chartType);p(J),x(De),m(ve),h(!0),W({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(U.toolName==="getUserSql"){if(!o){W({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"error",message:"No SQL found"}});return}W({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",sql:o,python:u||""}})}else if(U.toolName==="generateQueryConfig"){a("Generating query config...");const De=((_=U.input)==null?void 0:_.chartType)??((V=U.args)==null?void 0:V.chartType),ve=((Z=U.input)==null?void 0:Z.queryConfig)??((oe=U.args)==null?void 0:oe.queryConfig);((de=U.input)==null?void 0:de.cardConfig)??((ne=U.args)==null||ne.cardConfig),p(De),I(ve),x(void 0),m(void 0);const J=await v();if((me=J==null?void 0:J.data)!=null&&me.error){W({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"error",queryConfig:ve,message:(pe=J==null?void 0:J.data)==null?void 0:pe.error.message}});return}if((Re=J==null?void 0:J.data)!=null&&Re.records){W({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",queryConfig:ve,message:"The data has been visualized"}});return}W({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",queryConfig:ve,message:"The data has been visualized",records:(Le=J==null?void 0:J.data)==null?void 0:Le.records}})}else a("Analyzing...")}function ie(U){const ee=s.removeFromScopeArray(f,U);H(ee)}function H(U){const ee=s.sanitizeAIScope(U);F(ee),P(ce=>[...ce,{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 $(){const U={databaseName:L||"",schemaName:D||"",tableName:A||"",datamodelId:O||"",datamodelName:s.resolveDatamodelName(T),connectionId:w||"",connectionType:M||""},ee=s.dedup([...f,U]);H(ee)}function ae(){const U={databaseName:L||"",schemaName:D||"",tableName:A||"",datamodelName:s.resolveDatamodelName(T),connectionId:w||"",connectionType:M||"",datamodelId:O||""};if(!s.isInAiScopeArray([...g||[],...f],U)||f.length===0){const ce=s.dedup([...g||[],...f,U]).filter(le=>le.connectionId===U.connectionId);H(ce)}}const Q=!["ready","error"].includes(z),re=s.getErrorMessage(q);return{messages:E,setMessages:P,sendMessage:Y,regenerate:B,isLoading:Q,handleSetAIScope:ae,handleAddCurrentTableToScope:$,removeFromCurrentSelections:ie,currentAssitantScope:f,setCurrentAssitantScope:F,stop:X,status:z,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:re,clearError:se}}const Or=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Rs({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=k.useRef(null),[l,c]=k.useState(!1),[d,o]=k.useState(s.isDevEnv),[i,u]=k.useState(!1),[m,x]=k.useState(!1),[h,p]=k.useState(!1),b=t??h,f=s.useCurrentAIContext(),{setCurrentAIContext:j}=s.useAIActions(),{clearQueue:N}=s.useQueueActions(),{clearFileAttachments:C}=s.useFileActions(),L=s.useFileAttachments("editor"),A=s.useDashboardStore(J=>J.dashboard.aiContext),w=s.useEditorStore(J=>J.card.dataSource),D=s.useEditorStore(J=>J.actions.setCardSql),g=s.useEditorStore(J=>J.actions.setRunSql),y=s.useEditorStore(J=>J.showAIDialog),v=s.useDashboardStore(J=>J.handleOpenAssistantProfile),{setShowAIDialog:R,setCardPython:S}=s.useEditorActions(),{setDataSource:F}=s.useEditorActions(),{assistantProfile:I}=s.useAssistantProfile(),{messages:T,setMessages:M,sendMessage:O,isLoading:E,stop:P,status:B,llmUsage:q,errorMessage:Y,clearError:z}=Fr(),[W,X]=k.useState(""),se=J=>{X(J.target.value)},te=J=>{J.preventDefault();const ge=W.trim();if(!ge&&L.length===0)return;const Be=[];ge&&Be.push({type:"text",text:ge}),L.forEach(ke=>{ke.data&&Be.push({type:"file",mediaType:ke.type,filename:ke.name,url:`data:${ke.type};base64,${ke.data}`})}),O({role:"user",parts:Be}),X(""),C("editor"),le({force:!0})},{visibleMessages:ie,hasMoreMessages:H,totalMessageCount:$,loadMoreMessages:ae,resetMessageWindow:Q}=s.useMessageWindow(T,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:re,isAtBottom:U,hasNewMessages:ee,newMessageCount:ce,scrollToBottom:le,handleScroll:fe,resetNewMessageCount:ue}=s.useAutoScroll(ie,{threshold:50,behavior:"smooth"});k.useEffect(()=>{var J;y&&((J=r.current)==null||J.focus(),j({selectedEntities:(w==null?void 0:w.selectedEntities)||[]}))},[y,w,j]),s.useAutoSubmitQueue({assistantType:"editor",status:B,isLoading:E,sendMessage:O});const{hasActiveTools:K}=s.useActiveToolStatus(T),_=k.useCallback(J=>{n==null||n(J),t===void 0&&p(J)},[t,n]);k.useEffect(()=>{if(!b)return;function J(ge){ge.key==="Escape"&&_(!1)}return window.addEventListener("keydown",J),()=>{window.removeEventListener("keydown",J)}},[b,_]);const V=k.useCallback(J=>{O({role:"user",parts:[{type:"text",text:J}]}),le({force:!0})},[O,le]),Z=k.useCallback(async()=>{const J=JSON.stringify(T??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(J),s.ue.success("Conversation copied")}catch(ge){console.error("Failed to copy conversation",ge),s.ue.error("Unable to copy conversation")}},[T]),oe=k.useCallback(()=>{_(!b)},[b,_]);function de(J,ge){ge==="sql"?(D(J),g(!0)):ge==="python"&&(S(J),g(!0))}function ne(){f.selectedEntities.length===0&&j({selectedEntities:(A==null?void 0:A.selectedEntities)||[]})}function me(J){ne();const ge={role:"user",parts:[{type:"text",text:J.title+" "+J.subtitle}]};O(ge)}function pe(J){ne(),O({role:"user",parts:[{type:"text",text:J}]})}function Re(){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 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:l,onCheckedChange:c,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:u,children:"System Message"})]})]})}function Le(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const De=(W==null?void 0:W.length)===0&&(T==null?void 0:T.filter(J=>J.role==="user").length)===0,ve=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",b&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Le(),v&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:v,children:(I==null?void 0:I.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Re(),d&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Z,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:b?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:oe,children:b?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{M([]),N("editor"),z(),Q()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{R(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:re,className:"mt-2 flex w-full grow basis-0",onScroll:fe,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[H&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:ae,className:"text-xs",children:["Load ",Math.min(5,$-ie.length)," ","more messages (",$-ie.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:ie,showTools:d,handleRun:de,showSystemMessage:i,onQuickReply:V,disableQuickReplies:E}),!K&&e.jsx(s.AssistantStatus,{status:B,errorMessage:Y})]})}),!U&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{le({force:!0}),ue()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),ee&&ce>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:ce>9?"9+":ce})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[De&&!I&&e.jsx(s.Placeholders,{onClick:me,placeholders:Or}),e.jsx("div",{children:De&&I&&e.jsx(s.SeedQuestions,{seedQuestions:I.seedQuestions||[],handleSeedQuestionClick:pe})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:X,stop:P,input:W,handleInputChange:se,handleSubmit:J=>{ne(),te(J),le({force:!0})},isLoading:E,status:B,assistantType:"editor",onFocus:()=>{}})]}),q&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",q.inputTokens," prompt tokens, ",q.outputTokens," ","completion tokens, ",q.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(w==null?void 0:w.selectedEntities)||[],open:m,onOpenChange:x,dataSource:w||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return b&&a?Vt.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:ve})}),a):ve}function xs(t,n){const[a,r]=k.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):n});return k.useEffect(()=>{localStorage.setItem(t,JSON.stringify(a))},[a,t]),[a,r]}const Pr="chart-selector-standard-first";function Br(){const[t,n]=xs(Pr,!0);return{standardFirst:t,updatePreference:n}}const Ls=({pluginVisual:t,index:n,onSelect:a})=>{const r=Je(t.icon||""),l=t.name.charAt(0).toUpperCase(),c=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"}):c||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}`)},Fs=["default","standardPlugin","customPlugin"];function Vr({selectedChart:t,onChartChange:n}){var A;const[a,r]=k.useState(!1),{data:l}=jt();Br();const d=((A=s.useEditorStore(w=>w.card).customCardPreferences)==null?void 0:A.url)||"";os(d);const{setCardType:o,setCardPreferences:i,setIsDevMode:u}=s.useEditorStore(w=>w.actions),{setCardCustomCfg:m,setCustomCardPreferences:x,setQueryConfig:h}=s.useEditorActions(),[p,b]=xs("chart-section-active",null),f=k.useMemo(()=>p?[p,...Fs.filter(w=>w!==p)]:Fs,[p]);function j(w){m(null),i({}),o(w),["custom","map"].includes(w)&&(u(!0),h(void 0)),n(w),r(!1)}function N(w){m(null),i({}),o("custom"),x({type:"component",visualType:"single",url:w.url,componentName:w.name,icon:w.icon,pluginChartType:w.chartType}),h(void 0),n("custom"),r(!1)}const C=()=>{var D;if(t==="custom"){const g=s.useEditorStore.getState().card;return((D=g==null?void 0:g.customCardPreferences)==null?void 0:D.componentName)||"Custom Visual"}const w=s.chartTypes.find(g=>g.id===t);return(w==null?void 0:w.label)||"Select chart type"},L=()=>{var D,g;if(t==="custom"){const y=s.useEditorStore.getState().card,v=(D=y==null?void 0:y.customCardPreferences)==null?void 0:D.icon,R=(g=y==null?void 0:y.customCardPreferences)==null?void 0:g.componentName;if(v&&R)return e.jsx(zr,{icon:v,componentName:R});if(R){const S=s.getAutoDetectedChartIcon(R);if(S)return S}return e.jsx(ze,{className:"h-4 w-4"})}const w=s.chartTypes.find(y=>y.id===t);if(w){const y=w.icon;return e.jsx(y,{className:"h-4 w-4"})}return e.jsx(ze,{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:[L(),e.jsx("span",{children:C()})]}),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."}),f.map(w=>{if(w==="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:p==="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 g=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(g,{className:"h-4 w-4"}),e.jsx("span",{children:D.label})]})},D.id)})},"default");if(w==="standardPlugin"){const D=l.filter(g=>g.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:p==="standardPlugin",onCheckedChange:g=>b(g?"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(g=>g.componentType==="chart").map((g,y)=>e.jsx(Ls,{pluginVisual:g,index:y,onSelect:()=>N(g)},`${g.url}-${g.name}-${y}`))},"standardPlugin"):null}if(w==="customPlugin"){const D=l.filter(g=>g.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:p==="customPlugin",onCheckedChange:g=>b(g?"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((g,y)=>e.jsx(Ls,{pluginVisual:g,index:y,onSelect:()=>N(g)},`${g.url}-${g.name}-${y}`))},"customPlugin"):null}return null})]})]})})]})})}const zr=({icon:t,componentName:n})=>{const a=Je(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(ze,{className:"h-4 w-4"})},Ur=[{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 _r({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(c=>c.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:Ur.map(c=>{if(c.requiresPivot&&!r)return null;const d=c.icon,o=t===c.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(c.id),className:s.cn("h-8 w-8 p-0",o&&"bg-accent text-accent-foreground"),children:[e.jsx(d,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:c.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:c.label})})]},c.id)})})}const ps=({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(qe,{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(rs,{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($s,{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(qe,{className:"h-3 w-3"})})};function Gr({aliasTemplate:t,onAliasTemplateChange:n}){var i;const[a,r]=k.useState(t),[l,c]=k.useState(!1),d=(i=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:i[0],o=d?`e.g. Min Sales in {{${d.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:o,value:l?a:t,onChange:u=>{r(u.target.value),c(!0)},onFocus:()=>c(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&a!==t?(n(a),c(!1)):u.key==="Escape"&&(r(t),c(!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),c(!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),c(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function $r({valueAliases:t,onValueAliasesChange:n}){const[a,r]=k.useState(null),[l,c]=k.useState(""),[d,o]=k.useState(""),i=()=>{n({...t,"":""})},u=x=>{const h={...t};delete h[x],n(h)},m=x=>{const h={...t};delete h[x],h[l]=d,n(h),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(([x,h],p)=>e.jsx("div",{className:"flex items-center gap-2",children:a===x?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>c(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(x):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:d,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(x):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(x),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:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),c(x),o(h)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),c(x),o(h)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(x),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},x+p)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:i,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Yr({column:t}){const n=s.useEditorStore(i=>i.card.type),a=s.useEditorStore(i=>{var u,m;return(m=(u=i.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(a==null?void 0:a.map(i=>i.label))||[],l=r==null?void 0:r.find(i=>i===t.label||i===t.name),c=l?r.indexOf(l):-1;function d(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(St,{idx:c,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function o(){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(wt,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&d(),["pie","doughnut"].includes(n)&&o()]})}function qr({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),c=s.useEditorStore(u=>u.card),d=c==null?void 0:c.dataSource,o=["attribute-values",t.entityName,t.name,n,a],i=s.useQuery({queryKey:o,queryFn:async()=>{if(!(d!=null&&d.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:d.connectionId,cardConfig:u,cardDataSource:d,cache_config:s.getCacheConfig({card:c})};console.log("requestBody",m);const x=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(x!=null&&x.error)return console.error("Error fetching attribute values:",x.error),[];const h=t.name;return((x==null?void 0:x.records)||[]).map(b=>{const f=b[h]||b[t.alias||h]||b[t.label];return{id:f||"",value:f||"",label:String(f||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(d!=null&&d.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:i.data||[],isLoading:i.isLoading,isFetching:i.isFetching,isError:i.isError,error:i.error,refetch:i.refetch}}function Kr({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:c}){var L,A;const d=!!l,[o,i]=k.useState(d?"values":"fields"),[u,m]=k.useState(""),[x,h]=k.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]:[]}),p=a.filter(w=>{var g;return d?!1:!((g=r==null?void 0:r.conditions)==null?void 0:g.some(y=>y.field.id===w.id))&&w.label.toLowerCase().includes(u.toLowerCase())}),b=w=>{h({...x,field:w}),i("values")},f=()=>{if(x.field&&x.selectedValues.length>0){const w={id:x.id,field:x.field,operator:"in",value:x.selectedValues};let D;if(d){const g=((r==null?void 0:r.conditions)||[]).map(y=>y.id===l.id?w:y);D={...r,conditions:g}}else{const g=(r==null?void 0:r.conditions)||[];D={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...g,w],groups:[]}}c(D),n(!1)}},j=()=>{if(!d||!l)return;const w=((r==null?void 0:r.conditions)||[]).filter(D=>D.id!==l.id);if(w.length>0){const D={...r,conditions:w};c(D)}else c(void 0);n(!1)},N=w=>{h({...x,selectedValues:w})},C=()=>{d&&l?(h({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),i("values")):(h({id:s.v4(),field:null,selectedValues:[]}),i("fields")),m("")};return k.useEffect(()=>{t&&C()},[t,d,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:d?`Edit Filter: ${(L=x.field)==null?void 0:L.label}`:o==="fields"?"Select Field to Filter":`Select Values for ${(A=x.field)==null?void 0:A.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!d&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&o==="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(w=>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:[w.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(w.value)?`${w.value.length} values`:String(w.value)})]},w.id))})]}),o==="fields"&&!d?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:w=>m(w.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:p.map(w=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(w),children:[e.jsx(ps,{dataType:s.getDataType(w.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:w.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[w.entityName,".",w.name]})]})]},w.id))}),p.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),p.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(Hr,{field:x.field,selectedValues:x.selectedValues,onValuesChange:N,onBack:d?void 0:()=>i("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:d?e.jsx(s.Button,{variant:"destructive",onClick:j,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:C,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:f,disabled:!x.field||x.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Hr({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,c]=k.useState(""),{values:d,isLoading:o,isFetching:i}=qr({field:t,searchQuery:l,limit:500}),u=l?d.filter(h=>String(h.value).toLowerCase().includes(l.toLowerCase())):d,m=h=>{const p=n.includes(h);a(p?n.filter(b=>b!==h):[...n,h])},x=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(h=>h.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:h=>c(h.target.value),className:"pl-10"})]}),o||i?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:x}),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(h=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(h.value),children:[e.jsx(s.Checkbox,{checked:n.includes(h.value),onCheckedChange:()=>m(h.value)}),e.jsx(ms,{className:"text-sm",children:h.label})]},h.id))})]})]})}function Qr({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:c=!1,cardType:d}){var gs,js,bs,vs;const{attributes:o,listeners:i,setNodeRef:u,transform:m,transition:x,isDragging:h}=s.useSortable({id:t.id}),p=s.useEditorStore(G=>G.card),{updateLabel:b,handleAggregationChange:f,handleDateFormatChange:j,handleGranularityChange:N,handleAliasTemplateChange:C,handleValueAliasesChange:L,removeField:A,handleKpiComparisonTypeChange:w,handleKpiShowTrendlineChange:D,handleKpiTrendlineWindowChange:g,handleKpiTrendlineGranularityChange:y,handleKpiTargetValueChange:v}=ds(p),[R,S]=k.useState(!1),[F,I]=k.useState(!1),[T,M]=k.useState(null),[O,E]=k.useState(t.dateFormat||"YYYY-MM-DD"),[P,B]=k.useState(t.customFormat||""),[q,Y]=k.useState(!!t.customFormat),[z,W]=k.useState(t.granularity||"day"),[X,se]=k.useState(t.aliasTemplate||""),[te,ie]=k.useState(t.valueAliases||{}),[H,$]=k.useState((gs=t.parameters)==null?void 0:gs.filters),ae=G=>{G==="custom"?Y(!0):(Y(!1),E(G),n==="groupBy"&&j(a,G,""))},Q=G=>{B(G),n==="groupBy"&&j(a,"custom",G)},re=G=>{var je;W(G);const xe=(je=Z(G)[0])==null?void 0:je.value;xe&&!q&&(E(xe),n==="groupBy"&&j(a,xe,"")),n==="groupBy"&&N(a,G)},U=G=>{se(G),n==="metrics"&&C(a,G)},ee=G=>{ie(G),n==="metrics"&&L(a,G)},ce=G=>{b(n,a,G)},le=G=>{var he;if($(G),n==="metrics"){const xe={...t,parameters:{...t.parameters,filters:G}},je=[...((he=p.config)==null?void 0:he.metricColumns)||[]];je[a]=xe,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:je})}I(!1)},fe=()=>{A(n,a)},ue={transform:s.CSS.Transform.toString(m),transition:x},K=s.getDataType(t.dataType),_=K==="date",V=d==="kpi",Z=G=>{switch(G){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..."}]}},oe=Z(z),de=n!=="pivotBy",ne=_&&n==="groupBy"&&(!V||((js=p.config)==null?void 0:js.comparisonType)==="start_vs_end"),me=!V&&_&&n==="groupBy",pe=V&&_&&n==="groupBy",Re=V&&n==="metrics"&&((bs=p.config)==null?void 0:bs.comparisonType)==="target",Le=n==="metrics",De=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:G=>{G.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}`}),ve=()=>de?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:ce,placeholder:"Display label...",type:"text"})]}):null,J=()=>ne?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:z,onValueChange:re,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(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G,children:s.toTitleCase(G)},G))})]})]}):null,ge=()=>me?e.jsxs(e.Fragment,{children:[J(),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:q?"custom":O,onValueChange:ae,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:oe.map(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),q&&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:P,onChange:G=>{G.stopPropagation(),Q(G.target.value)},onClick:G=>G.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,Be=()=>{var G,he,xe,je,Te;return pe?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:((G=p.config)==null?void 0:G.comparisonType)||"none",onValueChange:w,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:"start_vs_end",children:"Start vs End"})]})]})]}),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:((he=p.config)==null?void 0:he.showTrendline)||!1,onCheckedChange:D})]})}),((xe=p.config)==null?void 0:xe.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:((je=p.config)==null?void 0:je.trendlineWindow)||30,onChange:Ue=>{const Bt=parseInt(Ue.target.value)||30;g(Bt)},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:((Te=p.config)==null?void 0:Te.trendlineGranularity)||"day",onValueChange:y,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},ke=()=>{var G,he;return Re?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:((G=p.config)==null?void 0:G.targetValue)!==void 0&&((he=p.config)==null?void 0:he.targetValue)!==null?String(p.config.targetValue):"",onSave:xe=>{!isNaN(Number(xe))&&xe!==null?v(Number(xe)):v(0)},placeholder:"Enter target value...",type:"text"})]}):null},Ft=()=>Le?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:G=>{f(a,G)},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"}),(H==null?void 0:H.conditions)&&H.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:H.conditions.map(G=>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(G),I(!0)},children:[e.jsxs("span",{className:"font-medium",children:[G.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(G.value)?G.value.length===1?String(G.value[0]):G.value.length<=2?G.value.join(", "):`${G.value.slice(0,2).join(", ")} +${G.value.length-2}`:String(G.value)})}),Array.isArray(G.value)&&G.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 (",G.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:G.value.map((he,xe)=>e.jsx("div",{children:String(he)},xe))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:he=>{var je;he.stopPropagation();const xe=H.conditions.filter(Te=>Te.id!==G.id);if(xe.length>0){const Te={...H,conditions:xe};le(Te)}else if($(void 0),n==="metrics"){const Te={...t,parameters:{...t.parameters,filters:void 0}},Ue=[...((je=p.config)==null?void 0:je.metricColumns)||[]];Ue[a]=Te,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:Ue})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},G.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{M(null),I(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Yr,{column:t}),c&&e.jsxs(e.Fragment,{children:[e.jsx(Gr,{aliasTemplate:X,onAliasTemplateChange:U}),e.jsx($r,{valueAliases:te,onValueAliasesChange:ee})]})]}):null,{columns:Ot=[]}=s.useColumns(),Pt=(H==null?void 0:H.conditions)&&H.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:ue,...o,...i,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 ${h?"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(ps,{dataType:K}),e.jsx(ms,{className:s.cn("w-[140px] flex-1 text-sm",Pt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((vs=H==null?void 0:H.conditions)==null?void 0:vs.length)&&!R&&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:H.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:H.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:G=>{G.stopPropagation(),S(!R)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${R?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:G=>{G.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const he=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",he),l(he)},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:G=>{G.stopPropagation(),fe()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),R&&e.jsxs("div",{className:"space-y-3",children:[De(),ve(),d==="kpi"&&J(),ge(),Be(),ke(),Ft()]})]}),F&&e.jsx(Kr,{open:F,onOpenChange:G=>{I(G),G||M(null)},availableFields:Ot,existingFilters:H,editingCondition:T,onSave:G=>{var he;if(G)le(G);else if($(void 0),n==="metrics"){const xe={...t,parameters:{...t.parameters,filters:void 0}},je=[...((he=p.config)==null?void 0:he.metricColumns)||[]];je[a]=xe,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:je})}M(null)}})]})}function Wr({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 $e({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:c=!1,activeField:d=null}){const{isOver:o,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(j=>j.card),x=s.useEditorStore(j=>j.card.type),h=n.length>0,p=k.useMemo(()=>!d||!o?!0:Ve(d,t,x).isValid,[d,o,t,x]),b=(j,N)=>{var L;!((L=m.config)!=null&&L.sortByColumns)||m.config.sortByColumns.findIndex(A=>A.id===j)===-1||u(m.id,j,{direction:N})};if(t==="sortBy"&&l===!1)return null;const f=t!=="sortBy"&&x!=="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}),f&&e.jsx(Wr,{concept:t})]}),e.jsx("div",{ref:i,className:s.cn("rounded-lg border-2 border-dashed p-1 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":o&&p,"border-red-500 bg-red-50 dark:bg-red-950":o&&!p,"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":!o&&h,"min-h-[60px] border-muted-foreground/20 bg-background":!o&&!h}),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(j=>j.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((j,N)=>{const L=j.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Qr,{field:j,zone:t,index:N,sortDirection:L,onSortDirectionChange:A=>b(j.id,A),hasPivotColumns:c,cardType:x})})},j.id)})})})})]})}const Os=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Jr=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function es({value:t,onChange:n,label:a}){const[r,l]=k.useState(!1),[c,d]=k.useState(!1),o=()=>{const i=Os.find(u=>u.value===t);return i?i.color:t.startsWith("#")?t:Os[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:o()},"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:Jr.map(i=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",o()===i?"border-gray-900":"border-transparent"),style:{backgroundColor:i},onClick:()=>{n(i),l(!1)},children:e.jsx("span",{className:"sr-only",children:i})},i))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{d(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),c&&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:()=>d(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Dt,{color:o(),onColorChange:i=>{n(i),d(!1)},onClose:()=>d(!1)})})]})]})}const Ps={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%
|
|
280
|
-
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 Xr(){var h,p,b,f,j,N,C,L,A,w,D;const t=s.useEditorStore(g=>g.card),{setCardPreferences:n}=s.useEditorActions(),a=((h=t.config)==null?void 0:h.metricColumns)||[],r=((p=t.config)==null?void 0:p.groupByColumns)||[],l=a.length===2&&r.length===0,c=a.length>=1&&r.length>0;if(!(t.type==="kpi"&&(l||c)))return null;const o=((f=(b=t.preferences)==null?void 0:b.kpiVisualOptions)==null?void 0:f.metricComparison)||{},i=g=>{var v;const y={...t.preferences,kpiVisualOptions:{...(v=t.preferences)==null?void 0:v.kpiVisualOptions,metricComparison:{...o,...g}}};n(y)},u=c||o.enabled,m=((j=t.config)==null?void 0:j.comparisonType)||"none",x=m==="previous_period"||m==="same_period_last_year"||m==="start_vs_end";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(Zt,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[l&&a.length===2&&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:g=>i({enabled:g,...g&&!o.calculationType?{calculationType:"difference"}:{}})})]}),u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const g=o.calculationType||"difference",y=Ps[g];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:y==null?void 0:y.label}),e.jsx("p",{children:y==null?void 0:y.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:y==null?void 0:y.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",y==null?void 0:y.example]})]})})()})]})]}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:g=>i({calculationType:g}),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(Ps).map(([g,y])=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:y.label},g))})]})]}),e.jsx(hs,{formatOptions:o.formatOptions||{},onFormatOptionsChange:g=>i({formatOptions:g}),showTitle:!0,title:"COMPARISON FORMAT"}),(x||l)&&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"}),l&&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||"right",onValueChange:g=>i({position:g}),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:"right",className:"text-xs",children:"Right"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:g=>i({showArrow:g})}),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:g=>i({showColor:g})}),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(es,{value:((N=o.colorConfig)==null?void 0:N.increase)||"green",onChange:g=>i({colorConfig:{...o.colorConfig,increase:g}}),label:"Primary > Secondary"}),e.jsx(es,{value:((C=o.colorConfig)==null?void 0:C.decrease)||"red",onChange:g=>i({colorConfig:{...o.colorConfig,decrease:g}}),label:"Primary < Secondary"}),e.jsx(es,{value:((L=o.colorConfig)==null?void 0:L.noChange)||"neutral",onChange:g=>i({colorConfig:{...o.colorConfig,noChange:g}}),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:g=>i({conditionalLabel:g})}),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:((A=o.conditionalLabels)==null?void 0:A.increase)??"Increase",onChange:g=>i({conditionalLabels:{...o.conditionalLabels,increase:g.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:((w=o.conditionalLabels)==null?void 0:w.decrease)??"Decrease",onChange:g=>i({conditionalLabels:{...o.conditionalLabels,decrease:g.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:((D=o.conditionalLabels)==null?void 0:D.noChange)??"No change",onChange:g=>i({conditionalLabels:{...o.conditionalLabels,noChange:g.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:"Previous Label"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:g=>i({labelName:g.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function Zr(){var l,c;const t=s.useEditorStore(d=>d.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((c=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:c.formatOptions)||{},r=d=>{var i;const o={...t.preferences,kpiVisualOptions:{...(i=t.preferences)==null?void 0:i.kpiVisualOptions,formatOptions:d}};n(o)};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(rs,{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(hs,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function el({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,activeField:l}){const c=s.useEditorStore(j=>{var N;return((N=j.card.customCardPreferences)==null?void 0:N.url)&&j.card.type==="custom"}),d=s.useEditorStore(j=>j.card),o=d==null?void 0:d.type,i=t.length>0||a.length>0,u=o!=="kpi"||a.length<=2,m=o!=="kpi",x=o!=="kpi"&&i,h=["pie","doughnut","polar","funnel","aggregateTable"].includes(o),p=m&&!h,b=()=>o==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},f=()=>o==="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:[u&&e.jsx($e,{zone:"groupBy",fields:t,label:b().label,placeholder:b().placeholder,activeField:l}),p&&e.jsx($e,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data",activeField:l}),e.jsx($e,{zone:"metrics",fields:a,label:f().label,placeholder:f().placeholder,hasPivotColumns:n.length>0,activeField:l}),x&&e.jsx($e,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:l})]})]}),!c&&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.Settings2,{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(Zr,{}),e.jsx(Xr,{}),e.jsx(Tt,{}),e.jsx(kt,{}),e.jsx(Et,{}),e.jsx(It,{})]})})]})]})}function sl({onEditJoins:t}){const n=s.useEditorStore(o=>o.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,l=(r==null?void 0:r.joins)||[];if(l.length===0)return null;const c=o=>!o||o.length===0?"No conditions":o.map(i=>{var h,p,b,f;const u=`${(h=i.source)==null?void 0:h.entityName}.${(p=i.source)==null?void 0:p.name}`,m=`${(b=i.target)==null?void 0:b.entityName}.${(f=i.target)==null?void 0:f.name}`,x=i.operator||"=";return`${u} ${x} ${m}`}).join(" AND "),d=o=>!o.joinKeyGroups||o.joinKeyGroups.length===0?"No conditions defined":o.joinKeyGroups.length===1?c(o.joinKeyGroups[0].keys):o.joinKeyGroups.map((i,u)=>({id:u,operator:i.operator,condition:c(i.keys)}));return e.jsx(s.Card,{className:"border-blue-500/30 bg-blue-50/30 dark:bg-blue-950/20",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ya,{className:"size-4 text-blue-600 dark:text-blue-400"}),e.jsx("h3",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Auto-Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:l.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:l.map((o,i)=>{const u=d(o),m=Array.isArray(u);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:o.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:o.target.name})]}),e.jsx(s.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:o.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:m?u.map(x=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:x.condition}),x.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",x.operator,")"]})]},x.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:u})})})]},o.id||i)})})})]})})]}),t&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:t,className:"h-7 gap-1 p-2 text-xs text-blue-700 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(s.SquarePen,{className:"size-3.5"})})]})})}const Bs={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(n){return console.warn(`Failed to read from localStorage (${t}):`,n),null}},setItem(t,n){if(!(typeof window>"u"))try{localStorage.setItem(t,n)}catch(a){console.warn(`Failed to write to localStorage (${t}):`,a)}}};function tl({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:c,activeField:d}){var g,y;const[o,i]=k.useState(()=>Bs.getItem("chart-selector-expanded")==="true"),[u,m]=k.useState(!1),x=s.useEditorStore(v=>v.card),h=s.useEditorStore(v=>v.actions.updateCardConfig),p=a.length>0||r.length>0||l.length>0,{data:b,autoJoinMetadata:f}=s.useDashboardCardQuery(x),j=((g=x==null?void 0:x.config)==null?void 0:g.joinPlan)||(f!=null&&f.autoResolved?f.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),N=((y=x==null?void 0:x.dataSource)==null?void 0:y.selectedEntities)||[],C=v=>{h(x.id,{...x==null?void 0:x.config,joinPlan:v}),m(!1)},L=()=>{h(x.id,{...x==null?void 0:x.config,joinPlan:void 0}),m(!1)},A=()=>{m(!1)},w=()=>{m(!0)};k.useEffect(()=>{Bs.setItem("chart-selector-expanded",String(o))},[o]);const D=()=>{i(v=>!v)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":o}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",o?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:o&&e.jsx(Vr,{selectedChart:t,onChartChange:n})}),e.jsxs("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center gap-1",children:[e.jsx(_r,{selectedChart:t,onChartChange:n}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:D,className:"h-8 w-8 p-0","aria-label":o?"Hide all charts":"Show all charts",children:o?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o?"Hide dropdown":"Show all charts"})})]})]})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsx("div",{className:s.cn("invisible flex gap-2",{visible:p||b}),children:e.jsx(is,{})})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(sl,{onEditJoins:w}),e.jsx(el,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:c,activeField:d})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(ns,{open:u,onOpenChange:m,joinPlan:j,availableDataSources:N,onSave:C,onCancel:A,onRemove:L,children:e.jsx("div",{})})]})}function al({initialFilters:t,availableFields:n}={}){const[a,r]=k.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(w=>w.card.dataSource);const{columns:l,isLoading:c}=s.useColumns(),o=n||l||[],i={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=w=>{const D=g=>{if(g.id===w){const y=o[0]||i,v=s.getDataType(y.dataType)==="date";return{...g,conditions:[...g.conditions,{id:`condition-${Date.now()}`,field:y,operator:v?"between":"=",value:v?[]:""}]}}return{...g,groups:g.groups.map(D)}};r(D(a))},m=w=>{const D=g=>{if(g.id===w){const y=o[0]||i,v=s.getDataType(y.dataType)==="date";return{...g,groups:[...g.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:y,operator:v?"between":"=",value:v?[]:""}],groups:[]}]}}return{...g,groups:g.groups.map(D)}};r(D(a))},x=(w,D)=>{const g=y=>y.id===w?{...y,conditions:y.conditions.filter(v=>v.id!==D)}:{...y,groups:y.groups.map(g)};r(g(a))},h=(w,D)=>{const g=y=>y.id===w?{...y,groups:y.groups.filter(v=>v.id!==D)}:{...y,groups:y.groups.map(g)};r(g(a))},p=(w,D,g,y)=>{if(g==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const v=R=>R.id===w?{...R,conditions:R.conditions.map(S=>S.id===D?{...S,[g]:y}:S)}:{...R,groups:R.groups.map(v)};r(v(a))},b=(w,D,g)=>{const y=v=>v.id===w?{...v,conditions:v.conditions.map(R=>R.id===D?{...R,...g}:R)}:{...v,groups:v.groups.map(y)};r(y(a))},f=(w,D)=>{const g=y=>y.id===w?{...y,logicalOperator:D}:{...y,groups:y.groups.map(g)};r(g(a))},j=(w,D)=>{const g=y=>y.id===w?{...y,negate:D}:{...y,groups:y.groups.map(g)};r(g(a))},N=(w,D,g)=>{const y=v=>v.id===w?{...v,conditions:s.arrayMove(v.conditions,D,g)}:{...v,groups:v.groups.map(y)};r(y(a))},C=(w,D,g)=>{const y=v=>v.id===w?{...v,groups:s.arrayMove(v.groups,D,g)}:{...v,groups:v.groups.map(y)};r(y(a))},L=w=>{if(!w||w.conditions.length===0&&w.groups.length===0)return"-- No filters defined";const D=y=>{let v="";typeof y.field=="object"?v=y.field.entityName?`${y.field.entityName}.${y.field.name}`:y.field.name:v=String(y.field);const R=y.operator;let S=y.value;if(y.field.dataType==="string"&&!["in","not in"].includes(y.operator))typeof S=="string"?S=`'${S}'`:Array.isArray(S)&&(S=`'${S.join(", ")}'`);else if(y.field.dataType==="date"||y.field.dataType==="datetime"||y.field.dataType==="timestamp")if(y.operator==="between"&&Array.isArray(S)&&S.length===2){const F=S[0]?`'${S[0]}'`:"NULL",I=S[1]?`'${S[1]}'`:"NULL";return`${v} BETWEEN ${F} AND ${I}`}else if((y.operator==="in"||y.operator==="not in")&&Array.isArray(S)){const F=S.map(I=>I?`'${I}'`:"NULL").join(", ");return`${v} ${R} (${F})`}else typeof S=="string"||S instanceof Date?S=`'${S}'`:Array.isArray(S)&&S.length>0&&(S=`'${S[0]}'`);else if(["in","not in"].includes(y.operator)){let F=[];Array.isArray(S)?F=S.map(I=>typeof I=="string"?`'${I}'`:String(I)):typeof S=="string"?F=S.split(",").map(I=>{const T=I.trim();return y.field.dataType==="string"?`'${T}'`:T}):typeof S=="number"&&(F=[String(S)]),S=`(${F.join(", ")})`}switch(R){case"contains":return typeof S=="string"?`${v} LIKE '%${S.replace(/'/g,"")}'`:`${v} LIKE '%${String(S)}'`;case"startsWith":return typeof S=="string"?`${v} LIKE '${S.replace(/'/g,"")}%'`:`${v} LIKE '${String(S)}%'`;case"endsWith":return typeof S=="string"?`${v} LIKE '%${S.replace(/'/g,"")}'`:`${v} LIKE '%${String(S)}'`;case"isNull":return`${v} IS NULL`;case"isNotNull":return`${v} IS NOT NULL`;default:return`${v} ${R} ${S}`}},g=y=>{const v=y.conditions.map(D),R=y.groups.map(T=>g(T)),S=[...v,...R].filter(Boolean);if(S.length===0)return"";const F=S.join(` ${y.logicalOperator} `),I=S.length>1?`(${F})`:F;return y.negate?`NOT ${I}`:I};return g(w)},A=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:o,isLoading:c,addCondition:u,addGroup:m,removeCondition:x,removeGroup:h,updateCondition:p,updateConditionFields:b,updateGroupOperator:f,updateGroupNegate:j,reorderConditions:N,reorderGroups:C,generateSQLPreview:L,hasAnyFilters:A}}function nl({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 rl=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"})}},ll=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function ol({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[c,d]=k.useState(!1),o=k.useMemo(()=>{const i={};return a.forEach(u=>{const m=ll(u);i[m]||(i[m]={}),i[m][u.entityId]||(i[m][u.entityId]=[]),i[m][u.entityId].push(u)}),i},[a]);return e.jsxs(s.Popover,{modal:!0,open:c,onOpenChange:d,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(nl,{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(o).map(([i,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"}),i]}),children:Object.entries(u).map(([m,x])=>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:[rl(x[0].entityType),e.jsx("span",{children:x[0].entityName})]}),x.map((h,p)=>e.jsxs(s.CommandItem,{value:h.id,onSelect:()=>{n(h),d(!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)===h.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:h.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:h.description&&e.jsx("span",{children:h.description})})]})]},h.id+p))]},`${i}-${m}`))},i))})]})})]})}function fs(t){var f;const n=s.useEditorStore(j=>j.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(j=>j.card.config),c=l==null?void 0:l.joinPlan,d={...t,alias:t.name,label:"value",role:"groupby"},o={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...d,role:"sortby",direction:"asc"},u={joinPlan:c,groupByColumns:[d],metricColumns:[o],sortByColumns:[i]},m=((f=n.dataSource)==null?void 0:f.connectionId)||n.connectionId,{data:x,isPending:h,error:p}=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:((x==null?void 0:x.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:h,error:p}}function il({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[c,d]=ss.useState(!1),{filterValues:o}=fs(t),i=m=>{a(n.filter(x=>x!==m))},u=m=>{n.includes(m)?a(n.filter(x=>x!==m)):a([...n,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:c,onOpenChange:d,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,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 x=o.find(h=>h.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[x==null?void 0:x.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:h=>{h.key==="Enter"&&i(m)},onMouseDown:h=>{h.preventDefault(),h.stopPropagation()},onClick:h=>{h.stopPropagation(),i(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:o.map((m,x)=>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+x))})]})]})})]})})}function cl({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:c,isPending:d,error:o}=fs(t);return d?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..."]}):o?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:c.map((i,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:i.value,children:i.label},i.value+u))})]})}function dl({value:t,operator:n,onChange:a,className:r}){var i;const{tokenProps:l}=s.useSemaphorContext(),c=(i=l==null?void 0:l.params)==null?void 0:i.timeZone,d=k.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]),o=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:d,onChange:o,timezone:c,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const ul=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ml=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],hl=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],xl=["=","!=","isNull","isNotNull"],pl=["between","isNull","isNotNull"],fl={"=":"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","not between":"Not Between"};function Vs(t){return fl[t]||s.titleCase(t)}function gl(t){switch(t){case"string":return ml;case"number":return hl;case"boolean":return xl;case"date":return pl;default:return ul}}function At({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:c,onUpdateGroupOperator:d,availableFields:o,updateConditionFields:i}){const{attributes:u,listeners:m,setNodeRef:x,transform:h,transition:p,isDragging:b}=s.useSortable({id:t.id}),{isPending:f,error:j}=fs(t.field),N={transform:s.CSS.Transform.toString(h),transition:p};return e.jsxs("div",{ref:x,style:N,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:C=>d(a,C),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(ol,{value:t.field,onValueChange:C=>{const L=C,A=s.getDataType(L.dataType)==="date";i(a,t.id,{field:L,value:"",operator:A?"between":"="})},availableFields:o,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:C=>{C==="in"||C==="not in"?i(a,t.id,{operator:C,value:[]}):C==="isNull"||C==="isNotNull"?i(a,t.id,{operator:C,value:null}):i(a,t.id,{operator:C,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Vs(t.operator):""})}),e.jsx(s.SelectContent,{children:gl(s.getDataType(t.field.dataType)).map(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C,children:Vs(C)},C))})]}),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"?f?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(il,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(C=>typeof C=="string")?t.value:[],onChange:C=>i(a,t.id,{value:C}),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:C=>i(a,t.id,{value:C.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(cl,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:C=>i(a,t.id,{value:C}),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:C=>i(a,t.id,{value:C==="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(dl,{value:t.value,operator:t.operator,onChange:C=>i(a,t.id,{value:C}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:C=>l(a,t.id,"value",C.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:()=>c(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function jl({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:c,onUpdateCondition:d,onUpdateField:o,onRemoveCondition:i,onReorderConditions:u,onReorderGroups:m,onAddCondition:x,onAddGroup:h,availableFields:p,renderFilterGroup:b,updateConditionFields:f}){const{attributes:j,listeners:N,setNodeRef:C,transform:L,transition:A,isDragging:w}=s.useSortable({id:t.id}),D={transform:s.CSS.Transform.toString(L),transition:A},g=v=>{const{active:R,over:S}=v;if(S&&R.id!==S.id){const F=t.conditions.findIndex(T=>T.id===R.id),I=t.conditions.findIndex(T=>T.id===S.id);F!==-1&&I!==-1&&u(t.id,F,I)}},y=v=>{const{active:R,over:S}=v;if(S&&R.id!==S.id&&a){const F=t.groups.findIndex(T=>T.id===R.id),I=t.groups.findIndex(T=>T.id===S.id);F!==-1&&I!==-1&&m(a,F,I)}};return e.jsxs("div",{ref:C,style:D,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${w?"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,...N,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:v=>r(t.id,v),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&&c(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:g,children:e.jsx(s.SortableContext,{items:t.conditions.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((v,R)=>e.jsx(At,{condition:v,index:R,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:d,onUpdateField:o,onRemoveCondition:i,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:f},v.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:y,children:e.jsx(s.SortableContext,{items:t.groups.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(v=>b(v,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:()=>x(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:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function bl({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:c,availableFields:d,isLoading:o,addCondition:i,addGroup:u,removeCondition:m,removeGroup:x,updateCondition:h,updateConditionFields:p,updateGroupOperator:b,updateGroupNegate:f,reorderConditions:j,reorderGroups:N,generateSQLPreview:C,hasAnyFilters:L,setCurrentFilters:A}=al({initialFilters:t,availableFields:n}),w=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[D,g]=k.useState(!1),y=(S,F,I)=>{const T=M=>M.id===S?{...M,conditions:M.conditions.map(O=>O.id===F?{...O,field:I,dataType:I.dataType}:O)}:{...M,groups:M.groups.map(T)};A(T(c))},v=(S,F=0,I)=>F===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:w,collisionDetection:s.closestCenter,onDragEnd:T=>{const{active:M,over:O}=T;if(O&&M.id!==O.id){const E=S.conditions.findIndex(B=>B.id===M.id),P=S.conditions.findIndex(B=>B.id===O.id);E!==-1&&P!==-1&&j(S.id,E,P)}},children:e.jsx(s.SortableContext,{items:S.conditions.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:S.conditions.map((T,M)=>e.jsx(At,{condition:T,index:M,groupId:S.id,groupLogicalOperator:S.logicalOperator,onUpdateCondition:h,onUpdateField:y,onRemoveCondition:m,onUpdateGroupOperator:b,availableFields:d,updateConditionFields:p},T.id))})}),e.jsx(s.DndContext,{sensors:w,collisionDetection:s.closestCenter,onDragEnd:T=>{const{active:M,over:O}=T;if(O&&M.id!==O.id){const E=S.groups.findIndex(B=>B.id===M.id),P=S.groups.findIndex(B=>B.id===O.id);E!==-1&&P!==-1&&N(S.id,E,P)}},children:e.jsx(s.SortableContext,{items:S.groups.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:S.groups.map(T=>v(T,F+1,S.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:()=>i(S.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(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},S.id):e.jsx(jl,{group:S,depth:F,parentGroupId:I,onUpdateGroupOperator:b,onUpdateGroupNegate:f,onRemoveGroup:x,onUpdateCondition:h,onUpdateField:y,onRemoveCondition:m,onReorderConditions:j,onReorderGroups:N,onAddCondition:i,onAddGroup:u,availableFields:d,renderFilterGroup:v,updateConditionFields:p},S.id),R=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:[o?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..."})]}):v(c),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:S=>g(S)}),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)"})]})}),L&&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:C(c)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),R>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(L?c:null),children:"Apply Filters"})]})]})}function vl({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:c,onOpenChange:d}){const o=u=>{a(t,u),d(!1)},i=()=>{r(t),d(!1)};return e.jsxs(s.Dialog,{modal:!1,open:c,onOpenChange:d,children:[c&&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(bl,{filters:n,availableFields:l,onSave:o,onCancel:()=>d(!1),onClearAll:i})]})]})}function yl({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var j,N;const[l,c]=k.useState(null),d=s.useEditorStore(C=>C.card),o=s.useEditorStore(C=>C.actions.updateCardConfig),i=(j=d==null?void 0:d.config)==null?void 0:j.joinPlan,u=(N=d==null?void 0:d.dataSource)==null?void 0:N.semanticDomainId,{data:m}=cs(u),x=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],h=k.useCallback(C=>C.startsWith("card-")?null:C.startsWith("source-")||n.find(L=>L.id===C)?"source":a("groupBy").find(L=>L.id===C)?"groupBy":a("metrics").find(L=>L.id===C)?"metrics":a("pivotBy").find(L=>L.id===C)?"pivotBy":a("sortBy").find(L=>L.id===C)?"sortBy":null,[n,a]),p=k.useCallback(C=>{c(C.active.id)},[]),b=k.useCallback(C=>{var v;const{active:L,over:A}=C;if(!A||!t){c(null);return}const w=L.id,D=A.id,g=h(w),y=h(D)||D;if(y==="sortBy"){if(g==="source"){const R=n.find(F=>F.id===w);if(!R){c(null);return}if(!(a("groupBy").some(F=>F.name===R.name&&F.qualifiedEntityName===R.qualifiedEntityName)||a("metrics").some(F=>F.name===R.name&&F.qualifiedEntityName===R.qualifiedEntityName))){c(null);return}}else if(g==="pivotBy"){c(null);return}else if(g!=="groupBy"&&g!=="metrics"&&g!=="sortBy"){c(null);return}}if(g==="source"&&y==="sortBy"){const R=[...n].find(T=>T.id===w);if(!R){c(null);return}const S=a("sortBy");if(s.fieldAlreadyExists(R,S)){c(null);return}const F=Ve(R,"sortBy",d.type);if(!F.isValid){s.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),c(null);return}const I=s.getNewField(R,"sortBy",S);c(null),r("sortBy",[...S,I]);return}if(g==="source"&&y!=="source"&&y!=="sortBy"){const R=[...n].find(O=>O.id===w);if(!R){c(null);return}const S=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(S.length>0){const O=S[0].qualifiedEntityName;if(!O){c(null);return}if(O!==R.qualifiedEntityName&&R.qualifiedEntityName)if(u&&(m!=null&&m.joinabilityMap)){if(s.calculateFieldState(R,{joinabilityMap:m.joinabilityMap,selectedFields:S,baseEntityName:(v=i==null?void 0:i.baseEntity)==null?void 0:v.name}).state==="unreachable"){s.showJoinRequiredNotification(),c(null);return}}else{if(!i){s.showJoinRequiredNotification(),c(null);return}if(!s.areEntitiesJoined(O,R.qualifiedEntityName,i)){s.showJoinRequiredNotification(),c(null);return}}}const F=a(y);if(s.fieldAlreadyExists(R,F)){c(null);return}const I=Ve(R,y,d.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),c(null);return}const T=s.getNewField(R,y,F),M=[...F,T];c(null),r(y,M),y==="metrics"&&t&&as(d.type,d.config,o,t,M);return}if(g&&y&&g!=="source"&&y!=="source"&&g!==y){const R=a(g),S=a(y),F=R.find(E=>E.id===w);if(!F){c(null);return}const I=Ve(F,y,d.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),c(null);return}const T=s.getNewField(F,y,S);if(c(null),y==="sortBy"){s.fieldAlreadyExists(F,S)||r(y,[...S,T]);return}const M=R.filter(E=>E.id!==w),O=[...S,T];r(g,M),r(y,O),y==="metrics"&&t&&as(d.type,d.config,o,t,O);return}if(g&&y&&g===y&&g!=="source"){const R=a(g),S=R.findIndex(I=>I.id===w),F=R.findIndex(I=>I.id===D);if(S!==F){const I=s.arrayMove(R,S,F);r(g,I)}}c(null)},[t,n,a,r,h,i,u,m,d.type,o,d.config]),f=l?x.find(C=>C.id===l):null;return{activeId:l,activeField:f,handleDragStart:p,handleDragEnd:b}}function Nl({activeView:t,onViewChange:n}){const a=s.useEditorStore(d=>d.card),{config:r}=k.useContext(s.SemaphorContext).tokenProps,l=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:c}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:d=>n(d),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",c&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:c?"Error":"Info"})]})})}const Cl=[{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 Sl(){var i,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=k.useState(!1),[l,c]=k.useState(""),d=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},o=m=>{const x=m.target.value;c(x),x&&!isNaN(parseInt(x))&&n(t.id,parseInt(x))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:o,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(i=t.config)==null?void 0:i.rowLimit)==null?void 0:u.toString())||"100",onValueChange:d,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:Cl.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function wl({isOpen:t,onClose:n}){const a=Ws(n,{enabled:t}),r=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.url)||""}),l=s.useEditorStore(m=>m.card),c=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.pluginChartType)||""}),d=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.settings)||{}}),{data:o}=s.useDashboardCardQuery(l),{getCard:i}=s.useCustomVisual(r),u=k.useMemo(()=>!r||r.trim()===""?null:i("Chart Settings"),[i,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(k.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(o==null?void 0:o.records)||[],chartType:c,settings:d})})})]})})}function Dl({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:l,activeCard:c,columns:d,columnsLoading:o,columnsError:i}){var H,$,ae;const u=s.useEditorStore(Q=>Q.card),m=s.useDashboardStore(Q=>Q.filterValues);m!=null&&m.length;const{updateCardConfig:x,setCard:h,updateCardInFrame:p,setCardId:b,setShowAIDialog:f}=s.useEditorActions(),{updateCardId:j}=s.useDashboardActions(),[N,C]=k.useState(null),L=s.useEditorStore(Q=>Q.showAIDialog),A=s.useDashboardStore(Q=>Q.isVisualEditing),[w,D]=k.useState(!1),[g,y]=k.useState(!1),[v,R]=k.useState(null),{isConsoleMode:S}=s.useDashboardPreferences(),{config:F}=k.useContext(s.SemaphorContext).tokenProps,I=(F==null?void 0:F.showInfoTab)!==!1,T=s.useEditorStore(Q=>{var re;return((re=Q.card.customCardPreferences)==null?void 0:re.url)&&Q.card.type==="custom"}),{data:M,errorMessage:O,isLoading:E,isFetching:P,errorSql:B,pagination:q,refetch:Y}=s.useDashboardCardQuery(c),[z,W]=k.useState(!1);k.useEffect(()=>{P||W(!1)},[P]);const X=(Q,re)=>{const U={...c,paginationConfig:{page:Q+1,pageSize:re}};h(U),p(U)};function se(){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(u.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(m||{},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 (",d.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:o?"Loading...":i?"Error loading columns":JSON.stringify(d.slice(0,5),null,2)})]})]})]})}const te=Q=>{if(!u.config)return;if(!Q.length){x(u.id,{...u.config,sortByColumns:[]});return}const re=u.config,U=Q.map(({id:ee,desc:ce})=>{var K,_;const le=(K=re.metricColumns)==null?void 0:K.find(V=>V.label===ee),fe=(_=re.groupByColumns)==null?void 0:_.find(V=>V.label===ee),ue=le||fe;return ue?{id:s.getFieldId("sortBy",ue),name:ue.name,dataType:ue.dataType,label:ue.label,qualifiedEntityName:ue.qualifiedEntityName,entityId:ue.entityId,entityName:ue.entityName,entityType:ue.entityType,role:"sortby",direction:ce?"desc":"asc"}:null}).filter(ee=>ee!==null);x(u.id,{...re,sortByColumns:U})},ie=k.useMemo(()=>{var Q,re;return(re=(Q=u.config)==null?void 0:Q.sortByColumns)==null?void 0:re.map(U=>({id:U.label,desc:U.direction==="desc"}))},[(H=u.config)==null?void 0:H.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":L&&A}),children:[a&&se(),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"&&L&&e.jsx(bt,{variant:"outline"}),e.jsx(Nl,{activeView:t,onViewChange:n}),e.jsx(s.FilterInfo,{cardId:c.id,cardFilters:($=c.config)==null?void 0:$.filters,cardFilterCount:s.getFilterCount(((ae=c.config)==null?void 0:ae.filters)||null),onFiltersClick:l}),e.jsx("div",{className:"ml-2",children:e.jsx(Sl,{})}),L&&e.jsx(is,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:E||P,onClick:()=>{W(!0),Y()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":z})})}),t==="chart"&&e.jsx(vt,{}),!L&&e.jsx(s.IconButton,{onClick:()=>f(!L),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!w&&T&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>D(!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(yt,{})}),t==="table"&&(M==null?void 0:M.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:(M==null?void 0:M.records)||[],paginationMetadata:q,onPaginationChange:X,isLoading:E||P,onSortChange:te,sortState:ie})}),t==="info"&&I&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[S&&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:u.id,onSave:Q=>{const re=s.sanitizeCardId(Q);if(!re){C("Card ID cannot be empty");return}const U=j(u.id,re);if(U.success){b(re);const ee={...u,id:re};h(ee),p(ee),C(null),s.ue.success("Card ID updated successfully")}else C(U.error||"Failed to update Card ID"),s.ue.error(U.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:u.id,className:"h-5 w-5"})]}),N&&e.jsx("p",{className:"text-xs text-destructive",children:N})]}),O||B?e.jsx(ht,{error:O,errorSql:B,onSendFeedback:()=>{const Q=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:c.dataSource,dashboardFilters:m,errorMessage:O,errorSql:B,generatedSql:M==null?void 0:M.sql});R(Q),y(!0)}}):e.jsxs(e.Fragment,{children:[(M==null?void 0:M.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(xt,{sql:M==null?void 0:M.sql,error:O,errorSql:B})]})]})})]}),e.jsx(wl,{isOpen:w,onClose:()=>D(!1)}),v&&e.jsx(s.FeedbackDialog,{open:g,onOpenChange:y,feedbackData:v})]})]})}function Tl({activeField:t}){const[n,a]=k.useState(!0);return k.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(ps,{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 kl=()=>{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 El(){var B,q;const[t,n]=k.useState("chart"),[a,r]=k.useState(!1),[l,c]=k.useState(!1),[d,o]=k.useState(!0),i=s.useEditorStore(Y=>Y.showAIDialog),u=s.useDashboardStore(Y=>Y.isVisualEditing),{setCardType:m}=s.useEditorActions(),x=s.useEditorStore(Y=>Y.card.type);k.useEffect(()=>kl(),[]);const h=Y=>{m(Y)},p=s.useEditorStore(Y=>Y.frame),b=s.useEditorStore(Y=>Y.card);s.useEditorStore(Y=>Y.activeTabCardId),s.useEditorStore(Y=>Y.actions.getAvailableFields);const{addCard:f,removeCard:j,updateCard:N,setActiveCard:C,updateFilters:L}=s.useEditorActions(),{columns:A=[],isLoading:w,error:D}=s.useColumns(),g=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),y=b,{getFieldsForContainer:v,setFieldsForContainer:R}=ds(y),{activeField:S,handleDragStart:F,handleDragEnd:I}=yl({activeCardId:p.activeCardId,sourceFields:A,getFieldsForContainer:v,setFieldsForContainer:R}),T=(Y,z)=>{z&&L(Y,z)},M=Y=>{var z;N(Y,{config:{...(z=p.cards.find(W=>W.id===Y))==null?void 0:z.config,filters:void 0}})},O=A,E=Y=>{if(!Y)return 0;let z=Y.conditions.length;return Y.groups.forEach(W=>{z+=E(W)}),z},P=E(((B=y==null?void 0:y.config)==null?void 0:B.filters)||null);return e.jsxs(s.DndContext,{sensors:g,collisionDetection:s.closestCenter,onDragStart:F,onDragEnd:I,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(mt,{isVisible:d,onToggleVisibility:()=>o(!d)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!i&&e.jsx(tl,{selectedChart:x,onChartChange:h,groupByFields:v("groupBy"),pivotByFields:v("pivotBy"),metricsFields:v("metrics"),sortByFields:v("sortBy"),activeField:S}),e.jsx(Dl,{selectedChart:x,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:()=>c(!0),filterCount:P,activeCard:y,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:A,columnsLoading:w,columnsError:D,getFieldsForContainer:v,cards:p.cards,activeCardId:p.activeCardId,addCard:f,setActiveCard:C})]}),!d&&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:()=>o(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),y&&e.jsx(vl,{cardId:y.id,filters:((q=y.config)==null?void 0:q.filters)||null,onFiltersChange:T,onClearFilters:M,availableFields:O,isOpen:l,onOpenChange:c}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Tl,{activeField:S||null})})]})}function Il({authToken:t,onSave:n,onClose:a}){const r=k.useRef(null),l=s.useEditorStore(D=>D.showAIDialog),c=s.useEditorStore(D=>D.isDevMode),d=s.useAssistantLayoutStore(D=>D.setFullscreen),o=s.useAssistantLayoutStore(D=>D.setPanelOpen),i=s.useAssistantLayoutStore(D=>D.setContainer),u=s.useAssistantPanel("editor"),m=s.useFullscreenAssistant(),x=s.useAssistantContainer("editor"),h=m==="editor",p=k.useCallback(D=>{i("editor",D)},[i]),{setAuthToken:b}=s.useDashboardActions(),{setShowAIDialog:f,setOnSave:j,setOnClose:N}=s.useEditorActions(),{setActiveAssistantType:C}=s.useAIActions();k.useEffect(()=>{n&&j(n),a&&N(a)},[n,j,a,N]),k.useEffect(()=>{t&&t.accessToken&&b(t)},[t,b]),k.useEffect(()=>{var D,g;l?((D=r.current)==null||D.resize(40),o("editor",!0),C("editor")):((g=r.current)==null||g.resize(0),o("editor",!1),m==="editor"&&d(null),C(null))},[l,o,C,d,m]);function L(D){D<1?(f(!1),o("editor",!1),m==="editor"&&d(null),C(null)):(l||(f(!0),C("editor")),u.isOpen||o("editor",!0))}function A(){return e.jsxs(e.Fragment,{children:[e.jsx(mt,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Lr,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:L,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Rs,{isFullscreen:h,onFullscreenChange:D=>d(D?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!h&&"pointer-events-none")})]})]})}function w(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:s.cn("flex grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(El,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:L,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Rs,{isFullscreen:h,onFullscreenChange:D=>d(D?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!h&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:c?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:A()}):w()})}function Al(){s.useDashboardStore(d=>d.selectedCardId);const t=s.useDashboardStore(d=>d.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(d=>d.actions),a=s.useDashboardStore(d=>d.isVisualEditing),r=s.useDashboardStore(d=>d.actions.updateFrame);function l(d){t&&(r(t,d),n(!1))}function c(){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(Il,{onSave:l,onClose:c})})}function Ml(){ut();const t=s.useDashboardStore(i=>i.selectedSheetId),n=s.useDashboardStore(i=>i.selectedFrameId),a=s.useDashboardStore(i=>i.dashboard),r=s.useDashboardStore(i=>i.actions.getSelectedFrame),{setSelectedFrameId:l}=s.useDashboardActions(),{setCard:c}=s.useEditorActions(),d=s.useEditorStore(i=>i.card.dataSource);return k.useEffect(()=>{var u,m;let i=r();if(!i){const x=(u=a==null?void 0:a.sheets)==null?void 0:u.find(p=>p.id===t),h=(m=x==null?void 0:x.frames)==null?void 0:m[0];h&&(l(h.id),i=h)}if(i){const x=i.cards.find(h=>h.id===i.activeCardId);x&&c(x)}},[r,t,n,a,l,c]),{hasEntities:!!(d!=null&&d.selectedEntities&&d.selectedEntities.length>0)}}function Rl(){const t=s.useDashboardStore(a=>a.actions.setShowFilters),{hasEntities:n}=Ml();return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[e.jsx(s.Label,{className:"px-2 text-base",children:"Dashboard Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),!n&&e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),e.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),n&&e.jsx("div",{className:"flex grow",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(dt,{context:"filter"})})})})]})}function Ll(){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 Fl(){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(Ll,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Rl,{})})]})}function Ol(){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 Mt(){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 Pl=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 Bl({visual:t,isDeleting:n,isDuplicating:a,onAddVisual:r,onOpenVisual:l,onEditDetails:c,onDeleteClick:d,onDuplicateVisual:o,onShareVisual:i,formatDate:u}){var w,D,g,y;const{selectVisual:m}=s.useManagementActions(),x=s.useIsVisualSelected(t.id),h=Pl(t.id),{isConsoleMode:p}=s.useDashboardPreferences(),b=k.useRef(null),[f,j]=k.useState(!1),[N,C]=k.useState(!1);k.useEffect(()=>{a?(j(!0),C(!0)):N&&(j(!1),C(!1))},[a,N]),k.useEffect(()=>{h&&b.current&&b.current.scrollIntoView({behavior:"smooth",block:"center"})},[h]);const L=()=>e.jsx(Qe,{className:"h-4 w-4"}),A=()=>{m(t),l==null||l(t)};return e.jsx(s.Card,{ref:b,className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",h?"border-purple-500":x&&"border-primary"),onClick:A,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:L()}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",title:t.title||"Untitled Visual",children:t.title||"Untitled Visual"}),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("p",{className:"text-xs text-muted-foreground line-clamp-2",title:t.description||"No description",children:(w=t.description)!=null&&w.trim()?t.description:"No description"})]}),e.jsxs("div",{className:s.cn("invisible ml-2 flex flex-shrink-0 items-center gap-1 transition-opacity duration-150 group-hover:visible",x&&"visible"),onClick:v=>v.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:v=>{v.stopPropagation(),r(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),t.ownership.isOwner&&e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:v=>{v.stopPropagation(),c==null||c(t)},title:"Edit details",children:e.jsx(Ye,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:f,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:v=>{v.stopPropagation(),r(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),l==null||l(t)},children:[e.jsx(Xt,{className:"mr-2 h-3 w-3"}),"Open"]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.preventDefault(),v.stopPropagation(),o(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:v=>{v.stopPropagation(),c==null||c(t)},children:[e.jsx(Ye,{className:"mr-2 h-3 w-3"}),"Edit details"]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),i(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.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:[(((D=t.ownership.createdBy)==null?void 0:D.type)==="tenant"||((g=t.ownership.createdBy)==null?void 0:g.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:((y=t.ownership.createdBy)==null?void 0:y.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:u(t.lastModified)})]})]})]})]})]})]})},t.id)}function Rt({open:t,resourceLabel:n,initialTitle:a,initialDescription:r="",onClose:l,onSave:c,isSaving:d=!1}){const[o,i]=k.useState(a),[u,m]=k.useState(r??"");k.useEffect(()=>{t&&(i(a),m(r??""))},[t,a,r]);const x=h=>{h.preventDefault();const p=o.trim();p&&c({title:p,description:u.trim()})};return e.jsx(s.Dialog,{open:t,onOpenChange:h=>h?null:l(),children:e.jsx(s.DialogContent,{className:"sm:max-w-md",children:e.jsxs("form",{onSubmit:x,className:"space-y-4",children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{children:["Edit ",n]}),e.jsxs(s.DialogDescription,{children:["Update the title and description for this ",n.toLowerCase(),"."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"resource-title",children:"Title"}),e.jsx(s.Input,{id:"resource-title",value:o,onChange:h=>i(h.target.value),placeholder:`Enter ${n.toLowerCase()} title`,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"resource-description",children:"Description"}),e.jsx(s.Textarea,{id:"resource-description",value:u,onChange:h=>m(h.target.value),placeholder:`Enter ${n.toLowerCase()} description (optional)`,rows:3})]}),e.jsxs(s.DialogFooter,{className:"mt-6 flex justify-end gap-2 sm:justify-end",children:[e.jsx(s.Button,{type:"button",variant:"outline",onClick:l,disabled:d,children:"Cancel"}),e.jsx(s.Button,{type:"submit",disabled:d||!o.trim(),children:d?"Saving...":"Save changes"})]})]})})})}function Vl({open:t,onOpenChange:n,onSubmit:a,isCreating:r}){const[l,c]=k.useState(""),[d,o]=k.useState("");k.useEffect(()=>{t||(c(""),o(""))},[t]);const i=()=>{l.trim()&&a({title:l,description:d})},u=m=>{n(m)};return e.jsx(s.Dialog,{open:t,onOpenChange:u,children:e.jsxs(s.DialogContent,{children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create New Visual"}),e.jsx(s.DialogDescription,{children:"Add a new visual to your library. You can configure it after creation."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",children:"Visual Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:m=>c(m.target.value),disabled:r,onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),i())}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:d,onChange:m=>o(m.target.value),disabled:r})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>u(!1),disabled:r,children:"Cancel"}),e.jsx(s.Button,{onClick:i,disabled:!l.trim()||r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Visual"})]})]})})}function zl(){const[t,n]=k.useState(""),[a,r]=k.useState(!1),[l,c]=k.useState(!1),[d,o]=k.useState(null),[i,u]=k.useState(!1),[m,x]=k.useState(null),[h,p]=k.useState(null),[b,f]=k.useState(null),{selectVisual:j}=s.useManagementActions(),{handleEditLibraryVisual:N,handleAddLibraryVisual:C}=Ae(),{resources:L,isLoading:A,isError:w,createResource:D,updateResource:g,deleteResource:y,duplicateResource:v,isCreating:R,isDeleting:S}=s.useVisualManagement(()=>{u(!1),x(null)},$=>{r(!1),$&&(j($),N($))});s.useCurrentUserInfo();const F=L.filter($=>{var ae,Q;return((ae=$==null?void 0:$.title)==null?void 0:ae.toLowerCase().includes(t.toLowerCase()))||((Q=$==null?void 0:$.description)==null?void 0:Q.toLowerCase().includes(t.toLowerCase()))}),I=$=>new Date($).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),T=$=>{D({title:$.title,description:$.description,isPrivate:!1})},M=$=>{x($),u(!0)},O=()=>{m&&y(m.id)},{startUpdating:E,stopUpdating:P,isUpdating:B}=s.useResourceUpdateState(),q=($,ae,Q)=>{var ce;const re=Object.fromEntries(Object.entries(ae).filter(([,le])=>le!==void 0));if(Object.keys(re).length===0){(ce=Q==null?void 0:Q.onSuccess)==null||ce.call(Q);return}const U=Object.keys(re),ee=U.length===1?U[0]:void 0;E($,ee),g({resourceId:$,data:re},{onSuccess:()=>{var le;P($,ee),(le=Q==null?void 0:Q.onSuccess)==null||le.call(Q)},onError:()=>{var le;P($,ee),(le=Q==null?void 0:Q.onError)==null||le.call(Q)}})},Y=$=>{p($),v($,{onSettled:()=>p(null)})},z=$=>{N($)},W=$=>{C($)},X=$=>{const ae=L.find(Q=>Q.id===$);ae&&g({resourceId:$,data:{isPrivate:!ae.isPrivate}})},se=$=>{o($),c(!0)},te=$=>{f($)},ie=()=>{f(null)},H=({title:$,description:ae})=>{if(!b)return;const Q={};$!==b.title&&(Q.title=$),(b.description||"")!==ae&&(Q.description=ae),q(b.id,Q,{onSuccess:()=>{f(null)}})};return A?e.jsx(Mt,{}):w?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:"relative flex h-full flex-1 flex-col gap-4",children:[L&&L.length>5&&e.jsx("div",{className:"space-y-2",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:$=>n($.target.value),className:"h-9"})}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-3 overflow-y-auto",children:F.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(Qe,{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"]})]}):F.map($=>e.jsx(Bl,{visual:$,onAddVisual:W,onOpenVisual:z,onEditDetails:te,onDeleteClick:M,onDuplicateVisual:Y,onTogglePrivacy:X,onShareVisual:se,isDeleting:S,isDuplicating:h===$.id,formatDate:I},$.id))})}),l&&d&&e.jsx(We,{resource:d,resourceType:s.ResourceType.VISUAL,onClose:()=>{c(!1),o(null)}}),b&&e.jsx(Rt,{open:!!b,resourceLabel:"Visual",initialTitle:b.title||"",initialDescription:b.description||"",onClose:ie,onSave:H,isSaving:B(b.id)}),e.jsx(s.AlertDialog,{open:i,onOpenChange:$=>{!$&&S||(u($),$||x(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 "',m==null?void 0:m.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:S,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:$=>{$.preventDefault(),$.stopPropagation(),O()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:S,children:[S?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"}),S?"Deleting...":"Delete"]})]})]})}),e.jsx(Vl,{open:a,onOpenChange:r,onSubmit:T,isCreating:R}),e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>r(!0),"aria-label":"Create visual",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function Ul({dashboard:t,isDeleting:n,isDuplicating:a,onLoadDashboard:r,onEditDetails:l,onDeleteClick:c,onDuplicateDashboard:d,onShareDashboard:o,formatDate:i,onDashboardItemClick:u}){var y,v,R,S,F;const{selectDashboard:m}=s.useManagementActions(),x=s.useIsDashboardSelected(t.id),{isConsoleMode:h}=s.useDashboardPreferences(),{currentUser:p,isLoading:b,isError:f}=s.useCurrentUserInfo(),j=!f&&(p==null?void 0:p.type)==="tenant"&&((y=p==null?void 0:p.role)==null?void 0:y.toUpperCase())==="VIEWER",N=b||j,[C,L]=k.useState(!1),[A,w]=k.useState(!1);k.useEffect(()=>{a?(L(!0),w(!0)):A&&(L(!1),w(!1))},[a,A]);const D=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),g=()=>{m(t),r(t.id),u==null||u(t.id)};return e.jsx(s.Card,{className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",x&&"border-primary"),onClick:g,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:D()}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",title:t.title||"Untitled Dashboard",children:t.title||"Untitled Dashboard"}),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("p",{className:"text-xs text-muted-foreground line-clamp-2",title:t.description||"No description",children:(v=t.description)!=null&&v.trim()?t.description:"No description"})]}),e.jsxs("div",{className:"invisible ml-2 flex flex-shrink-0 items-center gap-1 transition-opacity duration-150 group-hover:visible",onClick:I=>I.stopPropagation(),children:[t.permissions.canEdit&&!N&&e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:I=>{I.stopPropagation(),l==null||l(t)},title:"Edit details",children:e.jsx(Ye,{className:"h-3 w-3"})}),!N&&e.jsxs(s.DropdownMenu,{modal:!1,open:C,onOpenChange:L,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:I=>{I.preventDefault(),I.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.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),l==null||l(t)},children:[e.jsx(Ye,{className:"mr-2 h-3 w-3"}),"Edit details"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),o(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:I=>{I.stopPropagation(),c(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:[(((R=t.ownership.createdBy)==null?void 0:R.type)==="tenant"||((S=t.ownership.createdBy)==null?void 0:S.type)==="organization"&&h)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((F=t.ownership.createdBy)==null?void 0:F.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:i(t.lastModified)})]})]})]})]})]})]})},t.id)}function _l({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 Gl(t){const{onLoadDashboard:n,onEditDashboard:a,onDashboardItemClick:r}=t,[l,c]=k.useState(""),[d,o]=k.useState(!1),[i,u]=k.useState(!1),[m,x]=k.useState(null),[h,p]=k.useState(!1),[b,f]=k.useState(null),[j,N]=k.useState(null),[C,L]=k.useState(null),A=s.useManagementStore(K=>K.lastSelectedDashboard),w=s.useManagementStore(K=>K.selectedDashboard),D=s.useManagementStore(K=>K.actions.selectDashboard),g=s.useManagementStore(K=>K.actions.clearSelectedDashboard),{tokenProps:y,id:v}=s.useSemaphorContext(),{permissions:R}=s.useRoleAwareDisplayPreferences(),{onCreateSuccess:S}=s.useDashboardCreation({onDashboardSelect:r}),{resources:F,isLoading:I,isError:T,createResource:M,updateResource:O,deleteResource:E,duplicateResource:P,isCreating:B,isDeleting:q,refetch:Y}=s.useDashboardManagement(()=>{p(!1);const K=b==null?void 0:b.id;f(null),(w==null?void 0:w.id)===K&&(!(y!=null&&y.dashboard_id)&&!v?g():A&&A.id!==K&&D(A))},K=>{o(!1),S(K,Y)}),{currentUser:z}=s.useCurrentUserInfo(),W=F.filter(K=>{var _,V;return((_=K==null?void 0:K.title)==null?void 0:_.toLowerCase().includes(l.toLowerCase()))||((V=K==null?void 0:K.description)==null?void 0:V.toLowerCase().includes(l.toLowerCase()))}),X=K=>new Date(K).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),se=K=>{M({title:K.title,description:K.description,isPrivate:!1})},te=K=>{n==null||n(K)},ie=K=>{f(K),p(!0)},H=()=>{b&&E(b.id)},$=K=>{N(K),P(K,{onSettled:()=>N(null)})},{startUpdating:ae,stopUpdating:Q,isUpdating:re}=s.useResourceUpdateState(),U=(K,_,V)=>{var ne;const Z=Object.fromEntries(Object.entries(_).filter(([,me])=>me!==void 0));if(Object.keys(Z).length===0){(ne=V==null?void 0:V.onSuccess)==null||ne.call(V);return}const oe=Object.keys(Z),de=oe.length===1?oe[0]:void 0;ae(K,de),O({resourceId:K,data:Z},{onSuccess:()=>{var me;Q(K,de),(me=V==null?void 0:V.onSuccess)==null||me.call(V)},onError:()=>{var me;Q(K,de),(me=V==null?void 0:V.onError)==null||me.call(V)}})},ee=K=>{const _=F.find(V=>V.id===K);_&&O({resourceId:K,data:{isPrivate:!_.isPrivate}})},ce=K=>{x(K),z==null||z.type,u(!0)},le=K=>{a==null||a(K.id),L(K)},fe=()=>{L(null)},ue=({title:K,description:_})=>{if(!C)return;const V={};K!==C.title&&(V.title=K),(C.description||"")!==_&&(V.description=_),U(C.id,V,{onSuccess:()=>{L(null)}})};return I?e.jsx(Mt,{}):T?e.jsx(_l,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[F&&F.length>5&&e.jsx("div",{className:"space-y-2",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:l,onChange:K=>c(K.target.value),className:"h-9"})}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-3 overflow-y-auto",children:W.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:l?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:l?"Try adjusting your search":R.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),R.canCreateDashboards&&!l&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>o(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Dashboard"]})]}):W.map(K=>e.jsx(Ul,{dashboard:K,isDeleting:q,isDuplicating:j===K.id,onLoadDashboard:te,onEditDetails:le,onDeleteClick:ie,onDuplicateDashboard:$,onTogglePrivacy:ee,onShareDashboard:ce,formatDate:X,onDashboardItemClick:r},K.id))})}),i&&m&&e.jsx(We,{resource:m,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{u(!1),x(null)}}),e.jsx(s.AlertDialog,{open:h,onOpenChange:K=>{!K&&q||(p(K),K||f(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 "',b==null?void 0:b.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:q,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:K=>{K.preventDefault(),K.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:q,children:[q?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"}),q?"Deleting...":"Delete"]})]})]})}),C&&e.jsx(Rt,{open:!!C,resourceLabel:"Dashboard",initialTitle:C.title||"",initialDescription:C.description||"",onClose:fe,onSave:ue,isSaving:re(C.id)}),e.jsx(s.CreateDashboardDialog,{open:d,onOpenChange:o,onSubmit:se,isCreating:B}),R.canCreateDashboards&&e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>o(!0),"aria-label":"Create dashboard",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function Lt({isOpen:t,onClose:n,className:a,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(w=>w.dashboard);const{setDashboard:c,addSheet:d}=s.useDashboardStore(w=>w.actions),{currentUser:o}=s.useCurrentUserInfo(),i=o,{permissions:u}=s.useRoleAwareDisplayPreferences(),x=s.useSelectedDashboard()&&u.canAccessVisuals,h="dashboards",[p,b]=xs("resource-management-active-tab",h),f=x?p:"dashboards",j=l==="overlay",N=Ws(n,{enabled:t&&j}),C=s.cn("flex h-full flex-col border-r bg-background",j?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),L=w=>{},A=w=>{console.log("Editing dashboard:",w)};return e.jsx(s.TooltipProvider,{children:(!j||t)&&e.jsxs("div",{ref:N,className:C,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:i&&e.jsxs(e.Fragment,{children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"flex h-8 w-8 cursor-default items-center justify-center rounded-full bg-primary/10",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:i.name.charAt(0).toUpperCase()})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"ml-2 max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:i.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.email}),i.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(i.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",i.id]})]})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"text-sm font-medium text-foreground",children:i.name})})]})}),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(ua,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:f,onValueChange:x?b:void 0,className:"flex h-9 grow flex-col",children:[x&&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(s.TabsContent,{value:"dashboards",className:"flex-1 px-4 py-4",children:e.jsx(Gl,{onLoadDashboard:L,onEditDashboard:A,onDashboardItemClick:r})}),x&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 px-4 py-4",children:e.jsx(zl,{})})]})})]})})}function $l({showControls:t=!1,showFooter:n=!0,...a}){const r=s.useDashboardStore(h=>h.isDashboardPanelOpen);s.useDashboardStore(h=>h.isVisualEditing);const l=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),c=20,d=20,o=30,i=r,u=k.useRef(null),m=k.useRef(null);k.useEffect(()=>{u.current&&m.current&&(r?(u.current.resize(c),m.current.resize(100-c)):(u.current.resize(0),m.current.resize(100)))},[r]);const{preferences:x}=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:x,children:[e.jsx(Ol,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(vn,{}),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]":i}),defaultSize:i?c:0,minSize:i?d:0,maxSize:i?o:0,children:e.jsx(Lt,{isOpen:r,onClose:()=>l(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{withHandle:i,className:s.cn("w-1",{"w-0":!i})}),e.jsx(s.ResizablePanel,{ref:m,className:"flex min-w-0 flex-1",defaultSize:i?100-c:100,minSize:i?40:100,children:e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(Al,{}),e.jsx(Fl,{})]})})]})]})]})})]})})}exports.AdvancedModeToggle=lt;exports.DashboardPlus=$l;exports.ResourceManagementPanel=Lt;exports.ScheduleDashboard=qs;exports.ShareDialog=We;exports.VisualBadge=at;exports.VisualEditingControls=rt;exports.cleanCard=Ys;exports.getDashbaordStateWithoutData=Ke;
|
|
278
|
+
`;L(z)}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(Pn,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>c(!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(Fn,{})}),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(On,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function q(){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:v||R,onClick:()=>{O()},className:"h-8 shrink-0",size:"sm",children:[v||R?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(Rn,{errorSql:T,sql:y==null?void 0:y.sql,error:E,onDebugWithAssistant:P}),e.jsx(is,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:z=>r(z),className:"h-8",size:"sm",variant:"outline",children:e.jsx(Ln,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:o,onClick:()=>{A(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:o?"":"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()]}),q()]})}const Vn=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:He}];function zn({className:t}){const n=s.useEditorStore(i=>i.card),{setCardType:a,setCard:r,updateCardInFrame:l}=s.useEditorActions(),c=["table","aggregateTable","pivotTable"].includes(n.type),d=s.hasValidCardConfig(n.config);if(!c||!d)return null;const o=i=>{var m;const u=i;if(u==="aggregateTable"&&((m=n.config)!=null&&m.pivotByColumns)&&n.config.pivotByColumns.length>0){const x={...n,type:u,config:{...n.config,pivotByColumns:[]}};r(x),l(x)}else{a(u);const x={...n,type:u};l(x)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:o,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Vn.map(i=>{const u=i.icon,m=n.type===i.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:i.value,id:`table-type-${i.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${i.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"}),i.label]})]},i.value)})})})}function Un({card:t}){var L,A,w,D,g,y,v,R,S,F,I;const[n,a]=k.useState(!1),[r,l]=k.useState([]),{authToken:c}=s.useSemaphorContext(),{theme:d}=s.useTheme(),o=s.getTokenParams(c==null?void 0:c.accessToken),i=s.useDashboardStore(T=>T.themeStyle),u={mode:d||"system",colors:((A=(L=i==null?void 0:i.chart)==null?void 0:L.dataset)==null?void 0:A.backgroundColor)||[]};(w=t.customCardPreferences)!=null&&w.inputData;const{getCard:m}=s.useCustomVisual(((D=t.customCardPreferences)==null?void 0:D.url)||""),x=((g=t.customCardPreferences)==null?void 0:g.visualType)||"single",h=s.useEditorStore(T=>T.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(t),f=k.useCallback((T,M)=>{l(O=>({...O,[T]:M}))},[]);if(!((y=t.customCardPreferences)!=null&&y.componentName))return null;const j=m((v=t.customCardPreferences)==null?void 0:v.componentName);function N(T){a(T)}const C=Object.keys(((R=t.customCardPreferences)==null?void 0:R.dataInputCardIds)||{}).map(T=>{var E,P,B;const M=(P=(E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)==null?void 0:P[T].cardId,O=(B=h==null?void 0:h.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(k.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[j&&x==="single"&&e.jsx(j,{editing:!0,params:o,theme:u,settings:(S=t.customCardPreferences)==null?void 0:S.settings,onDataChange:f,data:(b==null?void 0:b.records)||[]}),j&&x==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)||{}).map(T=>{var E,P,B;const M=(P=(E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)==null?void 0:P[T].cardId,O=(B=h==null?void 0:h.cards)==null?void 0:B.find(Y=>Y.id===M);if(O)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:N,onDataChange:f,dataInputIndex:T,card:O},O.id+T)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(j,{theme:u,onDataChange:f,settings:C.map(T=>{var M;return(M=T==null?void 0:T.customCardPreferences)==null?void 0:M.settings}),data:C.map(T=>T!=null&&T.id?r==null?void 0:r[T.id]:[])})})]})]},(I=t.customCardPreferences)==null?void 0:I.componentName)})}function ft({className:t,...n}){var y;const a=s.useEditorStore(v=>v.card),r=s.hasValidCardConfig(a.config),l=((y=a.customCardPreferences)==null?void 0:y.showCardHeader)??!0,c=s.useEditorStore(v=>v.frame),d=s.useDashboardStore(v=>v.dashboard.filters),o=s.useEditorStore(v=>v.actions.setRunSql),{updateFilter:i}=s.useDashboardActions(),u=d==null?void 0:d.find(v=>v.id===c.filterId),{data:m,isLoading:x,isFetching:h,errorMessage:p,pagination:b}=s.useDashboardCardQuery(a),{setCard:f,updateCardInFrame:j}=s.useEditorActions(),{data:N}=s.useTopoJson(a),C=k.useMemo(()=>{var v;return a.type!=="pivotTable"||!((v=m==null?void 0:m.records)!=null&&v.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]),L=s.usePivotTableConfig(a,C),A=(v,R)=>{var F,I;const S={...a,paginationConfig:{page:v+1,pageSize:R}};f(S),j(S),a.sql&&((I=(F=a.preferences)==null?void 0:F.tablePrefs)!=null&&I.enableDevModePagination)&&o(!0)},w=k.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:N}),[a.id,m==null?void 0:m.records,a.type,a.queryConfig,a.customCfg,a.preferences,N]);function D(v){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Un,{card:v})})}function g(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!x&&!h)return p?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((x||h)&&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)&&w)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:x||h?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:w})});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:A,isLoading:x||h})});if(a.type==="pivotTable"&&L)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:L.data,options:L.options,onAggregationChange:v=>{const R=s.handleAggregationChange(v,a.config),S={...a,config:R};f(S),j(S)},onAggregationLabelChange:v=>{const R=s.handleAggregationLabelChange(v,a.config),S={...a,config:R};f(S),j(S)}})});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:A,onAggregationChange:v=>{const R=s.handleAggregationChange(v,a.config),S={...a,config:R};f(S),j(S)},isLoading:x||h})})}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:v=>f({...a,title:v}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(zn,{})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:v=>f({...a,description:v}),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:v=>i({...u,title:v}),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:g()})]})}const Xe=({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}),_n=()=>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."})]})]}),Gn=({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(Xe,{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(Xe,{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(Xe,{language:"javascript",value:t,onChange:l})})]}),$n=({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 Yn(){const[t,n]=k.useState(!1),[a,r]=k.useState(""),[l,c]=k.useState(""),[d,o]=k.useState(""),[i,u]=k.useState(""),m=s.useEditorStore(w=>w.card),x=s.useEditorStore(w=>w.card.customCfg),h=x?JSON.stringify(x,null,2):"",{data:p}=s.useDashboardCardQuery(m),{data:b}=s.useTopoJson(m),{setCardCustomCfg:f,setCustomVisualCode:j}=s.useEditorActions(),N=w=>{var D,g;return JSON.stringify({...w,data:{...w.data,datasets:(g=(D=w.data)==null?void 0:D.datasets)==null?void 0:g.map(y=>({...y,data:[]}))}},null,2)},C=()=>{var D,g;if(!((D=p==null?void 0:p.records)!=null&&D.length))return;const w=s.createChartConfig({card:m,data:p.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:b});if(w){r(N(w)),o(((g=m.preferences)==null?void 0:g.customVisualCode)||"");const y=s.merge(w,x);c(N(y))}},L=()=>{try{if(d&&j(d),l){const w=JSON.parse(l),D=s.getObjectDiff(JSON.parse(a),w);f(D),u("")}}catch{u("Invalid JSON configuration")}},A=Object.keys(x||{}).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:C,className:A?"":"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(_n,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(ft,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Gn,{customCode:d,cardCustomCfgString:h,mergedConfig:l,onConfigChange:w=>c(w??""),onCodeChange:w=>o(w??"")})]}),e.jsx($n,{error:i,hasCardCustomConfig:!!x,onReset:()=>{c(a),f(null)},onApply:L,onClose:()=>n(!1)})]})]})}function Je(t){const[n,a]=k.useState(null);return n}function gt(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{data:a,isLoading:r,isFetching:l,isError:c}=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:c}}function jt(){const{data:t,isLoading:n,isError:a}=gt(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(o=>({queryKey:["manifest",o.value],queryFn:()=>s.loadManifest(o.value),enabled:!!o.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:i=>Math.min(1e3*2**i,3e4)}))}),l=[];let c=n,d=a;return r.forEach((o,i)=>{var u;if(o.isLoading&&(c=!0),o.isError&&(d=!0),o.data&&((u=t==null?void 0:t.plugins)!=null&&u[i])){const m=t.plugins[i],x=o.data.visuals.map(h=>({name:h.name,pluginName:m.label,componentType:h.componentType,pluginType:m.type,icon:h.icon,chartType:h.chartType,url:m.value}));l.push(...x)}}),{data:l,isLoading:c,isError:d}}function qn({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:c,isLoading:d,isError:o}=jt(),i=k.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 d?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..."})})]}):o?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"})})]}):!c||c.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:c.map((u,m)=>e.jsx(Kn,{text:u.name,onClick:()=>i("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const Kn=({text:t,icon:n,onClick:a})=>{const r=Je(),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 Qn({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:c,setCustomCardPreferences:d,setQueryConfig:o}=s.useEditorActions();function i(m,x){c(null),r({}),a(m),["custom","text","map"].includes(m)&&(l(!0),o(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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("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:()=>i("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>i("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:()=>i("custom"),className:"h-10 p-4",children:e.jsx(ze,{className:s.cn("size-5",n)})})]})}function Hn({chartType:t,className:n,customIcon:a,componentName:r}){const l=Je();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(qe,{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(ze,{className:n});default:return e.jsx(s.Table2,{className:n})}}function bt({variant:t="ghost"}){var c,d;const[n,a]=k.useState(!1),r=s.useEditorStore(o=>o.card),l=r.type;return s.useDashboardStore(o=>o.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(Hn,{className:"size-4",chartType:l,customIcon:(c=r.customCardPreferences)==null?void 0:c.icon,componentName:(d=r.customCardPreferences)==null?void 0:d.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:o=>o.preventDefault(),className:"z-[51] w-72 p-1",children:[e.jsx(Qn,{onChartTypeChange:()=>a(!1)}),e.jsx(qn,{onChartTypeChange:()=>a(!1)})]})]})}function Wn({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,c]=k.useState(!1),d=k.useRef(null),o=k.useRef(!1);function i(){t&&!o.current&&navigator.clipboard.writeText(t)}function u(h){(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),i())}function m(){const h=window.getSelection();if(h&&h.toString().trim()!==""){const p=h.toString();navigator.clipboard.writeText(p),c(!0),o.current=!0,setTimeout(()=>{c(!1),o.current=!1},1e3)}else o.current=!1}function x(){c(!1),o.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:d,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:i,onKeyDown:u,onMouseUp:m,onMouseDown:x,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 Jn(){const t=s.useEditorStore(c=>{var d,o;return(o=(d=c.card.preferences)==null?void 0:d.chartOptions)==null?void 0:o.indexAxis}),n=s.useEditorStore(c=>c.card.type),{setChartOrientation:a}=s.useEditorStore(c=>c.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(Cs,{className:"size-4"}):e.jsx(Ns,{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(Cs,{className:"size-4"}):e.jsx(Ns,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function Xn({className:t}){var h,p,b,f,j,N,C,L;const n=s.useEditorStore(A=>A.card),{setCardPreferences:a,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[c,d]=k.useState(!1),o=((p=(h=n.preferences)==null?void 0:h.displayOptions)==null?void 0:p.showFilterInfo)??!0,i=((f=(b=n.preferences)==null?void 0:b.displayOptions)==null?void 0:f.showCardToolbar)??!0,u=((N=(j=n.preferences)==null?void 0:j.displayOptions)==null?void 0:N.showChrome)??!0,m=((L=(C=n.preferences)==null?void 0:C.displayOptions)==null?void 0:L.allowScroll)??!0,x=(A,w)=>{var y;const D={...n.preferences,displayOptions:{...(y=n.preferences)==null?void 0:y.displayOptions,[A]:w}};a(D);const g={...n,preferences:D};l(g),r(g)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:c,onOpenChange:d,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(_s,{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:o,onCheckedChange:A=>{x("showFilterInfo",A)},onSelect:A=>A.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:i,onCheckedChange:A=>{x("showCardToolbar",A)},onSelect:A=>A.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:A=>{x("showChrome",A)},onSelect:A=>A.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:A=>{x("allowScroll",A)},onSelect:A=>A.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 vt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var d,o;return(o=(d=c.card)==null?void 0:d.preferences)==null?void 0:o.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function l(){const c=["xy","none","x","y"],o=(c.indexOf(a)+1)%c.length;r(c[o])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(Jn,{})}),!["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(He,{className:"size-4"}),a==="x"&&e.jsx(Yt,{className:"size-4"}),a==="y"&&e.jsx(ma,{className:"size-4"}),a==="none"&&e.jsx(fa,{className:"size-4"})]}),e.jsx(Xn,{})]})}function Zn(){const t=s.useEditorStore(b=>b.frame),n=s.useEditorStore(b=>b.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:c}=s.useEditorActions(),d=(b,f)=>{b.dataTransfer.setData("tabIndex",f.toString())},o=b=>{b.preventDefault()},i=(b,f)=>{const j=b.dataTransfer.getData("tabIndex");if(j===f.toString())return;const N=Array.from(t.cards),[C]=N.splice(parseInt(j),1);N.splice(f,0,C),a({...t,cards:N})};function u(b){const f=t.cards.filter(C=>C.id!==b),j=f[0],N={...t,cards:f,activeCardId:j.id};a(N),r(j.id),l(j)}function m(b,f){const j={...t,cards:[...t.cards,f],activeCardId:b.id};a(j),r(f.id)}function x(){const b={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};m(n,b)}function h(b){const f={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,f)}function p(b,f){return b.cards.length===1&&(f.displayTab===!0||f.displayTab===void 0)||b.activeCardId!==f.id&&(f.displayTab===!0||f.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const j=f.displayTab===void 0?!1:!f.displayTab;l({...f,displayTab:j}),c({...f,displayTab:j})},children:f.displayTab===!0||f.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(Ht,{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,f)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:j=>d(j,f),onDragOver:o,onDrop:j=>i(j,f),className:"",value:b.id,children:[p(t,b),e.jsx(s.Editable,{enabled:t.activeCardId===b.id,text:b.tabTitle||b.title,onSave:j=>{l({...n,tabTitle:j}),c({...n,tabTitle:j})},children:b.tabTitle||b.title},b.id),t.activeCardId===b.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:j=>{j.stopPropagation(),x()}}),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.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>h(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function yt(){const t=s.useEditorStore(j=>j.frame),n=s.useEditorStore(j=>j.card),a=s.useEditorStore(j=>j.isSqlRunning),r=s.useEditorStore(j=>j.isDevMode),{setFrame:l,setActiveTabCardId:c,setCard:d,setIsDevMode:o,setRunSql:i}=s.useEditorActions(),{data:u,isLoading:m,isFetching:x,isError:h}=s.useDashboardCardQuery(n);function p(j){const N=t.cards.find(C=>C.id===j);if(N!=null&&N.sql){r||o(!0),c(j);return}if(N!=null&&N.queryConfig){r&&o(!1),b(j),c(j);return}r||b(j),c(j)}function b(j){const N={...t,cards:t.cards.map(L=>L.id===n.id?n:L),activeCardId:j};l(N);const C=N.cards.find(L=>L.id===j);C.sql&&i(!0),d(C)}function f(){return n.type==="kpi"?m||x?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||x,isError:h})})}):n.type==="text"?m||x?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(ft,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:p,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(j=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:j.id,children:f()},j.id)),e.jsx(Zn,{})]})}function Es({children:t}){var D,g;s.useEditorStore(y=>y.frame);const n=s.useEditorStore(y=>y.card),a=s.useEditorStore(y=>y.isDevMode),r=s.useEditorStore(y=>y.isShowingVisual),l=s.useDashboardStore(y=>y.isVisualEditing),c=s.useEditorStore(y=>y.pythonStdOut);s.useEditorStore(y=>y.actions.setRunSql);const{setFrame:d,setCard:o,setActiveTabCardId:i,runAssistant:u,setIsDevMode:m,setCardPreferences:x}=s.useEditorActions(),{data:h,isLoading:p,isFetching:b,errorMessage:f,refetch:j}=s.useDashboardCardQuery(n),[N,C]=k.useState(!1);k.useEffect(()=>{b||C(!1)},[b]);function L(){const y=JSON.stringify(h==null?void 0:h.records,null,2),v=new Blob([y],{type:"application/json"}),R=URL.createObjectURL(v),S=document.createElement("a");S.href=R,S.download=`${n.title}.json`,S.click()}function A(){const v=[Object.keys(h==null?void 0:h.records.reduce((I,T)=>({...I,...T}),{})).join(","),...((h==null?void 0:h.records)||[]).map(I=>Object.values(I).join(","))].join(`
|
|
279
|
+
`),R=new Blob([v],{type:"text/csv"}),S=URL.createObjectURL(R),F=document.createElement("a");F.href=S,F.download=`${n.title}.csv`,F.click()}function w(){const y=`Can you get the documentation for ${n.type} chart?`;u(y)}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(bt,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:w,children:e.jsx(_t,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(Yn,{})]}),!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:A,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:L,children:e.jsx(Jt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(h==null?void 0:h.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(s.IconButton,{tooltip:"Refresh",disabled:p||b,onClick:()=>{C(!0),j()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":N})})}),e.jsx(vt,{})]}),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:((g=(D=n.preferences)==null?void 0:D.tablePrefs)==null?void 0:g.enableDevModePagination)??!1,onCheckedChange:y=>{var v;x({...n.preferences,tablePrefs:{...(v=n.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:y}}),j()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(sr,{})]}),r?e.jsx(yt,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[c&&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:c&&e.jsx(er,{})}),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":c}),children:[(h==null?void 0:h.records)&&(h==null?void 0:h.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(h==null?void 0:h.records)||[]}),f&&e.jsx(Wn,{error:f})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function er(){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 sr(){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 Se({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:c,icon:d,showPlaceholderLabel:o=!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",c),children:e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("span",{children:d}),o&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(i=>e.jsx(s.SelectItem,{value:i.value,children:i.label},i.value))]})})]})}function tr(){var f,j;const t=s.useEditorStore(N=>N.card.customCardPreferences),{data:n}=gt(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(N=>N.card),l=s.useEditorStore(N=>N.frame),c=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:d}=s.useEditorActions(),{components:o,manifest:i}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(f=i==null?void 0:i.visuals)==null?void 0:f.find(N=>N.name===(t==null?void 0:t.componentName));function m(N,C){if(!t)return;const A={...(t==null?void 0:t.dataInputCardIds)||{},[N]:{cardId:C,hookRef:null}};d({...t,dataInputCardIds:A})}function x(N){var L,A;const C=(L=l==null?void 0:l.cards)==null?void 0:L.filter(w=>{var D;return((D=w==null?void 0:w.customCardPreferences)==null?void 0:D.visualType)!=="multiple"}).map(w=>({value:w.id,label:w.tabTitle||w.title}));return e.jsx("div",{className:"space-y-2",children:(A=N==null?void 0:N.dataInputs)==null?void 0:A.map((w,D)=>{var g,y;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:w}),e.jsx(Se,{className:"col-span-6 h-8 w-full justify-between",label:"",options:C||[],value:((y=(g=t==null?void 0:t.dataInputCardIds)==null?void 0:g[D])==null?void 0:y.cardId)||"",onValueChange:v=>m(D,v)})]},D+Math.random())})})}function h(N,C,L=[],A=""){var w,D;return t?N==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((w=t==null?void 0:t.settings)==null?void 0:w[C])||A,onChange:g=>{d({...t,settings:{...t==null?void 0:t.settings,[C]:g.target.value}})}},C):N==="select"?e.jsx(Se,{className:"h-8 w-full",label:"",options:L,value:((D=t==null?void 0:t.settings)==null?void 0:D[C])||A,onValueChange:g=>{d({...t,settings:{...t==null?void 0:t.settings,[C]:g}})}}):null:null}function p(N){const C=Object.entries((N==null?void 0:N.settings)||{});return e.jsx("div",{className:"space-y-3",children:C.map(([L,A])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:A.title}),h(A.ui,L,A.options,A.defaultValue)]},L))})}function b(N){t&&d({...t,visualType:N,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(Se,{icon:e.jsx(Ut,{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:N=>d({...t||{url:"",componentName:""},url:N})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:c,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:o&&e.jsx(Se,{icon:e.jsx(qt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.filter(N=>N.type===c).map(N=>({value:N.name,label:N.name})))||[],value:t.componentName,onValueChange:N=>{console.log("changing value",N),d({...t,componentName:N})}})})]})})]}),((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:x(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:p(u)})})]})]})]})}function Re(){const[t,n]=k.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),c=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),k.useEffect(()=>{c&&n(new Array(c.length).fill(!1))},[c]);function d(u,m){var x,h;m?a!=null&&a.onClickFilter&&((x=a==null?void 0:a.onClickFilter)==null?void 0:x.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):l({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...a,onClickFilter:(h=a==null?void 0:a.onClickFilter)==null?void 0:h.filter(p=>p.columnIndex!==u)}),n(p=>{const b=[...p];return b[u]=!1,b}))}function o(u,m){var h;const x=(h=a==null?void 0:a.onClickFilter)==null?void 0:h.map(p=>p.columnIndex===u?{...p,expression:m.target.value}:p);l({...a,onClickFilter:x})}function i(u){var m,x,h,p;if(t!=null&&t[u]||(x=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(b=>b.columnIndex===u))!=null&&x.expression)return e.jsx(s.Input,{value:(p=(h=a==null?void 0:a.onClickFilter)==null?void 0:h.find(b=>b.columnIndex===u))==null?void 0:p.expression,onChange:b=>o(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:c==null?void 0:c.map((u,m)=>{var x,h;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:!!((x=a==null?void 0:a.onClickFilter)!=null&&x.find(p=>p.columnIndex===m)),onCheckedChange:p=>d(m,p)}),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:((h=a==null?void 0:a.onClickFilter)==null?void 0:h.find(p=>p.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{n(p=>{const b=[...p];return b[m]=!p[m],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),i(m)]})},u)})})}function ar({idx:t}){var o;const n=s.useEditorStore(i=>{var u;return(u=i.card)==null?void 0:u.preferences}),a=s.useEditorStore(i=>{var u;return(u=i.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(i=>i.actions.setCardPreferences),l=(o=n==null?void 0:n.chartOptions)==null?void 0:o.indexAxis,c=a==null?void 0:a.find(i=>i.idx===t);function d(i,u){(i==="end"||i==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:i!=="none",align:i,anchor:i,clamp:!0};if(!c)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:m}]});else{const x={...c};x.datalabels=m;const h=a==null?void 0:a.map(p=>p.idx===u?x:p);r({...n,datasetOptions:h})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Gs,{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:()=>d("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>d("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(aa,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>d("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ra,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>d("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(na,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function nr(){const t=s.useEditorStore(c=>c.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(c=>!s.METADATA_KEYS.includes(c));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const c=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:d}=s.getKeys(c);l=d.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function ms({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 Nt(){const t=s.useEditorStore(i=>i.card),n=s.useEditorStore(i=>{var u,m,x;return(x=(m=(u=i==null?void 0:i.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:x.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:c,transformedMetricKeys:d,keys:o}=nr();return o.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:c.map(i=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:i,children:Ct(i)},i))})]}),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:d.map((i,u)=>e.jsx(St,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:i,idx:u},i))})]})]})}function Ct(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function St({col:t,idx:n,className:a,iconClassName:r,children:l}){const c=s.useEditorStore(m=>{var x;return(x=m.card)==null?void 0:x.preferences}),d=s.useEditorStore(m=>{var x,h;return(h=(x=m.card)==null?void 0:x.preferences)==null?void 0:h.datasetOptions}),o=d==null?void 0:d.find(m=>m.idx===n),{setCardPreferences:i}=s.useEditorStore(m=>m.actions);function u(m){if(!o)i({...c,datasetOptions:[...d||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const x={...o};x.type=m==="area"?"line":m,x.fill=m==="area"?"origin":"";const h=d==null?void 0:d.map(p=>p.idx===n?x:p);i({...c,datasetOptions:h})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(ms,{className:"max-w-[100px]",title:t,children:Ct(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(ar,{idx:n})]})]})}function Be(){const t=s.useDashboardStore(o=>o.dashboard.filters),n=s.useEditorStore(o=>o.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=ct();function c(o){const i=l(o,"frame");a({...n,filterId:i})}const d=t==null?void 0:t.find(o=>o.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(rr,{onSelect:c,columns:r}),d&&e.jsx(s.FilterHeader,{filter:d})]})}function rr({columns:t,onSelect:n}){var d;const[a,r]=ss.useState(!1),[l,c]=ss.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?(d=t.find(o=>o.column_name===l))==null?void 0:d.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(o=>e.jsxs(s.CommandItem,{value:o.column_name,onSelect:i=>{const u=i===l?"":i;c(u),r(!1),u&&n(o)},children:[o.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===o.column_name?"opacity-100":"opacity-0")})]},o.column_name))})]})]})})]})}function lr({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(Nt,{})})]}),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(Re,{}),e.jsx(Be,{})]})]})]})})}function or({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:c=>c.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(Re,{}),e.jsx(Be,{})]})]})]})})}function wt(){const t=s.useEditorStore(o=>o.card.type),n=s.useEditorStore(o=>o.isDevMode),a=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:r}=s.useEditorStore(o=>o.actions);function l(o){var m;const i={datalabels:{display:o!=="none",align:o,anchor:o,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(m=a==null?void 0:a.chartOptions)==null?void 0:m.plugins,...i}}};r(u)}function c(){var o,i,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=(i=(o=a==null?void 0:a.chartOptions)==null?void 0:o.plugins)==null?void 0:i.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 d(){var o,i,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(i=(o=a==null?void 0:a.chartOptions)==null?void 0:o.plugins)==null?void 0:i.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?c():d()})}const ir={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},cr={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function dr(){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:ur(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(wt,{}),e.jsx(Re,{}),e.jsx(Be,{})]})]})}function ur(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(ir,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(cr,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 mr({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(d,o,i){const u=[...t];u[d]={...u[d],[o]:i},n(u)}function l(d){const o=[...t];o.splice(d,1),n(o)}function c(){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:c,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((d,o)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:i=>r(o,"start",i.target.value),value:d.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:d.end,onChange:i=>r(o,"end",i.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:i=>r(o,"color",i.target.value),value:d.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(o),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},o))]})}function hr(){var m,x,h,p,b;const t=s.useEditorStore(f=>f.card.preferences),n=s.useEditorStore(f=>f.actions.setCardPreferences),a=s.useEditorStore(f=>f.card),r=s.hasValidCardConfig(a.config),l=s.useEditorStore(f=>f.actions.setNumberFormat);s.useEditorStore(f=>{var j,N;return(N=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:N.decimalPlaces});const c=s.useEditorStore(f=>{var j,N;return(N=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:N.locale}),d=s.useEditorStore(f=>{var j,N;return(N=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:N.currency});s.useEditorStore(f=>f.actions.setFilterOnClickField);const o=s.useEditorStore(f=>{var j,N;return(N=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:N.colorRanges})||[],i=s.useEditorStore(f=>f.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(f=>f.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:f=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:f}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((x=t==null?void 0:t.formatNumber)==null?void 0:x.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:c||"none",onValueChange:f=>{var j,N,C;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((N=t==null?void 0:t.formatNumber)==null?void 0:N.currency)||"",f,((C=t==null?void 0:t.formatNumber)==null?void 0:C.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(f=>e.jsx(s.SelectItem,{value:f.locale,children:f.locale},f.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:d||"none",onValueChange:f=>{var j,N,C;console.log("currency",f),l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,f==="none"?"":f,((N=t==null?void 0:t.formatNumber)==null?void 0:N.locale)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.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(f=>e.jsx(s.SelectItem,{value:f,children:f},f))]})})]})]})]}),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:((p=(h=t==null?void 0:t.formatNumber)==null?void 0:h.decimalPlaces)==null?void 0:p.toString())||"0",onValueChange:f=>{var j,N,C;return l(Number(f),((j=t==null?void 0:t.formatNumber)==null?void 0:j.currency)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.locale)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.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(f=>e.jsx(s.SelectItem,{value:f,children:f},f))})]})]}),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:f=>{var j,N,C;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((N=t==null?void 0:t.formatNumber)==null?void 0:N.currency)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",f.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(mr,{colorRanges:o,setColorRanges:i})]})]})}function xr(){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(hr,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function Ze({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 pr=[{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"}],fr=["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"],gr=fr.map(t=>({label:t,value:t}));function jr(){var i,u,m,x,h,p,b,f,j,N,C,L,A,w,D,g,y,v;const t=s.useEditorStore(R=>R.card),n=(u=(i=t==null?void 0:t.preferences)==null?void 0:i.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=k.useState(((x=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:c}=s.useTopoJson(t),d=Object.keys((c==null?void 0:c.objects)||{}).map(R=>({label:R,value:R}))||[],o=[{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(Ze,{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(Ze,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Se,{className:"h-9",options:o,onValueChange:R=>{console.log("value",R),l({...t.preferences,mapVisualOptions:{topoJsonUrl:R}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:R=>{r(R.target.value)},onBlur:()=>{var R;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(R=t.preferences)==null?void 0:R.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(Se,{className:"h-9",options:d,value:((p=(h=t.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:R=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,objectKey:R}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(Se,{className:"h-9",options:pr,value:((f=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:f.projection)||"",label:"Projection",onValueChange:R=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projection:R}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(Se,{className:"h-9",options:gr,value:((N=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:N.colorScale)||"",label:"Select Color Scale",onValueChange:R=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,colorScale:R}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ze,{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:((L=(C=t.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:L.projectionScale)||1,onChange:R=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionScale:Number(R.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=(w=(A=t.preferences)==null?void 0:A.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:D[0])||0,onChange:R=>{var S,F,I,T;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[Number(R.target.value),((T=(I=(F=t.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:T[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((v=(y=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:y.projectionOffset)==null?void 0:v[1])||0,onChange:R=>{var S,F,I,T;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[((T=(I=(F=t.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:T[0])||0,Number(R.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Re,{})]})}function br(){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 Ge({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(br,{})})]}),!["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(Re,{}),e.jsx(Be,{})]})]})]})})}function vr(){const t=s.useEditorStore(r=>{var l,c;return(c=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:c.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(Se,{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(Nt,{})]})]}),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(Re,{}),e.jsx(Be,{})]})]})]})})}function yr({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var c;return(c=l.card)==null?void 0:c.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(Re,{}),e.jsx(Be,{})]})]})}),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 Dt({color:t,onColorChange:n,onClose:a}){const[r,l]=k.useState(0),[c,d]=k.useState(100),[o,i]=k.useState(50),[u,m]=k.useState(t);k.useEffect(()=>{const j=Is(t);if(j){const N=As(j.r,j.g,j.b);l(N.h),d(N.s),i(N.l),m(t)}},[t]);const x=j=>{l(j),p(j,c,o)},h=j=>{const N=j.currentTarget.getBoundingClientRect(),C=Math.max(0,Math.min(1,(j.clientX-N.left)/N.width)),L=Math.max(0,Math.min(1,(j.clientY-N.top)/N.height)),A=C*100,w=(1-L)*100;d(A),i(w),p(r,A,w)},p=(j,N,C)=>{const L=Cr(j,N,C),A=Nr(L.r,L.g,L.b);m(A)},b=j=>{if(m(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const N=Is(j);if(N){const C=As(N.r,N.g,N.b);l(C.h),d(C.s),i(C.l)}}},f=()=>{/^#[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:h,onMouseMove:j=>{j.buttons===1&&h(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:`${c}%`,top:`${100-o}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>x(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:f,children:"OK"})]})]})}function Is(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 Nr(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function As(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let c=0,d=0;const o=(r+l)/2;if(r!==l){const i=r-l;switch(d=o>.5?i/(2-r-l):i/(r+l),r){case t:c=((n-a)/i+(n<a?6:0))/6;break;case n:c=((a-t)/i+2)/6;break;case a:c=((t-n)/i+4)/6;break}}return{h:Math.round(c*360),s:Math.round(d*100),l:Math.round(o*100)}}function Cr(t,n,a){t/=360,n/=100,a/=100;let r,l,c;if(n===0)r=l=c=a;else{const d=(u,m,x)=>(x<0&&(x+=1),x>1&&(x-=1),x<.16666666666666666?u+(m-u)*6*x:x<.5?m:x<.6666666666666666?u+(m-u)*(.6666666666666666-x)*6:u),o=a<.5?a*(1+n):a+n-a*n,i=2*a-o;r=d(i,o,t+1/3),l=d(i,o,t),c=d(i,o,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(c*255)}}const Sr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Tt(){var L,A,w,D,g,y,v,R,S,F;const t=s.useEditorStore(I=>I.card),n=s.useEditorStore(I=>{var T;return(T=I.card)==null?void 0:T.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[c,d]=k.useState({}),[o,i]=k.useState(null),[u,m]=k.useState(null),x=k.useMemo(()=>{var O,E,P,B,Y,q,z;if(!(l!=null&&l.records)||l.records.length===0)return[];const I=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",T=(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((I||T)&&M){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const J=new Set;return l.pivotSchema.forEach(W=>{W.alias&&J.add(W.alias)}),Array.from(J)}if(l.records.length>0){const J=l.records[0],W=Object.keys(J),se=new Set;(E=t==null?void 0:t.config)!=null&&E.groupByColumns&&t.config.groupByColumns.forEach(Q=>{se.add(Q.label||Q.name),se.add(Q.alias||Q.name)});const te=new Set;return(P=t==null?void 0:t.config)!=null&&P.metricColumns&&t.config.metricColumns.forEach(Q=>{const _=Q.alias||Q.name;te.add(_),te.add(`${_}_count`),te.add(`${_}_sum`),te.add(`${_}_avg`),te.add(`${_}_min`),te.add(`${_}_max`);const ae=Q.entityName||Q.qualifiedEntityName;ae&&(te.add(`${ae}_${_}`),te.add(`${ae}_${_}_count`))}),W.filter(Q=>!se.has(Q)&&!te.has(Q))}}if((T||I)&&!M&&((Y=(B=t==null?void 0:t.config)==null?void 0:B.metricColumns)!=null&&Y.length))return t.config.metricColumns.map(J=>J.alias||J.label||J.name);if((z=(q=t==null?void 0:t.config)==null?void 0:q.groupByColumns)!=null&&z.length){const J=t.config.groupByColumns[0],W=J.label||J.name,se=new Set;return l.records.forEach(te=>{const oe=te[W];oe!=null&&se.add(String(oe))}),Array.from(se)}return[]},[l,(L=t==null?void 0:t.config)==null?void 0:L.groupByColumns,(A=t==null?void 0:t.config)==null?void 0:A.pivotByColumns,(w=t==null?void 0:t.config)==null?void 0:w.metricColumns,t==null?void 0:t.type]),h=k.useMemo(()=>s.getDefaultChartColors(),[]);k.useEffect(()=>{const I={};x.forEach((T,M)=>{I[T]=s.getColorForValue(T,M,n==null?void 0:n.colorConfig)}),d(I)},[x,n==null?void 0:n.colorConfig,h]);const p=(I,T)=>{const M={...c,[I]:T};d(M);const O={...n||{},colorConfig:{segments:M}};a(O);const E={...t,preferences:O};r(E)},b=(I,T)=>{var Y;const M=h[T%h.length],{[I]:O,...E}=((Y=n==null?void 0:n.colorConfig)==null?void 0:Y.segments)||{},P={...n||{},colorConfig:{segments:E}};a(P);const B={...t,preferences:P};r(B),d(q=>({...q,[I]:M}))};if(!x.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((g=(D=t==null?void 0:t.config)==null?void 0:D.groupByColumns)==null?void 0:g.length)||((v=(y=t==null?void 0:t.config)==null?void 0:y.pivotByColumns)==null?void 0:v.length):(S=(R=t==null?void 0:t.config)==null?void 0:R.groupByColumns)==null?void 0:S.length)||["table","kpi","text","custom"].includes(t.type))return null;const N=()=>{const I={...n||{},colorConfig:{segments:{}}};a(I);const T={...t,preferences:I};r(T);const M={};x.forEach((O,E)=>{M[O]=s.getColorForValue(O,E,void 0)}),d(M)},C=Object.keys(((F=n==null?void 0:n.colorConfig)==null?void 0:F.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(da,{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:C&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:N,children:[e.jsx(Ss,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:x.map((I,T)=>{const M=s.isDefaultColor(c[I],T),O=!M;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:o===I,onOpenChange:E=>i(E?I: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:c[I]}})}),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:h.slice(0,10).map((E,P)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",c[I]===E?"border-gray-900":"border-transparent"),style:{backgroundColor:E},onClick:()=>{p(I,E),i(null)},children:[P===T%h.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:E})]},`default-${P}`))})]}),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:Sr.map((E,P)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",c[I]===E?"border-2 border-gray-900":E==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:E},onClick:()=>{p(I,E),i(null)},children:e.jsx("span",{className:"sr-only",children:E})},`preset-${P}`))})]}),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:I,color:c[I]}),i(null)},children:"Custom color"}),!M&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(I,T),i(null)},children:[e.jsx(Ss,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:I}),O&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},I)})}),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(Dt,{color:u.color,onColorChange:I=>{p(u.value,I),m(null)},onClose:()=>m(null)})})]})]})})]})}function we({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[c,d]=k.useState(t??""),[o,i]=k.useState(!1);k.useEffect(()=>{d(t??"")},[t]);const u=()=>{n(c),i(!1)},m=()=>{d(t??""),i(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:o?c:t??"",onChange:x=>{d(x.target.value),i(!0)},onFocus:()=>i(!0),onClick:x=>x.stopPropagation(),className:"h-8 text-xs",onPointerDown:x=>x.stopPropagation(),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&o&&c!==t?u():x.key==="Escape"&&m()},"aria-label":a||"Edit field"}),o&&c!==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 wr=["auto","number","currency","percent","scientific","date"],Dr=[{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"}],Tr=[{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"}],kr=t=>t.charAt(0).toUpperCase()+t.slice(1);function hs({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",c=(o,i)=>{n({...t,[o]:i})},d=()=>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:o=>c("type",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:wr.map(o=>e.jsx(s.SelectItem,{value:o,className:"text-xs",children:o==="auto"?"Auto (Default)":kr(o)},o))})]})]}),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??d(),onChange:o=>c("decimalPlaces",parseInt(o.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:o=>c("currency",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Dr.map(o=>e.jsx(s.SelectItem,{value:o.value,className:"text-xs",children:o.label},o.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:o=>c("useSuffix",o)})]}),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:o=>c("locale",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Tr.map(o=>e.jsx(s.SelectItem,{value:o.value,className:"text-xs",children:o.label},o.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:o=>c("prefix",o.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:o=>c("suffix",o.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:o=>c("negativeInParentheses",o)})]}),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:o=>c("multiplyBy",o.target.value?parseFloat(o.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:o=>c("dateFormat",o.target.value),className:"h-8 text-xs"})})]})]})]})}function Ms({axis:t,label:n,type:a,config:r,onChange:l}){var x,h,p,b,f,j,N,C,L,A,w,D;const c=(g,y)=>{l({...r,[g]:y})},d=(g,y)=>{var v,R;l({...r,name:{enabled:g==="enabled"?y:((v=r==null?void 0:r.name)==null?void 0:v.enabled)??!1,text:g==="text"?y:(R=r==null?void 0:r.name)==null?void 0:R.text}})},o=(g,y)=>{var v,R;l({...r,labels:{enabled:g==="enabled"?y:((v=r==null?void 0:r.labels)==null?void 0:v.enabled)??!0,rotation:g==="rotation"?y:(R=r==null?void 0:r.labels)==null?void 0:R.rotation}})},i=(g,y)=>{l({...r,scale:{...r==null?void 0:r.scale,[g]:y===""?"auto":Number(y)}})},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:g=>c("enabled",g),onClick:g=>g.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:((x=r==null?void 0:r.name)==null?void 0:x.enabled)??!1,onCheckedChange:g=>d("enabled",g)})]}),((h=r==null?void 0:r.name)==null?void 0:h.enabled)&&e.jsx(we,{placeholder:`${n} title`,value:((p=r==null?void 0:r.name)==null?void 0:p.text)||"",onSave:g=>d("text",g),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:g=>c("position",g),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(g=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:g==="auto"?"Auto (Default)":s.titleCase(g)},g))})]})]}),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:g=>o("enabled",g)})]}),((f=r==null?void 0:r.labels)==null?void 0:f.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:g=>o("rotation",g==="auto"?"auto":Number(g)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(g=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:g==="auto"?"Auto (Default)":`${g}°`},g))})]})]})]}),a==="value"&&e.jsx(hs,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:g=>l({...r,formatOptions:g}),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:((N=r==null?void 0:r.scale)==null?void 0:N.min)==="auto"||((C=r==null?void 0:r.scale)==null?void 0:C.min)===void 0?"":String(r.scale.min),onSave:g=>i("min",g),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:((L=r==null?void 0:r.scale)==null?void 0:L.max)==="auto"||((A=r==null?void 0:r.scale)==null?void 0:A.max)===void 0?"":String(r.scale.max),onSave:g=>i("max",g),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:((w=r==null?void 0:r.scale)==null?void 0:w.stepSize)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.stepSize)===void 0?"":String(r.scale.stepSize),onSave:g=>i("stepSize",g),className:""})})]})]})]})]})]})}function kt(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.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 c=(d,o)=>{const u={...n||{},[d==="x"?"xAxisConfig":"yAxisConfig"]:o};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(_s,{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(Ms,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:d=>c("x",d)}),l.hasYAxis&&e.jsx(Ms,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:d=>c("y",d)})]})})]})}function Et(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var m,x,h,p;return(p=(h=(x=(m=u.card)==null?void 0:m.preferences)==null?void 0:x.chartOptions)==null?void 0:h.plugins)==null?void 0:p.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",c=!(t.type==="stackedBar"||t.type==="stackedLine"),d=(u,m)=>{const x={...n,[u]:m};a(x)},o=["top","bottom","left","right"],i=["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(ta,{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)??c,onCheckedChange:u=>d("display",u)})]}),((n==null?void 0:n.display)??c)&&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=>d("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:o.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=>d("align",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))})]})]})]})]})})]})}function It(){var y,v,R,S,F,I,T,M,O;const t=s.useEditorStore(E=>E.card),n=s.useEditorStore(E=>{var P,B;return(B=(P=E.card)==null?void 0:P.preferences)==null?void 0:B.dataLabelsConfig}),a=s.useEditorStore(E=>{var P;return(P=E.card)==null?void 0:P.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const c=((y=a==null?void 0:a.chartOptions)==null?void 0:y.indexAxis)==="y",d=t.type==="stackedBar"||t.type==="stackedLine",o=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",i=!o,u=(R=(v=a==null?void 0:a.chartOptions)==null?void 0:v.plugins)==null?void 0:R.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),x=(n==null?void 0:n.enabled)!==void 0?n.enabled:m,h=(E,P)=>{const B={...n,[E]:P},Y={...t.preferences||{},dataLabelsConfig:B};r(Y);const q={...t,preferences:Y};l(q)},p=(E,P)=>{const B={...n,font:{...n==null?void 0:n.font,[E]:P}},Y={...t.preferences||{},dataLabelsConfig:B};r(Y);const q={...t,preferences:Y};l(q)},b=(E,P)=>{const B={...n,formatOptions:{...n==null?void 0:n.formatOptions,[E]:P}},Y={...t.preferences||{},dataLabelsConfig:B};r(Y);const q={...t,preferences:Y};l(q)},j=(()=>{const E=t.type;return E==="stackedBar"||E==="stackedLine"||E==="pie"||E==="doughnut"?"center":c?"right":"top"})();let N=[];d||o?N=["center"]:N=["auto",...(c?["center","left","right"]:["center","top","bottom"]).filter(P=>P!==j),"custom"];const C=()=>s.titleCase(j),L=["center","start","end"],A=["center","start","end","top","bottom"],w=i?["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"}],g=[{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(ja,{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:x,onCheckedChange:E=>h("enabled",E)})]}),x&&e.jsxs(e.Fragment,{children:[!d&&!o&&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:E=>h("position",E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(E=>e.jsx(s.SelectItem,{value:E,className:"text-xs",children:E==="auto"?C():E==="custom"?"Custom (Advanced)":s.titleCase(E)},E))})]})]}),d&&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:E=>h("showTotal",E)})]}),(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:E=>h("anchor",E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:L.map(E=>e.jsx(s.SelectItem,{value:E,className:"text-xs",children:s.titleCase(E)},E))})]})]}),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:E=>h("align",E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:A.map(E=>e.jsx(s.SelectItem,{value:E,className:"text-xs",children:s.titleCase(E)},E))})]})]})]}),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)||(i?"auto":"none"),onValueChange:E=>h("format",E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:w.map(E=>e.jsx(s.SelectItem,{value:E,className:"text-xs",children:E==="auto"&&i?"Auto (Use Axis)":E==="none"?"None (Raw Value)":s.titleCase(E)},E))})]})]}),(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(((S=n==null?void 0:n.formatOptions)==null?void 0:S.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:E=>b("decimalPlaces",Number(E)),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:((F=n==null?void 0:n.formatOptions)==null?void 0:F.currency)||"USD",onValueChange:E=>b("currency",E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:D.map(E=>e.jsx(s.SelectItem,{value:E.value,className:"text-xs",children:E.label},E.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:((I=n==null?void 0:n.formatOptions)==null?void 0:I.useSuffix)??!1,onCheckedChange:E=>b("useSuffix",E)})]}),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:((T=n==null?void 0:n.formatOptions)==null?void 0:T.locale)||"en-US",onValueChange:E=>b("locale",E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:g.map(E=>e.jsx(s.SelectItem,{value:E.value,className:"text-xs",children:E.label},E.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:E=>p("size",Number(E)),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:E=>p("weight",E),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:E=>{E==="auto"&&h("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:E=>h("rotation",Number(E)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Er(){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(Tt,{}),e.jsx(kt,{}),e.jsx(Et,{}),e.jsx(It,{})]})]})}const Ir=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."]})]}),Ar=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."]})]}),Mr=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 Rr(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=c=>r.includes(a)?c:e.jsxs(e.Fragment,{children:[c,e.jsx(Er,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(vr,{}));case"tornado":case"pyramid":return l(e.jsx(Ge,{docContent:Ir,cardType:a}));case"kpi":return e.jsx(xr,{});case"line":case"bar":return l(e.jsx(lr,{cardType:a}));case"range":return l(e.jsx(Ge,{docContent:Ar,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Ge,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(or,{cardType:a}));case"table":return e.jsx(yr,{cardType:a});case"text":return e.jsx(Ge,{docContent:Mr,cardType:a,suffix:"Visual"});case"map":return e.jsx(jr,{});case"custom":return e.jsx(tr,{});default:return l(e.jsx(dr,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Lr(){const t=k.useRef(null),n=k.useRef(null),a=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog);return k.useEffect(()=>{var l,c,d,o;r?((l=t.current)==null||l.resize(0),(c=n.current)==null||c.resize(0)):((d=t.current)==null||d.resize(25),(o=n.current)==null||o.resize(25))},[r]),e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Bn,{})}),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(Rr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Es,{})})]}):e.jsx(Es,{})})]})}function Fr(t){var ue;s.useAIInteractionStore(U=>U.currentAIContext);const[n,a]=k.useState(""),[r,l]=k.useState(null),{authToken:c,tokenProps:d}=s.useSemaphorContext(),o=s.useEditorStore(U=>{var X;return(X=U==null?void 0:U.card)==null?void 0:X.sql}),i=s.useEditorStore(U=>U.isDevMode),u=s.useEditorStore(U=>{var X;return(X=U==null?void 0:U.card)==null?void 0:X.python}),{setCardPython:m,setCardSql:x,setRunSql:h,switchCardType:p,setQueryConfig:b}=s.useEditorActions(),f=s.useEditorStore(U=>U.currentAssitantScope)||[],j=s.useEditorStore(U=>U.userInputForAI),N=s.useEditorStore(U=>U.triggerAIRun),C=s.useEditorStore(U=>U.card),L=s.useEditorStore(U=>U.selectedDatabaseName),A=s.useEditorStore(U=>U.selectedTableName),w=s.useEditorStore(U=>U.selectedConnectionId),D=s.useEditorStore(U=>U.selectedSchemaName),g=s.useDashboardStore(U=>U.dashboard.aiScopeTables),{errorMessage:y,refetch:v,data:R}=s.useDashboardCardQuery(C),{setTriggerAIRun:S,setCurrentAssitantScope:F,setCardConfig:I}=s.useEditorActions(),{selectedDatamodelName:T,connectionType:M,selectedDatamodelId:O}=s.useEditorAside(),E=(ue=s.useDashboardQuery().data)==null?void 0:ue.assistantProfileId,{messages:P,setMessages:B,regenerate:Y,error:q,sendMessage:z,status:J,addToolResult:W,stop:se,clearError:te}=s.useChat({transport:new s.DefaultChatTransport({api:`${d.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const U=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:E,isDevMode:i,aiContext:U.currentAIContext,reasoningEffort:U.reasoningEffort,showReasoning:U.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:U,body:X})=>({body:{...X,messages:s.cleanupIncompleteMessages(U)}})}),onError:U=>{var X;if(U.name==="AbortError"||(X=U.message)!=null&&X.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",U)},onToolCall:oe,onFinish({isAbort:U,isDisconnect:X,isError:xe}){a(""),console.log(U?"[Editor Assistant] Stream aborted by user":X?"[Editor Assistant] Stream disconnected (network error)":xe?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});k.useEffect(()=>{N&&j&&(z({role:"user",parts:[{type:"text",text:j}]}),S(!1))},[N,j,z,S]);async function oe({toolCall:U}){var X,xe,ce,K,G,V,Z,le,de,ne,me,je,Le,Fe,Te,ke;if(["createChartFromSql","createForecast"].includes(U.toolName)){const ee=((X=U.input)==null?void 0:X.sql)??((xe=U.args)==null?void 0:xe.sql),he=((ce=U.input)==null?void 0:ce.python)??((K=U.args)==null?void 0:K.python),pe=((G=U.input)==null?void 0:G.chartType)??((V=U.args)==null?void 0:V.chartType);p(pe),x(ee),m(he),h(!0),W({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(U.toolName==="getUserSql"){if(!o){W({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"error",message:"No SQL found"}});return}W({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",sql:o,python:u||""}})}else if(U.toolName==="generateQueryConfig"){a("Generating query config...");const ee=((Z=U.input)==null?void 0:Z.chartType)??((le=U.args)==null?void 0:le.chartType),he=((de=U.input)==null?void 0:de.queryConfig)??((ne=U.args)==null?void 0:ne.queryConfig);((me=U.input)==null?void 0:me.cardConfig)??((je=U.args)==null||je.cardConfig),p(ee),I(he),x(void 0),m(void 0);const pe=await v();if((Le=pe==null?void 0:pe.data)!=null&&Le.error){W({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"error",queryConfig:he,message:(Fe=pe==null?void 0:pe.data)==null?void 0:Fe.error.message}});return}if((Te=pe==null?void 0:pe.data)!=null&&Te.records){W({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",queryConfig:he,message:"The data has been visualized"}});return}W({tool:U.toolName,toolCallId:U.toolCallId,output:{status:"success",queryConfig:he,message:"The data has been visualized",records:(ke=pe==null?void 0:pe.data)==null?void 0:ke.records}})}else a("Analyzing...")}function Q(U){const X=s.removeFromScopeArray(f,U);_(X)}function _(U){const X=s.sanitizeAIScope(U);F(X),B(xe=>[...xe,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(X)}`}]}])}function ae(){const U={databaseName:L||"",schemaName:D||"",tableName:A||"",datamodelId:O||"",datamodelName:s.resolveDatamodelName(T),connectionId:w||"",connectionType:M||""},X=s.dedup([...f,U]);_(X)}function H(){const U={databaseName:L||"",schemaName:D||"",tableName:A||"",datamodelName:s.resolveDatamodelName(T),connectionId:w||"",connectionType:M||"",datamodelId:O||""};if(!s.isInAiScopeArray([...g||[],...f],U)||f.length===0){const xe=s.dedup([...g||[],...f,U]).filter(ce=>ce.connectionId===U.connectionId);_(xe)}}const re=!["ready","error"].includes(J),ie=s.getErrorMessage(q);return{messages:P,setMessages:B,sendMessage:z,regenerate:Y,isLoading:re,handleSetAIScope:H,handleAddCurrentTableToScope:ae,removeFromCurrentSelections:Q,currentAssitantScope:f,setCurrentAssitantScope:F,stop:se,status:J,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:ie,clearError:te}}const Or=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Rs({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=k.useRef(null),[l,c]=k.useState(!1),[d,o]=k.useState(s.isDevEnv),[i,u]=k.useState(!1),[m,x]=k.useState(!1),[h,p]=k.useState(!1),b=t??h,f=s.useCurrentAIContext(),{setCurrentAIContext:j}=s.useAIActions(),{clearQueue:N}=s.useQueueActions(),{clearFileAttachments:C}=s.useFileActions(),L=s.useFileAttachments("editor"),A=s.useDashboardStore(ee=>ee.dashboard.aiContext),w=s.useEditorStore(ee=>ee.card.dataSource),D=s.useEditorStore(ee=>ee.actions.setCardSql),g=s.useEditorStore(ee=>ee.actions.setRunSql),y=s.useEditorStore(ee=>ee.showAIDialog),v=s.useDashboardStore(ee=>ee.handleOpenAssistantProfile),{setShowAIDialog:R,setCardPython:S}=s.useEditorActions(),{setDataSource:F}=s.useEditorActions(),{assistantProfile:I}=s.useAssistantProfile(),{messages:T,setMessages:M,sendMessage:O,isLoading:E,stop:P,status:B,llmUsage:Y,errorMessage:q,clearError:z}=Fr(),[J,W]=k.useState(""),se=ee=>{W(ee.target.value)},te=ee=>{ee.preventDefault();const he=J.trim();if(!he&&L.length===0)return;const pe=[];he&&pe.push({type:"text",text:he}),L.forEach(Ee=>{Ee.data&&pe.push({type:"file",mediaType:Ee.type,filename:Ee.name,url:`data:${Ee.type};base64,${Ee.data}`})}),O({role:"user",parts:pe}),W(""),C("editor"),X({force:!0})},{visibleMessages:oe,hasMoreMessages:Q,totalMessageCount:_,loadMoreMessages:ae,resetMessageWindow:H}=s.useMessageWindow(T,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:re,isAtBottom:ie,hasNewMessages:ue,newMessageCount:U,scrollToBottom:X,handleScroll:xe,resetNewMessageCount:ce}=s.useAutoScroll(oe,{threshold:50,behavior:"smooth",isStreaming:E});k.useEffect(()=>{var ee;y&&((ee=r.current)==null||ee.focus(),j({selectedEntities:(w==null?void 0:w.selectedEntities)||[]}))},[y,w,j]),s.useAutoSubmitQueue({assistantType:"editor",status:B,isLoading:E,sendMessage:O});const{hasActiveTools:K}=s.useActiveToolStatus(T),G=k.useCallback(ee=>{n==null||n(ee),t===void 0&&p(ee)},[t,n]);k.useEffect(()=>{if(!b)return;function ee(he){he.key==="Escape"&&G(!1)}return window.addEventListener("keydown",ee),()=>{window.removeEventListener("keydown",ee)}},[b,G]);const V=k.useCallback(ee=>{O({role:"user",parts:[{type:"text",text:ee}]}),X({force:!0})},[O,X]),Z=k.useCallback(async()=>{const ee=JSON.stringify(T??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ee),s.ue.success("Conversation copied")}catch(he){console.error("Failed to copy conversation",he),s.ue.error("Unable to copy conversation")}},[T]),le=k.useCallback(()=>{G(!b)},[b,G]);function de(ee,he){he==="sql"?(D(ee),g(!0)):he==="python"&&(S(ee),g(!0))}function ne(){f.selectedEntities.length===0&&j({selectedEntities:(A==null?void 0:A.selectedEntities)||[]})}function me(ee){ne();const he={role:"user",parts:[{type:"text",text:ee.title+" "+ee.subtitle}]};O(he)}function je(ee){ne(),O({role:"user",parts:[{type:"text",text:ee}]})}function Le(){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 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:l,onCheckedChange:c,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:u,children:"System Message"})]})]})}function Fe(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Te=(J==null?void 0:J.length)===0&&(T==null?void 0:T.filter(ee=>ee.role==="user").length)===0,ke=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",b&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Fe(),v&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:v,children:(I==null?void 0:I.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Le(),d&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Z,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:b?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:le,children:b?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{M([]),N("editor"),z(),H()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{R(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:re,className:"mt-2 flex w-full grow basis-0",onScroll:xe,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[Q&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:ae,className:"text-xs",children:["Load ",Math.min(5,_-oe.length)," ","more messages (",_-oe.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:oe,showTools:d,handleRun:de,showSystemMessage:i,onQuickReply:V,disableQuickReplies:E}),!K&&e.jsx(s.AssistantStatus,{status:B,errorMessage:q})]})}),!ie&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{X({force:!0}),ce()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),ue&&U>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:U>9?"9+":U})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Te&&!I&&e.jsx(s.Placeholders,{onClick:me,placeholders:Or}),e.jsx("div",{children:Te&&I&&e.jsx(s.SeedQuestions,{seedQuestions:I.seedQuestions||[],handleSeedQuestionClick:je})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:W,stop:P,input:J,handleInputChange:se,handleSubmit:ee=>{ne(),te(ee),X({force:!0})},isLoading:E,status:B,assistantType:"editor",onFocus:()=>{}})]}),Y&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",Y.inputTokens," prompt tokens, ",Y.outputTokens," ","completion tokens, ",Y.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(w==null?void 0:w.selectedEntities)||[],open:m,onOpenChange:x,dataSource:w||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return b&&a?Vt.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:ke})}),a):ke}function xs(t,n){const[a,r]=k.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):n});return k.useEffect(()=>{localStorage.setItem(t,JSON.stringify(a))},[a,t]),[a,r]}const Pr="chart-selector-standard-first";function Br(){const[t,n]=xs(Pr,!0);return{standardFirst:t,updatePreference:n}}const Ls=({pluginVisual:t,index:n,onSelect:a})=>{const r=Je(t.icon||""),l=t.name.charAt(0).toUpperCase(),c=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"}):c||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}`)},Fs=["default","standardPlugin","customPlugin"];function Vr({selectedChart:t,onChartChange:n}){var A;const[a,r]=k.useState(!1),{data:l}=jt();Br();const d=((A=s.useEditorStore(w=>w.card).customCardPreferences)==null?void 0:A.url)||"";os(d);const{setCardType:o,setCardPreferences:i,setIsDevMode:u}=s.useEditorStore(w=>w.actions),{setCardCustomCfg:m,setCustomCardPreferences:x,setQueryConfig:h}=s.useEditorActions(),[p,b]=xs("chart-section-active",null),f=k.useMemo(()=>p?[p,...Fs.filter(w=>w!==p)]:Fs,[p]);function j(w){m(null),i({}),o(w),["custom","map"].includes(w)&&(u(!0),h(void 0)),n(w),r(!1)}function N(w){m(null),i({}),o("custom"),x({type:"component",visualType:"single",url:w.url,componentName:w.name,icon:w.icon,pluginChartType:w.chartType}),h(void 0),n("custom"),r(!1)}const C=()=>{var D;if(t==="custom"){const g=s.useEditorStore.getState().card;return((D=g==null?void 0:g.customCardPreferences)==null?void 0:D.componentName)||"Custom Visual"}const w=s.chartTypes.find(g=>g.id===t);return(w==null?void 0:w.label)||"Select chart type"},L=()=>{var D,g;if(t==="custom"){const y=s.useEditorStore.getState().card,v=(D=y==null?void 0:y.customCardPreferences)==null?void 0:D.icon,R=(g=y==null?void 0:y.customCardPreferences)==null?void 0:g.componentName;if(v&&R)return e.jsx(zr,{icon:v,componentName:R});if(R){const S=s.getAutoDetectedChartIcon(R);if(S)return S}return e.jsx(ze,{className:"h-4 w-4"})}const w=s.chartTypes.find(y=>y.id===t);if(w){const y=w.icon;return e.jsx(y,{className:"h-4 w-4"})}return e.jsx(ze,{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:[L(),e.jsx("span",{children:C()})]}),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."}),f.map(w=>{if(w==="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:p==="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 g=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(g,{className:"h-4 w-4"}),e.jsx("span",{children:D.label})]})},D.id)})},"default");if(w==="standardPlugin"){const D=l.filter(g=>g.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:p==="standardPlugin",onCheckedChange:g=>b(g?"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(g=>g.componentType==="chart").map((g,y)=>e.jsx(Ls,{pluginVisual:g,index:y,onSelect:()=>N(g)},`${g.url}-${g.name}-${y}`))},"standardPlugin"):null}if(w==="customPlugin"){const D=l.filter(g=>g.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:p==="customPlugin",onCheckedChange:g=>b(g?"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((g,y)=>e.jsx(Ls,{pluginVisual:g,index:y,onSelect:()=>N(g)},`${g.url}-${g.name}-${y}`))},"customPlugin"):null}return null})]})]})})]})})}const zr=({icon:t,componentName:n})=>{const a=Je(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(ze,{className:"h-4 w-4"})},Ur=[{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 _r({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(c=>c.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:Ur.map(c=>{if(c.requiresPivot&&!r)return null;const d=c.icon,o=t===c.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(c.id),className:s.cn("h-8 w-8 p-0",o&&"bg-accent text-accent-foreground"),children:[e.jsx(d,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:c.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:c.label})})]},c.id)})})}const ps=({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(qe,{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(rs,{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($s,{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(qe,{className:"h-3 w-3"})})};function Gr({aliasTemplate:t,onAliasTemplateChange:n}){var i;const[a,r]=k.useState(t),[l,c]=k.useState(!1),d=(i=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:i[0],o=d?`e.g. Min Sales in {{${d.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:o,value:l?a:t,onChange:u=>{r(u.target.value),c(!0)},onFocus:()=>c(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&a!==t?(n(a),c(!1)):u.key==="Escape"&&(r(t),c(!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),c(!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),c(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function $r({valueAliases:t,onValueAliasesChange:n}){const[a,r]=k.useState(null),[l,c]=k.useState(""),[d,o]=k.useState(""),i=()=>{n({...t,"":""})},u=x=>{const h={...t};delete h[x],n(h)},m=x=>{const h={...t};delete h[x],h[l]=d,n(h),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(([x,h],p)=>e.jsx("div",{className:"flex items-center gap-2",children:a===x?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>c(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(x):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:d,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(x):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(x),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:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),c(x),o(h)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),c(x),o(h)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(x),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},x+p)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:i,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Yr({column:t}){const n=s.useEditorStore(i=>i.card.type),a=s.useEditorStore(i=>{var u,m;return(m=(u=i.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(a==null?void 0:a.map(i=>i.label))||[],l=r==null?void 0:r.find(i=>i===t.label||i===t.name),c=l?r.indexOf(l):-1;function d(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(St,{idx:c,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function o(){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(wt,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&d(),["pie","doughnut"].includes(n)&&o()]})}function qr({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),c=s.useEditorStore(u=>u.card),d=c==null?void 0:c.dataSource,o=["attribute-values",t.entityName,t.name,n,a],i=s.useQuery({queryKey:o,queryFn:async()=>{if(!(d!=null&&d.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:d.connectionId,cardConfig:u,cardDataSource:d,cache_config:s.getCacheConfig({card:c})};console.log("requestBody",m);const x=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(x!=null&&x.error)return console.error("Error fetching attribute values:",x.error),[];const h=t.name;return((x==null?void 0:x.records)||[]).map(b=>{const f=b[h]||b[t.alias||h]||b[t.label];return{id:f||"",value:f||"",label:String(f||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(d!=null&&d.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:i.data||[],isLoading:i.isLoading,isFetching:i.isFetching,isError:i.isError,error:i.error,refetch:i.refetch}}function Kr({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:c}){var L,A;const d=!!l,[o,i]=k.useState(d?"values":"fields"),[u,m]=k.useState(""),[x,h]=k.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]:[]}),p=a.filter(w=>{var g;return d?!1:!((g=r==null?void 0:r.conditions)==null?void 0:g.some(y=>y.field.id===w.id))&&w.label.toLowerCase().includes(u.toLowerCase())}),b=w=>{h({...x,field:w}),i("values")},f=()=>{if(x.field&&x.selectedValues.length>0){const w={id:x.id,field:x.field,operator:"in",value:x.selectedValues};let D;if(d){const g=((r==null?void 0:r.conditions)||[]).map(y=>y.id===l.id?w:y);D={...r,conditions:g}}else{const g=(r==null?void 0:r.conditions)||[];D={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...g,w],groups:[]}}c(D),n(!1)}},j=()=>{if(!d||!l)return;const w=((r==null?void 0:r.conditions)||[]).filter(D=>D.id!==l.id);if(w.length>0){const D={...r,conditions:w};c(D)}else c(void 0);n(!1)},N=w=>{h({...x,selectedValues:w})},C=()=>{d&&l?(h({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),i("values")):(h({id:s.v4(),field:null,selectedValues:[]}),i("fields")),m("")};return k.useEffect(()=>{t&&C()},[t,d,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:d?`Edit Filter: ${(L=x.field)==null?void 0:L.label}`:o==="fields"?"Select Field to Filter":`Select Values for ${(A=x.field)==null?void 0:A.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!d&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&o==="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(w=>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:[w.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(w.value)?`${w.value.length} values`:String(w.value)})]},w.id))})]}),o==="fields"&&!d?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:w=>m(w.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:p.map(w=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(w),children:[e.jsx(ps,{dataType:s.getDataType(w.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:w.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[w.entityName,".",w.name]})]})]},w.id))}),p.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),p.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(Qr,{field:x.field,selectedValues:x.selectedValues,onValuesChange:N,onBack:d?void 0:()=>i("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:d?e.jsx(s.Button,{variant:"destructive",onClick:j,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:C,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:f,disabled:!x.field||x.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Qr({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,c]=k.useState(""),{values:d,isLoading:o,isFetching:i}=qr({field:t,searchQuery:l,limit:500}),u=l?d.filter(h=>String(h.value).toLowerCase().includes(l.toLowerCase())):d,m=h=>{const p=n.includes(h);a(p?n.filter(b=>b!==h):[...n,h])},x=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(h=>h.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:h=>c(h.target.value),className:"pl-10"})]}),o||i?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:x}),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(h=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(h.value),children:[e.jsx(s.Checkbox,{checked:n.includes(h.value),onCheckedChange:()=>m(h.value)}),e.jsx(ms,{className:"text-sm",children:h.label})]},h.id))})]})]})}function Hr({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:c=!1,cardType:d}){var gs,js,bs,vs;const{attributes:o,listeners:i,setNodeRef:u,transform:m,transition:x,isDragging:h}=s.useSortable({id:t.id}),p=s.useEditorStore($=>$.card),{updateLabel:b,handleAggregationChange:f,handleDateFormatChange:j,handleGranularityChange:N,handleAliasTemplateChange:C,handleValueAliasesChange:L,removeField:A,handleKpiComparisonTypeChange:w,handleKpiShowTrendlineChange:D,handleKpiTrendlineWindowChange:g,handleKpiTrendlineGranularityChange:y,handleKpiTargetValueChange:v}=ds(p),[R,S]=k.useState(!1),[F,I]=k.useState(!1),[T,M]=k.useState(null),[O,E]=k.useState(t.dateFormat||"YYYY-MM-DD"),[P,B]=k.useState(t.customFormat||""),[Y,q]=k.useState(!!t.customFormat),[z,J]=k.useState(t.granularity||"day"),[W,se]=k.useState(t.aliasTemplate||""),[te,oe]=k.useState(t.valueAliases||{}),[Q,_]=k.useState((gs=t.parameters)==null?void 0:gs.filters),ae=$=>{$==="custom"?q(!0):(q(!1),E($),n==="groupBy"&&j(a,$,""))},H=$=>{B($),n==="groupBy"&&j(a,"custom",$)},re=$=>{var be;J($);const ge=(be=Z($)[0])==null?void 0:be.value;ge&&!Y&&(E(ge),n==="groupBy"&&j(a,ge,"")),n==="groupBy"&&N(a,$)},ie=$=>{se($),n==="metrics"&&C(a,$)},ue=$=>{oe($),n==="metrics"&&L(a,$)},U=$=>{b(n,a,$)},X=$=>{var fe;if(_($),n==="metrics"){const ge={...t,parameters:{...t.parameters,filters:$}},be=[...((fe=p.config)==null?void 0:fe.metricColumns)||[]];be[a]=ge,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:be})}I(!1)},xe=()=>{A(n,a)},ce={transform:s.CSS.Transform.toString(m),transition:x},K=s.getDataType(t.dataType),G=K==="date",V=d==="kpi",Z=$=>{switch($){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..."}]}},le=Z(z),de=n!=="pivotBy",ne=G&&n==="groupBy"&&(!V||((js=p.config)==null?void 0:js.comparisonType)==="start_vs_end"),me=!V&&G&&n==="groupBy",je=V&&G&&n==="groupBy",Le=V&&n==="metrics"&&((bs=p.config)==null?void 0:bs.comparisonType)==="target",Fe=n==="metrics",Te=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:$=>{$.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}`}),ke=()=>de?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:U,placeholder:"Display label...",type:"text"})]}):null,ee=()=>ne?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:z,onValueChange:re,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($=>e.jsx(s.SelectItem,{className:"text-xs",value:$,children:s.toTitleCase($)},$))})]})]}):null,he=()=>me?e.jsxs(e.Fragment,{children:[ee(),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:ae,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:le.map($=>e.jsx(s.SelectItem,{className:"text-xs",value:$.value,children:$.label},$.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:P,onChange:$=>{$.stopPropagation(),H($.target.value)},onClick:$=>$.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,pe=()=>{var $,fe,ge,be,De;return 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:"Comparison Type"}),e.jsxs(s.Select,{value:(($=p.config)==null?void 0:$.comparisonType)||"none",onValueChange:w,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:"start_vs_end",children:"Start vs End"})]})]})]}),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:((fe=p.config)==null?void 0:fe.showTrendline)||!1,onCheckedChange:D})]})}),((ge=p.config)==null?void 0:ge.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:((be=p.config)==null?void 0:be.trendlineWindow)||30,onChange:Ue=>{const Bt=parseInt(Ue.target.value)||30;g(Bt)},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:((De=p.config)==null?void 0:De.trendlineGranularity)||"day",onValueChange:y,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},Ee=()=>{var $,fe;return Le?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:(($=p.config)==null?void 0:$.targetValue)!==void 0&&((fe=p.config)==null?void 0:fe.targetValue)!==null?String(p.config.targetValue):"",onSave:ge=>{!isNaN(Number(ge))&&ge!==null?v(Number(ge)):v(0)},placeholder:"Enter target value...",type:"text"})]}):null},Ft=()=>Fe?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:$=>{f(a,$)},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"}),(Q==null?void 0:Q.conditions)&&Q.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Q.conditions.map($=>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($),I(!0)},children:[e.jsxs("span",{className:"font-medium",children:[$.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($.value)?$.value.length===1?String($.value[0]):$.value.length<=2?$.value.join(", "):`${$.value.slice(0,2).join(", ")} +${$.value.length-2}`:String($.value)})}),Array.isArray($.value)&&$.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 (",$.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:$.value.map((fe,ge)=>e.jsx("div",{children:String(fe)},ge))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:fe=>{var be;fe.stopPropagation();const ge=Q.conditions.filter(De=>De.id!==$.id);if(ge.length>0){const De={...Q,conditions:ge};X(De)}else if(_(void 0),n==="metrics"){const De={...t,parameters:{...t.parameters,filters:void 0}},Ue=[...((be=p.config)==null?void 0:be.metricColumns)||[]];Ue[a]=De,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:Ue})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},$.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{M(null),I(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Yr,{column:t}),c&&e.jsxs(e.Fragment,{children:[e.jsx(Gr,{aliasTemplate:W,onAliasTemplateChange:ie}),e.jsx($r,{valueAliases:te,onValueAliasesChange:ue})]})]}):null,{columns:Ot=[]}=s.useColumns(),Pt=(Q==null?void 0:Q.conditions)&&Q.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:ce,...o,...i,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 ${h?"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(ps,{dataType:K}),e.jsx(ms,{className:s.cn("w-[140px] flex-1 text-sm",Pt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((vs=Q==null?void 0:Q.conditions)==null?void 0:vs.length)&&!R&&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:Q.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Q.conditions.map($=>e.jsxs("div",{children:[$.field.label,":"," ",Array.isArray($.value)?`${$.value.length} values`:String($.value)]},$.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:$=>{$.stopPropagation(),S(!R)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${R?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:$=>{$.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const fe=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",fe),l(fe)},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:$=>{$.stopPropagation(),xe()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),R&&e.jsxs("div",{className:"space-y-3",children:[Te(),ke(),d==="kpi"&&ee(),he(),pe(),Ee(),Ft()]})]}),F&&e.jsx(Kr,{open:F,onOpenChange:$=>{I($),$||M(null)},availableFields:Ot,existingFilters:Q,editingCondition:T,onSave:$=>{var fe;if($)X($);else if(_(void 0),n==="metrics"){const ge={...t,parameters:{...t.parameters,filters:void 0}},be=[...((fe=p.config)==null?void 0:fe.metricColumns)||[]];be[a]=ge,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:be})}M(null)}})]})}function Wr({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 $e({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:c=!1,activeField:d=null}){const{isOver:o,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(j=>j.card),x=s.useEditorStore(j=>j.card.type),h=n.length>0,p=k.useMemo(()=>!d||!o?!0:Ve(d,t,x).isValid,[d,o,t,x]),b=(j,N)=>{var L;!((L=m.config)!=null&&L.sortByColumns)||m.config.sortByColumns.findIndex(A=>A.id===j)===-1||u(m.id,j,{direction:N})};if(t==="sortBy"&&l===!1)return null;const f=t!=="sortBy"&&x!=="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}),f&&e.jsx(Wr,{concept:t})]}),e.jsx("div",{ref:i,className:s.cn("rounded-lg border-2 border-dashed p-1 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":o&&p,"border-red-500 bg-red-50 dark:bg-red-950":o&&!p,"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":!o&&h,"min-h-[60px] border-muted-foreground/20 bg-background":!o&&!h}),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(j=>j.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((j,N)=>{const L=j.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Hr,{field:j,zone:t,index:N,sortDirection:L,onSortDirectionChange:A=>b(j.id,A),hasPivotColumns:c,cardType:x})})},j.id)})})})})]})}const Os=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Jr=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function es({value:t,onChange:n,label:a}){const[r,l]=k.useState(!1),[c,d]=k.useState(!1),o=()=>{const i=Os.find(u=>u.value===t);return i?i.color:t.startsWith("#")?t:Os[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:o()},"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:Jr.map(i=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",o()===i?"border-gray-900":"border-transparent"),style:{backgroundColor:i},onClick:()=>{n(i),l(!1)},children:e.jsx("span",{className:"sr-only",children:i})},i))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{d(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),c&&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:()=>d(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Dt,{color:o(),onColorChange:i=>{n(i),d(!1)},onClose:()=>d(!1)})})]})]})}const Ps={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%
|
|
280
|
+
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 Xr(){var h,p,b,f,j,N,C,L,A,w,D;const t=s.useEditorStore(g=>g.card),{setCardPreferences:n}=s.useEditorActions(),a=((h=t.config)==null?void 0:h.metricColumns)||[],r=((p=t.config)==null?void 0:p.groupByColumns)||[],l=a.length===2&&r.length===0,c=a.length>=1&&r.length>0;if(!(t.type==="kpi"&&(l||c)))return null;const o=((f=(b=t.preferences)==null?void 0:b.kpiVisualOptions)==null?void 0:f.metricComparison)||{},i=g=>{var v;const y={...t.preferences,kpiVisualOptions:{...(v=t.preferences)==null?void 0:v.kpiVisualOptions,metricComparison:{...o,...g}}};n(y)},u=c||o.enabled,m=((j=t.config)==null?void 0:j.comparisonType)||"none",x=m==="previous_period"||m==="same_period_last_year"||m==="start_vs_end";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(Zt,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[l&&a.length===2&&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:g=>i({enabled:g,...g&&!o.calculationType?{calculationType:"difference"}:{}})})]}),u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const g=o.calculationType||"difference",y=Ps[g];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:y==null?void 0:y.label}),e.jsx("p",{children:y==null?void 0:y.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:y==null?void 0:y.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",y==null?void 0:y.example]})]})})()})]})]}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:g=>i({calculationType:g}),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(Ps).map(([g,y])=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:y.label},g))})]})]}),e.jsx(hs,{formatOptions:o.formatOptions||{},onFormatOptionsChange:g=>i({formatOptions:g}),showTitle:!0,title:"COMPARISON FORMAT"}),(x||l)&&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"}),l&&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||"right",onValueChange:g=>i({position:g}),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:"right",className:"text-xs",children:"Right"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:g=>i({showArrow:g})}),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:g=>i({showColor:g})}),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(es,{value:((N=o.colorConfig)==null?void 0:N.increase)||"green",onChange:g=>i({colorConfig:{...o.colorConfig,increase:g}}),label:"Primary > Secondary"}),e.jsx(es,{value:((C=o.colorConfig)==null?void 0:C.decrease)||"red",onChange:g=>i({colorConfig:{...o.colorConfig,decrease:g}}),label:"Primary < Secondary"}),e.jsx(es,{value:((L=o.colorConfig)==null?void 0:L.noChange)||"neutral",onChange:g=>i({colorConfig:{...o.colorConfig,noChange:g}}),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:g=>i({conditionalLabel:g})}),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:((A=o.conditionalLabels)==null?void 0:A.increase)??"Increase",onChange:g=>i({conditionalLabels:{...o.conditionalLabels,increase:g.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:((w=o.conditionalLabels)==null?void 0:w.decrease)??"Decrease",onChange:g=>i({conditionalLabels:{...o.conditionalLabels,decrease:g.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:((D=o.conditionalLabels)==null?void 0:D.noChange)??"No change",onChange:g=>i({conditionalLabels:{...o.conditionalLabels,noChange:g.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:"Previous Label"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:g=>i({labelName:g.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function Zr(){var l,c;const t=s.useEditorStore(d=>d.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((c=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:c.formatOptions)||{},r=d=>{var i;const o={...t.preferences,kpiVisualOptions:{...(i=t.preferences)==null?void 0:i.kpiVisualOptions,formatOptions:d}};n(o)};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(rs,{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(hs,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function el({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,activeField:l}){const c=s.useEditorStore(j=>{var N;return((N=j.card.customCardPreferences)==null?void 0:N.url)&&j.card.type==="custom"}),d=s.useEditorStore(j=>j.card),o=d==null?void 0:d.type,i=t.length>0||a.length>0,u=o!=="kpi"||a.length<=2,m=o!=="kpi",x=o!=="kpi"&&i,h=["pie","doughnut","polar","funnel","aggregateTable"].includes(o),p=m&&!h,b=()=>o==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},f=()=>o==="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:[u&&e.jsx($e,{zone:"groupBy",fields:t,label:b().label,placeholder:b().placeholder,activeField:l}),p&&e.jsx($e,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data",activeField:l}),e.jsx($e,{zone:"metrics",fields:a,label:f().label,placeholder:f().placeholder,hasPivotColumns:n.length>0,activeField:l}),x&&e.jsx($e,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:l})]})]}),!c&&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.Settings2,{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(Zr,{}),e.jsx(Xr,{}),e.jsx(Tt,{}),e.jsx(kt,{}),e.jsx(Et,{}),e.jsx(It,{})]})})]})]})}function sl({onEditJoins:t}){const n=s.useEditorStore(o=>o.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,l=(r==null?void 0:r.joins)||[];if(l.length===0)return null;const c=o=>!o||o.length===0?"No conditions":o.map(i=>{var h,p,b,f;const u=`${(h=i.source)==null?void 0:h.entityName}.${(p=i.source)==null?void 0:p.name}`,m=`${(b=i.target)==null?void 0:b.entityName}.${(f=i.target)==null?void 0:f.name}`,x=i.operator||"=";return`${u} ${x} ${m}`}).join(" AND "),d=o=>!o.joinKeyGroups||o.joinKeyGroups.length===0?"No conditions defined":o.joinKeyGroups.length===1?c(o.joinKeyGroups[0].keys):o.joinKeyGroups.map((i,u)=>({id:u,operator:i.operator,condition:c(i.keys)}));return e.jsx(s.Card,{className:"border-blue-500/30 bg-blue-50/30 dark:bg-blue-950/20",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ya,{className:"size-4 text-blue-600 dark:text-blue-400"}),e.jsx("h3",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Auto-Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:l.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:l.map((o,i)=>{const u=d(o),m=Array.isArray(u);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:o.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:o.target.name})]}),e.jsx(s.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:o.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:m?u.map(x=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:x.condition}),x.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",x.operator,")"]})]},x.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:u})})})]},o.id||i)})})})]})})]}),t&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:t,className:"h-7 gap-1 p-2 text-xs text-blue-700 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(s.SquarePen,{className:"size-3.5"})})]})})}const Bs={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(n){return console.warn(`Failed to read from localStorage (${t}):`,n),null}},setItem(t,n){if(!(typeof window>"u"))try{localStorage.setItem(t,n)}catch(a){console.warn(`Failed to write to localStorage (${t}):`,a)}}};function tl({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:c,activeField:d}){var g,y;const[o,i]=k.useState(()=>Bs.getItem("chart-selector-expanded")==="true"),[u,m]=k.useState(!1),x=s.useEditorStore(v=>v.card),h=s.useEditorStore(v=>v.actions.updateCardConfig),p=a.length>0||r.length>0||l.length>0,{data:b,autoJoinMetadata:f}=s.useDashboardCardQuery(x),j=((g=x==null?void 0:x.config)==null?void 0:g.joinPlan)||(f!=null&&f.autoResolved?f.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),N=((y=x==null?void 0:x.dataSource)==null?void 0:y.selectedEntities)||[],C=v=>{h(x.id,{...x==null?void 0:x.config,joinPlan:v}),m(!1)},L=()=>{h(x.id,{...x==null?void 0:x.config,joinPlan:void 0}),m(!1)},A=()=>{m(!1)},w=()=>{m(!0)};k.useEffect(()=>{Bs.setItem("chart-selector-expanded",String(o))},[o]);const D=()=>{i(v=>!v)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":o}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",o?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:o&&e.jsx(Vr,{selectedChart:t,onChartChange:n})}),e.jsxs("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center gap-1",children:[e.jsx(_r,{selectedChart:t,onChartChange:n}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:D,className:"h-8 w-8 p-0","aria-label":o?"Hide all charts":"Show all charts",children:o?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o?"Hide dropdown":"Show all charts"})})]})]})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsx("div",{className:s.cn("invisible flex gap-2",{visible:p||b}),children:e.jsx(is,{})})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(sl,{onEditJoins:w}),e.jsx(el,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:c,activeField:d})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(ns,{open:u,onOpenChange:m,joinPlan:j,availableDataSources:N,onSave:C,onCancel:A,onRemove:L,children:e.jsx("div",{})})]})}function al({initialFilters:t,availableFields:n}={}){const[a,r]=k.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(w=>w.card.dataSource);const{columns:l,isLoading:c}=s.useColumns(),o=n||l||[],i={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=w=>{const D=g=>{if(g.id===w){const y=o[0]||i,v=s.getDataType(y.dataType)==="date";return{...g,conditions:[...g.conditions,{id:`condition-${Date.now()}`,field:y,operator:v?"between":"=",value:v?[]:""}]}}return{...g,groups:g.groups.map(D)}};r(D(a))},m=w=>{const D=g=>{if(g.id===w){const y=o[0]||i,v=s.getDataType(y.dataType)==="date";return{...g,groups:[...g.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:y,operator:v?"between":"=",value:v?[]:""}],groups:[]}]}}return{...g,groups:g.groups.map(D)}};r(D(a))},x=(w,D)=>{const g=y=>y.id===w?{...y,conditions:y.conditions.filter(v=>v.id!==D)}:{...y,groups:y.groups.map(g)};r(g(a))},h=(w,D)=>{const g=y=>y.id===w?{...y,groups:y.groups.filter(v=>v.id!==D)}:{...y,groups:y.groups.map(g)};r(g(a))},p=(w,D,g,y)=>{if(g==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const v=R=>R.id===w?{...R,conditions:R.conditions.map(S=>S.id===D?{...S,[g]:y}:S)}:{...R,groups:R.groups.map(v)};r(v(a))},b=(w,D,g)=>{const y=v=>v.id===w?{...v,conditions:v.conditions.map(R=>R.id===D?{...R,...g}:R)}:{...v,groups:v.groups.map(y)};r(y(a))},f=(w,D)=>{const g=y=>y.id===w?{...y,logicalOperator:D}:{...y,groups:y.groups.map(g)};r(g(a))},j=(w,D)=>{const g=y=>y.id===w?{...y,negate:D}:{...y,groups:y.groups.map(g)};r(g(a))},N=(w,D,g)=>{const y=v=>v.id===w?{...v,conditions:s.arrayMove(v.conditions,D,g)}:{...v,groups:v.groups.map(y)};r(y(a))},C=(w,D,g)=>{const y=v=>v.id===w?{...v,groups:s.arrayMove(v.groups,D,g)}:{...v,groups:v.groups.map(y)};r(y(a))},L=w=>{if(!w||w.conditions.length===0&&w.groups.length===0)return"-- No filters defined";const D=y=>{let v="";typeof y.field=="object"?v=y.field.entityName?`${y.field.entityName}.${y.field.name}`:y.field.name:v=String(y.field);const R=y.operator;let S=y.value;if(y.field.dataType==="string"&&!["in","not in"].includes(y.operator))typeof S=="string"?S=`'${S}'`:Array.isArray(S)&&(S=`'${S.join(", ")}'`);else if(y.field.dataType==="date"||y.field.dataType==="datetime"||y.field.dataType==="timestamp")if(y.operator==="between"&&Array.isArray(S)&&S.length===2){const F=S[0]?`'${S[0]}'`:"NULL",I=S[1]?`'${S[1]}'`:"NULL";return`${v} BETWEEN ${F} AND ${I}`}else if((y.operator==="in"||y.operator==="not in")&&Array.isArray(S)){const F=S.map(I=>I?`'${I}'`:"NULL").join(", ");return`${v} ${R} (${F})`}else typeof S=="string"||S instanceof Date?S=`'${S}'`:Array.isArray(S)&&S.length>0&&(S=`'${S[0]}'`);else if(["in","not in"].includes(y.operator)){let F=[];Array.isArray(S)?F=S.map(I=>typeof I=="string"?`'${I}'`:String(I)):typeof S=="string"?F=S.split(",").map(I=>{const T=I.trim();return y.field.dataType==="string"?`'${T}'`:T}):typeof S=="number"&&(F=[String(S)]),S=`(${F.join(", ")})`}switch(R){case"contains":return typeof S=="string"?`${v} LIKE '%${S.replace(/'/g,"")}'`:`${v} LIKE '%${String(S)}'`;case"startsWith":return typeof S=="string"?`${v} LIKE '${S.replace(/'/g,"")}%'`:`${v} LIKE '${String(S)}%'`;case"endsWith":return typeof S=="string"?`${v} LIKE '%${S.replace(/'/g,"")}'`:`${v} LIKE '%${String(S)}'`;case"isNull":return`${v} IS NULL`;case"isNotNull":return`${v} IS NOT NULL`;default:return`${v} ${R} ${S}`}},g=y=>{const v=y.conditions.map(D),R=y.groups.map(T=>g(T)),S=[...v,...R].filter(Boolean);if(S.length===0)return"";const F=S.join(` ${y.logicalOperator} `),I=S.length>1?`(${F})`:F;return y.negate?`NOT ${I}`:I};return g(w)},A=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:o,isLoading:c,addCondition:u,addGroup:m,removeCondition:x,removeGroup:h,updateCondition:p,updateConditionFields:b,updateGroupOperator:f,updateGroupNegate:j,reorderConditions:N,reorderGroups:C,generateSQLPreview:L,hasAnyFilters:A}}function nl({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 rl=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"})}},ll=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function ol({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[c,d]=k.useState(!1),o=k.useMemo(()=>{const i={};return a.forEach(u=>{const m=ll(u);i[m]||(i[m]={}),i[m][u.entityId]||(i[m][u.entityId]=[]),i[m][u.entityId].push(u)}),i},[a]);return e.jsxs(s.Popover,{modal:!0,open:c,onOpenChange:d,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(nl,{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(o).map(([i,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"}),i]}),children:Object.entries(u).map(([m,x])=>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:[rl(x[0].entityType),e.jsx("span",{children:x[0].entityName})]}),x.map((h,p)=>e.jsxs(s.CommandItem,{value:h.id,onSelect:()=>{n(h),d(!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)===h.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:h.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:h.description&&e.jsx("span",{children:h.description})})]})]},h.id+p))]},`${i}-${m}`))},i))})]})})]})}function fs(t){var f;const n=s.useEditorStore(j=>j.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(j=>j.card.config),c=l==null?void 0:l.joinPlan,d={...t,alias:t.name,label:"value",role:"groupby"},o={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...d,role:"sortby",direction:"asc"},u={joinPlan:c,groupByColumns:[d],metricColumns:[o],sortByColumns:[i]},m=((f=n.dataSource)==null?void 0:f.connectionId)||n.connectionId,{data:x,isPending:h,error:p}=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:((x==null?void 0:x.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:h,error:p}}function il({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[c,d]=ss.useState(!1),{filterValues:o}=fs(t),i=m=>{a(n.filter(x=>x!==m))},u=m=>{n.includes(m)?a(n.filter(x=>x!==m)):a([...n,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:c,onOpenChange:d,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,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 x=o.find(h=>h.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[x==null?void 0:x.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:h=>{h.key==="Enter"&&i(m)},onMouseDown:h=>{h.preventDefault(),h.stopPropagation()},onClick:h=>{h.stopPropagation(),i(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:o.map((m,x)=>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+x))})]})]})})]})})}function cl({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:c,isPending:d,error:o}=fs(t);return d?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..."]}):o?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:c.map((i,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:i.value,children:i.label},i.value+u))})]})}function dl({value:t,operator:n,onChange:a,className:r}){var i;const{tokenProps:l}=s.useSemaphorContext(),c=(i=l==null?void 0:l.params)==null?void 0:i.timeZone,d=k.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]),o=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:d,onChange:o,timezone:c,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const ul=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ml=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],hl=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],xl=["=","!=","isNull","isNotNull"],pl=["between","isNull","isNotNull"],fl={"=":"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","not between":"Not Between"};function Vs(t){return fl[t]||s.titleCase(t)}function gl(t){switch(t){case"string":return ml;case"number":return hl;case"boolean":return xl;case"date":return pl;default:return ul}}function At({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:c,onUpdateGroupOperator:d,availableFields:o,updateConditionFields:i}){const{attributes:u,listeners:m,setNodeRef:x,transform:h,transition:p,isDragging:b}=s.useSortable({id:t.id}),{isPending:f,error:j}=fs(t.field),N={transform:s.CSS.Transform.toString(h),transition:p};return e.jsxs("div",{ref:x,style:N,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:C=>d(a,C),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(ol,{value:t.field,onValueChange:C=>{const L=C,A=s.getDataType(L.dataType)==="date";i(a,t.id,{field:L,value:"",operator:A?"between":"="})},availableFields:o,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:C=>{C==="in"||C==="not in"?i(a,t.id,{operator:C,value:[]}):C==="isNull"||C==="isNotNull"?i(a,t.id,{operator:C,value:null}):i(a,t.id,{operator:C,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Vs(t.operator):""})}),e.jsx(s.SelectContent,{children:gl(s.getDataType(t.field.dataType)).map(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C,children:Vs(C)},C))})]}),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"?f?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(il,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(C=>typeof C=="string")?t.value:[],onChange:C=>i(a,t.id,{value:C}),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:C=>i(a,t.id,{value:C.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(cl,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:C=>i(a,t.id,{value:C}),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:C=>i(a,t.id,{value:C==="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(dl,{value:t.value,operator:t.operator,onChange:C=>i(a,t.id,{value:C}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:C=>l(a,t.id,"value",C.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:()=>c(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function jl({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:c,onUpdateCondition:d,onUpdateField:o,onRemoveCondition:i,onReorderConditions:u,onReorderGroups:m,onAddCondition:x,onAddGroup:h,availableFields:p,renderFilterGroup:b,updateConditionFields:f}){const{attributes:j,listeners:N,setNodeRef:C,transform:L,transition:A,isDragging:w}=s.useSortable({id:t.id}),D={transform:s.CSS.Transform.toString(L),transition:A},g=v=>{const{active:R,over:S}=v;if(S&&R.id!==S.id){const F=t.conditions.findIndex(T=>T.id===R.id),I=t.conditions.findIndex(T=>T.id===S.id);F!==-1&&I!==-1&&u(t.id,F,I)}},y=v=>{const{active:R,over:S}=v;if(S&&R.id!==S.id&&a){const F=t.groups.findIndex(T=>T.id===R.id),I=t.groups.findIndex(T=>T.id===S.id);F!==-1&&I!==-1&&m(a,F,I)}};return e.jsxs("div",{ref:C,style:D,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${w?"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,...N,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:v=>r(t.id,v),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&&c(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:g,children:e.jsx(s.SortableContext,{items:t.conditions.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((v,R)=>e.jsx(At,{condition:v,index:R,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:d,onUpdateField:o,onRemoveCondition:i,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:f},v.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:y,children:e.jsx(s.SortableContext,{items:t.groups.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(v=>b(v,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:()=>x(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:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function bl({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:c,availableFields:d,isLoading:o,addCondition:i,addGroup:u,removeCondition:m,removeGroup:x,updateCondition:h,updateConditionFields:p,updateGroupOperator:b,updateGroupNegate:f,reorderConditions:j,reorderGroups:N,generateSQLPreview:C,hasAnyFilters:L,setCurrentFilters:A}=al({initialFilters:t,availableFields:n}),w=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[D,g]=k.useState(!1),y=(S,F,I)=>{const T=M=>M.id===S?{...M,conditions:M.conditions.map(O=>O.id===F?{...O,field:I,dataType:I.dataType}:O)}:{...M,groups:M.groups.map(T)};A(T(c))},v=(S,F=0,I)=>F===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:w,collisionDetection:s.closestCenter,onDragEnd:T=>{const{active:M,over:O}=T;if(O&&M.id!==O.id){const E=S.conditions.findIndex(B=>B.id===M.id),P=S.conditions.findIndex(B=>B.id===O.id);E!==-1&&P!==-1&&j(S.id,E,P)}},children:e.jsx(s.SortableContext,{items:S.conditions.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:S.conditions.map((T,M)=>e.jsx(At,{condition:T,index:M,groupId:S.id,groupLogicalOperator:S.logicalOperator,onUpdateCondition:h,onUpdateField:y,onRemoveCondition:m,onUpdateGroupOperator:b,availableFields:d,updateConditionFields:p},T.id))})}),e.jsx(s.DndContext,{sensors:w,collisionDetection:s.closestCenter,onDragEnd:T=>{const{active:M,over:O}=T;if(O&&M.id!==O.id){const E=S.groups.findIndex(B=>B.id===M.id),P=S.groups.findIndex(B=>B.id===O.id);E!==-1&&P!==-1&&N(S.id,E,P)}},children:e.jsx(s.SortableContext,{items:S.groups.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:S.groups.map(T=>v(T,F+1,S.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:()=>i(S.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(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},S.id):e.jsx(jl,{group:S,depth:F,parentGroupId:I,onUpdateGroupOperator:b,onUpdateGroupNegate:f,onRemoveGroup:x,onUpdateCondition:h,onUpdateField:y,onRemoveCondition:m,onReorderConditions:j,onReorderGroups:N,onAddCondition:i,onAddGroup:u,availableFields:d,renderFilterGroup:v,updateConditionFields:p},S.id),R=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:[o?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..."})]}):v(c),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:S=>g(S)}),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)"})]})}),L&&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:C(c)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),R>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(L?c:null),children:"Apply Filters"})]})]})}function vl({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:c,onOpenChange:d}){const o=u=>{a(t,u),d(!1)},i=()=>{r(t),d(!1)};return e.jsxs(s.Dialog,{modal:!1,open:c,onOpenChange:d,children:[c&&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(bl,{filters:n,availableFields:l,onSave:o,onCancel:()=>d(!1),onClearAll:i})]})]})}function yl({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var j,N;const[l,c]=k.useState(null),d=s.useEditorStore(C=>C.card),o=s.useEditorStore(C=>C.actions.updateCardConfig),i=(j=d==null?void 0:d.config)==null?void 0:j.joinPlan,u=(N=d==null?void 0:d.dataSource)==null?void 0:N.semanticDomainId,{data:m}=cs(u),x=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],h=k.useCallback(C=>C.startsWith("card-")?null:C.startsWith("source-")||n.find(L=>L.id===C)?"source":a("groupBy").find(L=>L.id===C)?"groupBy":a("metrics").find(L=>L.id===C)?"metrics":a("pivotBy").find(L=>L.id===C)?"pivotBy":a("sortBy").find(L=>L.id===C)?"sortBy":null,[n,a]),p=k.useCallback(C=>{c(C.active.id)},[]),b=k.useCallback(C=>{var v;const{active:L,over:A}=C;if(!A||!t){c(null);return}const w=L.id,D=A.id,g=h(w),y=h(D)||D;if(y==="sortBy"){if(g==="source"){const R=n.find(F=>F.id===w);if(!R){c(null);return}if(!(a("groupBy").some(F=>F.name===R.name&&F.qualifiedEntityName===R.qualifiedEntityName)||a("metrics").some(F=>F.name===R.name&&F.qualifiedEntityName===R.qualifiedEntityName))){c(null);return}}else if(g==="pivotBy"){c(null);return}else if(g!=="groupBy"&&g!=="metrics"&&g!=="sortBy"){c(null);return}}if(g==="source"&&y==="sortBy"){const R=[...n].find(T=>T.id===w);if(!R){c(null);return}const S=a("sortBy");if(s.fieldAlreadyExists(R,S)){c(null);return}const F=Ve(R,"sortBy",d.type);if(!F.isValid){s.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),c(null);return}const I=s.getNewField(R,"sortBy",S);c(null),r("sortBy",[...S,I]);return}if(g==="source"&&y!=="source"&&y!=="sortBy"){const R=[...n].find(O=>O.id===w);if(!R){c(null);return}const S=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(S.length>0){const O=S[0].qualifiedEntityName;if(!O){c(null);return}if(O!==R.qualifiedEntityName&&R.qualifiedEntityName)if(u&&(m!=null&&m.joinabilityMap)){if(s.calculateFieldState(R,{joinabilityMap:m.joinabilityMap,selectedFields:S,baseEntityName:(v=i==null?void 0:i.baseEntity)==null?void 0:v.name}).state==="unreachable"){s.showJoinRequiredNotification(),c(null);return}}else{if(!i){s.showJoinRequiredNotification(),c(null);return}if(!s.areEntitiesJoined(O,R.qualifiedEntityName,i)){s.showJoinRequiredNotification(),c(null);return}}}const F=a(y);if(s.fieldAlreadyExists(R,F)){c(null);return}const I=Ve(R,y,d.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),c(null);return}const T=s.getNewField(R,y,F),M=[...F,T];c(null),r(y,M),y==="metrics"&&t&&as(d.type,d.config,o,t,M);return}if(g&&y&&g!=="source"&&y!=="source"&&g!==y){const R=a(g),S=a(y),F=R.find(E=>E.id===w);if(!F){c(null);return}const I=Ve(F,y,d.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),c(null);return}const T=s.getNewField(F,y,S);if(c(null),y==="sortBy"){s.fieldAlreadyExists(F,S)||r(y,[...S,T]);return}const M=R.filter(E=>E.id!==w),O=[...S,T];r(g,M),r(y,O),y==="metrics"&&t&&as(d.type,d.config,o,t,O);return}if(g&&y&&g===y&&g!=="source"){const R=a(g),S=R.findIndex(I=>I.id===w),F=R.findIndex(I=>I.id===D);if(S!==F){const I=s.arrayMove(R,S,F);r(g,I)}}c(null)},[t,n,a,r,h,i,u,m,d.type,o,d.config]),f=l?x.find(C=>C.id===l):null;return{activeId:l,activeField:f,handleDragStart:p,handleDragEnd:b}}function Nl({activeView:t,onViewChange:n}){const a=s.useEditorStore(d=>d.card),{config:r}=k.useContext(s.SemaphorContext).tokenProps,l=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:c}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:d=>n(d),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",c&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:c?"Error":"Info"})]})})}const Cl=[{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 Sl(){var i,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=k.useState(!1),[l,c]=k.useState(""),d=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},o=m=>{const x=m.target.value;c(x),x&&!isNaN(parseInt(x))&&n(t.id,parseInt(x))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:o,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(i=t.config)==null?void 0:i.rowLimit)==null?void 0:u.toString())||"100",onValueChange:d,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:Cl.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function wl({isOpen:t,onClose:n}){const a=Ws(n,{enabled:t}),r=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.url)||""}),l=s.useEditorStore(m=>m.card),c=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.pluginChartType)||""}),d=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.settings)||{}}),{data:o}=s.useDashboardCardQuery(l),{getCard:i}=s.useCustomVisual(r),u=k.useMemo(()=>!r||r.trim()===""?null:i("Chart Settings"),[i,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(k.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(o==null?void 0:o.records)||[],chartType:c,settings:d})})})]})})}function Dl({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:l,activeCard:c,columns:d,columnsLoading:o,columnsError:i}){var Q,_,ae;const u=s.useEditorStore(H=>H.card),m=s.useDashboardStore(H=>H.filterValues);m!=null&&m.length;const{updateCardConfig:x,setCard:h,updateCardInFrame:p,setCardId:b,setShowAIDialog:f}=s.useEditorActions(),{updateCardId:j}=s.useDashboardActions(),[N,C]=k.useState(null),L=s.useEditorStore(H=>H.showAIDialog),A=s.useDashboardStore(H=>H.isVisualEditing),[w,D]=k.useState(!1),[g,y]=k.useState(!1),[v,R]=k.useState(null),{isConsoleMode:S}=s.useDashboardPreferences(),{config:F}=k.useContext(s.SemaphorContext).tokenProps,I=(F==null?void 0:F.showInfoTab)!==!1,T=s.useEditorStore(H=>{var re;return((re=H.card.customCardPreferences)==null?void 0:re.url)&&H.card.type==="custom"}),{data:M,errorMessage:O,isLoading:E,isFetching:P,errorSql:B,pagination:Y,refetch:q}=s.useDashboardCardQuery(c),[z,J]=k.useState(!1);k.useEffect(()=>{P||J(!1)},[P]);const W=(H,re)=>{const ie={...c,paginationConfig:{page:H+1,pageSize:re}};h(ie),p(ie)};function se(){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(u.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(m||{},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 (",d.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:o?"Loading...":i?"Error loading columns":JSON.stringify(d.slice(0,5),null,2)})]})]})]})}const te=H=>{if(!u.config)return;if(!H.length){x(u.id,{...u.config,sortByColumns:[]});return}const re=u.config,ie=H.map(({id:ue,desc:U})=>{var K,G;const X=(K=re.metricColumns)==null?void 0:K.find(V=>V.label===ue),xe=(G=re.groupByColumns)==null?void 0:G.find(V=>V.label===ue),ce=X||xe;return ce?{id:s.getFieldId("sortBy",ce),name:ce.name,dataType:ce.dataType,label:ce.label,qualifiedEntityName:ce.qualifiedEntityName,entityId:ce.entityId,entityName:ce.entityName,entityType:ce.entityType,role:"sortby",direction:U?"desc":"asc"}:null}).filter(ue=>ue!==null);x(u.id,{...re,sortByColumns:ie})},oe=k.useMemo(()=>{var H,re;return(re=(H=u.config)==null?void 0:H.sortByColumns)==null?void 0:re.map(ie=>({id:ie.label,desc:ie.direction==="desc"}))},[(Q=u.config)==null?void 0:Q.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":L&&A}),children:[a&&se(),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"&&L&&e.jsx(bt,{variant:"outline"}),e.jsx(Nl,{activeView:t,onViewChange:n}),e.jsx(s.FilterInfo,{cardId:c.id,cardFilters:(_=c.config)==null?void 0:_.filters,cardFilterCount:s.getFilterCount(((ae=c.config)==null?void 0:ae.filters)||null),onFiltersClick:l}),e.jsx("div",{className:"ml-2",children:e.jsx(Sl,{})}),L&&e.jsx(is,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:E||P,onClick:()=>{J(!0),q()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":z})})}),t==="chart"&&e.jsx(vt,{}),!L&&e.jsx(s.IconButton,{onClick:()=>f(!L),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!w&&T&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>D(!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(yt,{})}),t==="table"&&(M==null?void 0:M.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:(M==null?void 0:M.records)||[],paginationMetadata:Y,onPaginationChange:W,isLoading:E||P,onSortChange:te,sortState:oe})}),t==="info"&&I&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[S&&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:u.id,onSave:H=>{const re=s.sanitizeCardId(H);if(!re){C("Card ID cannot be empty");return}const ie=j(u.id,re);if(ie.success){b(re);const ue={...u,id:re};h(ue),p(ue),C(null),s.ue.success("Card ID updated successfully")}else C(ie.error||"Failed to update Card ID"),s.ue.error(ie.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:u.id,className:"h-5 w-5"})]}),N&&e.jsx("p",{className:"text-xs text-destructive",children:N})]}),O||B?e.jsx(ht,{error:O,errorSql:B,onSendFeedback:()=>{const H=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:c.dataSource,dashboardFilters:m,errorMessage:O,errorSql:B,generatedSql:M==null?void 0:M.sql});R(H),y(!0)}}):e.jsxs(e.Fragment,{children:[(M==null?void 0:M.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(xt,{sql:M==null?void 0:M.sql,error:O,errorSql:B})]})]})})]}),e.jsx(wl,{isOpen:w,onClose:()=>D(!1)}),v&&e.jsx(s.FeedbackDialog,{open:g,onOpenChange:y,feedbackData:v})]})]})}function Tl({activeField:t}){const[n,a]=k.useState(!0);return k.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(ps,{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 kl=()=>{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 El(){var B,Y;const[t,n]=k.useState("chart"),[a,r]=k.useState(!1),[l,c]=k.useState(!1),[d,o]=k.useState(!0),i=s.useEditorStore(q=>q.showAIDialog),u=s.useDashboardStore(q=>q.isVisualEditing),{setCardType:m}=s.useEditorActions(),x=s.useEditorStore(q=>q.card.type);k.useEffect(()=>kl(),[]);const h=q=>{m(q)},p=s.useEditorStore(q=>q.frame),b=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.activeTabCardId),s.useEditorStore(q=>q.actions.getAvailableFields);const{addCard:f,removeCard:j,updateCard:N,setActiveCard:C,updateFilters:L}=s.useEditorActions(),{columns:A=[],isLoading:w,error:D}=s.useColumns(),g=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),y=b,{getFieldsForContainer:v,setFieldsForContainer:R}=ds(y),{activeField:S,handleDragStart:F,handleDragEnd:I}=yl({activeCardId:p.activeCardId,sourceFields:A,getFieldsForContainer:v,setFieldsForContainer:R}),T=(q,z)=>{z&&L(q,z)},M=q=>{var z;N(q,{config:{...(z=p.cards.find(J=>J.id===q))==null?void 0:z.config,filters:void 0}})},O=A,E=q=>{if(!q)return 0;let z=q.conditions.length;return q.groups.forEach(J=>{z+=E(J)}),z},P=E(((B=y==null?void 0:y.config)==null?void 0:B.filters)||null);return e.jsxs(s.DndContext,{sensors:g,collisionDetection:s.closestCenter,onDragStart:F,onDragEnd:I,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(mt,{isVisible:d,onToggleVisibility:()=>o(!d)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!i&&e.jsx(tl,{selectedChart:x,onChartChange:h,groupByFields:v("groupBy"),pivotByFields:v("pivotBy"),metricsFields:v("metrics"),sortByFields:v("sortBy"),activeField:S}),e.jsx(Dl,{selectedChart:x,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:()=>c(!0),filterCount:P,activeCard:y,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:A,columnsLoading:w,columnsError:D,getFieldsForContainer:v,cards:p.cards,activeCardId:p.activeCardId,addCard:f,setActiveCard:C})]}),!d&&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:()=>o(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),y&&e.jsx(vl,{cardId:y.id,filters:((Y=y.config)==null?void 0:Y.filters)||null,onFiltersChange:T,onClearFilters:M,availableFields:O,isOpen:l,onOpenChange:c}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Tl,{activeField:S||null})})]})}function Il({authToken:t,onSave:n,onClose:a}){const r=k.useRef(null),l=s.useEditorStore(D=>D.showAIDialog),c=s.useEditorStore(D=>D.isDevMode),d=s.useAssistantLayoutStore(D=>D.setFullscreen),o=s.useAssistantLayoutStore(D=>D.setPanelOpen),i=s.useAssistantLayoutStore(D=>D.setContainer),u=s.useAssistantPanel("editor"),m=s.useFullscreenAssistant(),x=s.useAssistantContainer("editor"),h=m==="editor",p=k.useCallback(D=>{i("editor",D)},[i]),{setAuthToken:b}=s.useDashboardActions(),{setShowAIDialog:f,setOnSave:j,setOnClose:N}=s.useEditorActions(),{setActiveAssistantType:C}=s.useAIActions();k.useEffect(()=>{n&&j(n),a&&N(a)},[n,j,a,N]),k.useEffect(()=>{t&&t.accessToken&&b(t)},[t,b]),k.useEffect(()=>{var D,g;l?((D=r.current)==null||D.resize(40),o("editor",!0),C("editor")):((g=r.current)==null||g.resize(0),o("editor",!1),m==="editor"&&d(null),C(null))},[l,o,C,d,m]);function L(D){D<1?(f(!1),o("editor",!1),m==="editor"&&d(null),C(null)):(l||(f(!0),C("editor")),u.isOpen||o("editor",!0))}function A(){return e.jsxs(e.Fragment,{children:[e.jsx(mt,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Lr,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:L,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Rs,{isFullscreen:h,onFullscreenChange:D=>d(D?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!h&&"pointer-events-none")})]})]})}function w(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:s.cn("flex grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(El,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:L,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Rs,{isFullscreen:h,onFullscreenChange:D=>d(D?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!h&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:c?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:A()}):w()})}function Al(){s.useDashboardStore(d=>d.selectedCardId);const t=s.useDashboardStore(d=>d.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(d=>d.actions),a=s.useDashboardStore(d=>d.isVisualEditing),r=s.useDashboardStore(d=>d.actions.updateFrame);function l(d){t&&(r(t,d),n(!1))}function c(){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(Il,{onSave:l,onClose:c})})}function Ml(){ut();const t=s.useDashboardStore(i=>i.selectedSheetId),n=s.useDashboardStore(i=>i.selectedFrameId),a=s.useDashboardStore(i=>i.dashboard),r=s.useDashboardStore(i=>i.actions.getSelectedFrame),{setSelectedFrameId:l}=s.useDashboardActions(),{setCard:c}=s.useEditorActions(),d=s.useEditorStore(i=>i.card.dataSource);return k.useEffect(()=>{var u,m;let i=r();if(!i){const x=(u=a==null?void 0:a.sheets)==null?void 0:u.find(p=>p.id===t),h=(m=x==null?void 0:x.frames)==null?void 0:m[0];h&&(l(h.id),i=h)}if(i){const x=i.cards.find(h=>h.id===i.activeCardId);x&&c(x)}},[r,t,n,a,l,c]),{hasEntities:!!(d!=null&&d.selectedEntities&&d.selectedEntities.length>0)}}function Rl(){const t=s.useDashboardStore(a=>a.actions.setShowFilters),{hasEntities:n}=Ml();return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[e.jsx(s.Label,{className:"px-2 text-base",children:"Dashboard Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),!n&&e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),e.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),n&&e.jsx("div",{className:"flex grow",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(dt,{context:"filter"})})})})]})}function Ll(){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 Fl(){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(Ll,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Rl,{})})]})}function Ol(){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 Mt(){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 Pl=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 Bl({visual:t,isDeleting:n,isDuplicating:a,onAddVisual:r,onOpenVisual:l,onEditDetails:c,onDeleteClick:d,onDuplicateVisual:o,onShareVisual:i,formatDate:u}){var w,D,g,y;const{selectVisual:m}=s.useManagementActions(),x=s.useIsVisualSelected(t.id),h=Pl(t.id),{isConsoleMode:p}=s.useDashboardPreferences(),b=k.useRef(null),[f,j]=k.useState(!1),[N,C]=k.useState(!1);k.useEffect(()=>{a?(j(!0),C(!0)):N&&(j(!1),C(!1))},[a,N]),k.useEffect(()=>{h&&b.current&&b.current.scrollIntoView({behavior:"smooth",block:"center"})},[h]);const L=()=>e.jsx(He,{className:"h-4 w-4"}),A=()=>{m(t),l==null||l(t)};return e.jsx(s.Card,{ref:b,className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",h?"border-purple-500":x&&"border-primary"),onClick:A,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:L()}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",title:t.title||"Untitled Visual",children:t.title||"Untitled Visual"}),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("p",{className:"text-xs text-muted-foreground line-clamp-2",title:t.description||"No description",children:(w=t.description)!=null&&w.trim()?t.description:"No description"})]}),e.jsxs("div",{className:s.cn("invisible ml-2 flex flex-shrink-0 items-center gap-1 transition-opacity duration-150 group-hover:visible",x&&"visible"),onClick:v=>v.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:v=>{v.stopPropagation(),r(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),t.ownership.isOwner&&e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:v=>{v.stopPropagation(),c==null||c(t)},title:"Edit details",children:e.jsx(Ye,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:f,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:v=>{v.stopPropagation(),r(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),l==null||l(t)},children:[e.jsx(Xt,{className:"mr-2 h-3 w-3"}),"Open"]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.preventDefault(),v.stopPropagation(),o(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:v=>{v.stopPropagation(),c==null||c(t)},children:[e.jsx(Ye,{className:"mr-2 h-3 w-3"}),"Edit details"]}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),i(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.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:[(((D=t.ownership.createdBy)==null?void 0:D.type)==="tenant"||((g=t.ownership.createdBy)==null?void 0:g.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:((y=t.ownership.createdBy)==null?void 0:y.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:u(t.lastModified)})]})]})]})]})]})]})},t.id)}function Rt({open:t,resourceLabel:n,initialTitle:a,initialDescription:r="",onClose:l,onSave:c,isSaving:d=!1}){const[o,i]=k.useState(a),[u,m]=k.useState(r??"");k.useEffect(()=>{t&&(i(a),m(r??""))},[t,a,r]);const x=h=>{h.preventDefault();const p=o.trim();p&&c({title:p,description:u.trim()})};return e.jsx(s.Dialog,{open:t,onOpenChange:h=>h?null:l(),children:e.jsx(s.DialogContent,{className:"sm:max-w-md",children:e.jsxs("form",{onSubmit:x,className:"space-y-4",children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{children:["Edit ",n]}),e.jsxs(s.DialogDescription,{children:["Update the title and description for this ",n.toLowerCase(),"."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"resource-title",children:"Title"}),e.jsx(s.Input,{id:"resource-title",value:o,onChange:h=>i(h.target.value),placeholder:`Enter ${n.toLowerCase()} title`,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"resource-description",children:"Description"}),e.jsx(s.Textarea,{id:"resource-description",value:u,onChange:h=>m(h.target.value),placeholder:`Enter ${n.toLowerCase()} description (optional)`,rows:3})]}),e.jsxs(s.DialogFooter,{className:"mt-6 flex justify-end gap-2 sm:justify-end",children:[e.jsx(s.Button,{type:"button",variant:"outline",onClick:l,disabled:d,children:"Cancel"}),e.jsx(s.Button,{type:"submit",disabled:d||!o.trim(),children:d?"Saving...":"Save changes"})]})]})})})}function Vl({open:t,onOpenChange:n,onSubmit:a,isCreating:r}){const[l,c]=k.useState(""),[d,o]=k.useState("");k.useEffect(()=>{t||(c(""),o(""))},[t]);const i=()=>{l.trim()&&a({title:l,description:d})},u=m=>{n(m)};return e.jsx(s.Dialog,{open:t,onOpenChange:u,children:e.jsxs(s.DialogContent,{children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create New Visual"}),e.jsx(s.DialogDescription,{children:"Add a new visual to your library. You can configure it after creation."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",children:"Visual Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:m=>c(m.target.value),disabled:r,onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),i())}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:d,onChange:m=>o(m.target.value),disabled:r})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>u(!1),disabled:r,children:"Cancel"}),e.jsx(s.Button,{onClick:i,disabled:!l.trim()||r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Visual"})]})]})})}function zl(){const[t,n]=k.useState(""),[a,r]=k.useState(!1),[l,c]=k.useState(!1),[d,o]=k.useState(null),[i,u]=k.useState(!1),[m,x]=k.useState(null),[h,p]=k.useState(null),[b,f]=k.useState(null),{selectVisual:j}=s.useManagementActions(),{handleEditLibraryVisual:N,handleAddLibraryVisual:C}=Me(),{resources:L,isLoading:A,isError:w,createResource:D,updateResource:g,deleteResource:y,duplicateResource:v,isCreating:R,isDeleting:S}=s.useVisualManagement(()=>{u(!1),x(null)},_=>{r(!1),_&&(j(_),N(_))});s.useCurrentUserInfo();const F=L.filter(_=>{var ae,H;return((ae=_==null?void 0:_.title)==null?void 0:ae.toLowerCase().includes(t.toLowerCase()))||((H=_==null?void 0:_.description)==null?void 0:H.toLowerCase().includes(t.toLowerCase()))}),I=_=>new Date(_).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),T=_=>{D({title:_.title,description:_.description,isPrivate:!1})},M=_=>{x(_),u(!0)},O=()=>{m&&y(m.id)},{startUpdating:E,stopUpdating:P,isUpdating:B}=s.useResourceUpdateState(),Y=(_,ae,H)=>{var U;const re=Object.fromEntries(Object.entries(ae).filter(([,X])=>X!==void 0));if(Object.keys(re).length===0){(U=H==null?void 0:H.onSuccess)==null||U.call(H);return}const ie=Object.keys(re),ue=ie.length===1?ie[0]:void 0;E(_,ue),g({resourceId:_,data:re},{onSuccess:()=>{var X;P(_,ue),(X=H==null?void 0:H.onSuccess)==null||X.call(H)},onError:()=>{var X;P(_,ue),(X=H==null?void 0:H.onError)==null||X.call(H)}})},q=_=>{p(_),v(_,{onSettled:()=>p(null)})},z=_=>{N(_)},J=_=>{C(_)},W=_=>{const ae=L.find(H=>H.id===_);ae&&g({resourceId:_,data:{isPrivate:!ae.isPrivate}})},se=_=>{o(_),c(!0)},te=_=>{f(_)},oe=()=>{f(null)},Q=({title:_,description:ae})=>{if(!b)return;const H={};_!==b.title&&(H.title=_),(b.description||"")!==ae&&(H.description=ae),Y(b.id,H,{onSuccess:()=>{f(null)}})};return A?e.jsx(Mt,{}):w?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:"relative flex h-full flex-1 flex-col gap-4",children:[L&&L.length>5&&e.jsx("div",{className:"space-y-2",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:_=>n(_.target.value),className:"h-9"})}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-3 overflow-y-auto",children:F.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(He,{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"]})]}):F.map(_=>e.jsx(Bl,{visual:_,onAddVisual:J,onOpenVisual:z,onEditDetails:te,onDeleteClick:M,onDuplicateVisual:q,onTogglePrivacy:W,onShareVisual:se,isDeleting:S,isDuplicating:h===_.id,formatDate:I},_.id))})}),l&&d&&e.jsx(We,{resource:d,resourceType:s.ResourceType.VISUAL,onClose:()=>{c(!1),o(null)}}),b&&e.jsx(Rt,{open:!!b,resourceLabel:"Visual",initialTitle:b.title||"",initialDescription:b.description||"",onClose:oe,onSave:Q,isSaving:B(b.id)}),e.jsx(s.AlertDialog,{open:i,onOpenChange:_=>{!_&&S||(u(_),_||x(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 "',m==null?void 0:m.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:S,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:_=>{_.preventDefault(),_.stopPropagation(),O()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:S,children:[S?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"}),S?"Deleting...":"Delete"]})]})]})}),e.jsx(Vl,{open:a,onOpenChange:r,onSubmit:T,isCreating:R}),e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>r(!0),"aria-label":"Create visual",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function Ul({dashboard:t,isDeleting:n,isDuplicating:a,onLoadDashboard:r,onEditDetails:l,onDeleteClick:c,onDuplicateDashboard:d,onShareDashboard:o,formatDate:i,onDashboardItemClick:u}){var y,v,R,S,F;const{selectDashboard:m}=s.useManagementActions(),x=s.useIsDashboardSelected(t.id),{isConsoleMode:h}=s.useDashboardPreferences(),{currentUser:p,isLoading:b,isError:f}=s.useCurrentUserInfo(),j=!f&&(p==null?void 0:p.type)==="tenant"&&((y=p==null?void 0:p.role)==null?void 0:y.toUpperCase())==="VIEWER",N=b||j,[C,L]=k.useState(!1),[A,w]=k.useState(!1);k.useEffect(()=>{a?(L(!0),w(!0)):A&&(L(!1),w(!1))},[a,A]);const D=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),g=()=>{m(t),r(t.id),u==null||u(t.id)};return e.jsx(s.Card,{className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",x&&"border-primary"),onClick:g,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:D()}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",title:t.title||"Untitled Dashboard",children:t.title||"Untitled Dashboard"}),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("p",{className:"text-xs text-muted-foreground line-clamp-2",title:t.description||"No description",children:(v=t.description)!=null&&v.trim()?t.description:"No description"})]}),e.jsxs("div",{className:"invisible ml-2 flex flex-shrink-0 items-center gap-1 transition-opacity duration-150 group-hover:visible",onClick:I=>I.stopPropagation(),children:[t.permissions.canEdit&&!N&&e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:I=>{I.stopPropagation(),l==null||l(t)},title:"Edit details",children:e.jsx(Ye,{className:"h-3 w-3"})}),!N&&e.jsxs(s.DropdownMenu,{modal:!1,open:C,onOpenChange:L,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:I=>{I.preventDefault(),I.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.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),l==null||l(t)},children:[e.jsx(Ye,{className:"mr-2 h-3 w-3"}),"Edit details"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),o(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:I=>{I.stopPropagation(),c(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:[(((R=t.ownership.createdBy)==null?void 0:R.type)==="tenant"||((S=t.ownership.createdBy)==null?void 0:S.type)==="organization"&&h)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((F=t.ownership.createdBy)==null?void 0:F.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:i(t.lastModified)})]})]})]})]})]})]})},t.id)}function _l({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 Gl(t){const{onLoadDashboard:n,onEditDashboard:a,onDashboardItemClick:r}=t,[l,c]=k.useState(""),[d,o]=k.useState(!1),[i,u]=k.useState(!1),[m,x]=k.useState(null),[h,p]=k.useState(!1),[b,f]=k.useState(null),[j,N]=k.useState(null),[C,L]=k.useState(null),A=s.useManagementStore(K=>K.lastSelectedDashboard),w=s.useManagementStore(K=>K.selectedDashboard),D=s.useManagementStore(K=>K.actions.selectDashboard),g=s.useManagementStore(K=>K.actions.clearSelectedDashboard),{tokenProps:y,id:v}=s.useSemaphorContext(),{permissions:R}=s.useRoleAwareDisplayPreferences(),{onCreateSuccess:S}=s.useDashboardCreation({onDashboardSelect:r}),{resources:F,isLoading:I,isError:T,createResource:M,updateResource:O,deleteResource:E,duplicateResource:P,isCreating:B,isDeleting:Y,refetch:q}=s.useDashboardManagement(()=>{p(!1);const K=b==null?void 0:b.id;f(null),(w==null?void 0:w.id)===K&&(!(y!=null&&y.dashboard_id)&&!v?g():A&&A.id!==K&&D(A))},K=>{o(!1),S(K,q)}),{currentUser:z}=s.useCurrentUserInfo(),J=F.filter(K=>{var G,V;return((G=K==null?void 0:K.title)==null?void 0:G.toLowerCase().includes(l.toLowerCase()))||((V=K==null?void 0:K.description)==null?void 0:V.toLowerCase().includes(l.toLowerCase()))}),W=K=>new Date(K).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),se=K=>{M({title:K.title,description:K.description,isPrivate:!1})},te=K=>{n==null||n(K)},oe=K=>{f(K),p(!0)},Q=()=>{b&&E(b.id)},_=K=>{N(K),P(K,{onSettled:()=>N(null)})},{startUpdating:ae,stopUpdating:H,isUpdating:re}=s.useResourceUpdateState(),ie=(K,G,V)=>{var ne;const Z=Object.fromEntries(Object.entries(G).filter(([,me])=>me!==void 0));if(Object.keys(Z).length===0){(ne=V==null?void 0:V.onSuccess)==null||ne.call(V);return}const le=Object.keys(Z),de=le.length===1?le[0]:void 0;ae(K,de),O({resourceId:K,data:Z},{onSuccess:()=>{var me;H(K,de),(me=V==null?void 0:V.onSuccess)==null||me.call(V)},onError:()=>{var me;H(K,de),(me=V==null?void 0:V.onError)==null||me.call(V)}})},ue=K=>{const G=F.find(V=>V.id===K);G&&O({resourceId:K,data:{isPrivate:!G.isPrivate}})},U=K=>{x(K),z==null||z.type,u(!0)},X=K=>{a==null||a(K.id),L(K)},xe=()=>{L(null)},ce=({title:K,description:G})=>{if(!C)return;const V={};K!==C.title&&(V.title=K),(C.description||"")!==G&&(V.description=G),ie(C.id,V,{onSuccess:()=>{L(null)}})};return I?e.jsx(Mt,{}):T?e.jsx(_l,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[F&&F.length>5&&e.jsx("div",{className:"space-y-2",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:l,onChange:K=>c(K.target.value),className:"h-9"})}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-3 overflow-y-auto",children:J.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:l?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:l?"Try adjusting your search":R.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),R.canCreateDashboards&&!l&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>o(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Dashboard"]})]}):J.map(K=>e.jsx(Ul,{dashboard:K,isDeleting:Y,isDuplicating:j===K.id,onLoadDashboard:te,onEditDetails:X,onDeleteClick:oe,onDuplicateDashboard:_,onTogglePrivacy:ue,onShareDashboard:U,formatDate:W,onDashboardItemClick:r},K.id))})}),i&&m&&e.jsx(We,{resource:m,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{u(!1),x(null)}}),e.jsx(s.AlertDialog,{open:h,onOpenChange:K=>{!K&&Y||(p(K),K||f(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 "',b==null?void 0:b.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:Y,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:K=>{K.preventDefault(),K.stopPropagation(),Q()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:Y,children:[Y?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"}),Y?"Deleting...":"Delete"]})]})]})}),C&&e.jsx(Rt,{open:!!C,resourceLabel:"Dashboard",initialTitle:C.title||"",initialDescription:C.description||"",onClose:xe,onSave:ce,isSaving:re(C.id)}),e.jsx(s.CreateDashboardDialog,{open:d,onOpenChange:o,onSubmit:se,isCreating:B}),R.canCreateDashboards&&e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>o(!0),"aria-label":"Create dashboard",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function Lt({isOpen:t,onClose:n,className:a,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(w=>w.dashboard);const{setDashboard:c,addSheet:d}=s.useDashboardStore(w=>w.actions),{currentUser:o}=s.useCurrentUserInfo(),i=o,{permissions:u}=s.useRoleAwareDisplayPreferences(),x=s.useSelectedDashboard()&&u.canAccessVisuals,h="dashboards",[p,b]=xs("resource-management-active-tab",h),f=x?p:"dashboards",j=l==="overlay",N=Ws(n,{enabled:t&&j}),C=s.cn("flex h-full flex-col border-r bg-background",j?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),L=w=>{},A=w=>{console.log("Editing dashboard:",w)};return e.jsx(s.TooltipProvider,{children:(!j||t)&&e.jsxs("div",{ref:N,className:C,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:i&&e.jsxs(e.Fragment,{children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"flex h-8 w-8 cursor-default items-center justify-center rounded-full bg-primary/10",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:i.name.charAt(0).toUpperCase()})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"ml-2 max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:i.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.email}),i.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(i.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",i.id]})]})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"text-sm font-medium text-foreground",children:i.name})})]})}),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(ua,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:f,onValueChange:x?b:void 0,className:"flex h-9 grow flex-col",children:[x&&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(s.TabsContent,{value:"dashboards",className:"flex-1 px-4 py-4",children:e.jsx(Gl,{onLoadDashboard:L,onEditDashboard:A,onDashboardItemClick:r})}),x&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 px-4 py-4",children:e.jsx(zl,{})})]})})]})})}function $l({showControls:t=!1,showFooter:n=!0,...a}){const r=s.useDashboardStore(h=>h.isDashboardPanelOpen);s.useDashboardStore(h=>h.isVisualEditing);const l=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),c=20,d=20,o=30,i=r,u=k.useRef(null),m=k.useRef(null);k.useEffect(()=>{u.current&&m.current&&(r?(u.current.resize(c),m.current.resize(100-c)):(u.current.resize(0),m.current.resize(100)))},[r]);const{preferences:x}=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:x,children:[e.jsx(Ol,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(vn,{}),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]":i}),defaultSize:i?c:0,minSize:i?d:0,maxSize:i?o:0,children:e.jsx(Lt,{isOpen:r,onClose:()=>l(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{withHandle:i,className:s.cn("w-1",{"w-0":!i})}),e.jsx(s.ResizablePanel,{ref:m,className:"flex min-w-0 flex-1",defaultSize:i?100-c:100,minSize:i?40:100,children:e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(Al,{}),e.jsx(Fl,{})]})})]})]})]})})]})})}exports.AdvancedModeToggle=lt;exports.DashboardPlus=$l;exports.ResourceManagementPanel=Lt;exports.ScheduleDashboard=qs;exports.ShareDialog=We;exports.VisualBadge=at;exports.VisualEditingControls=rt;exports.cleanCard=Ys;exports.getDashbaordStateWithoutData=Ke;
|