react-semaphor 0.0.681 → 0.0.683

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.
@@ -1,4 +1,4 @@
1
- "use strict";const e=require("react/jsx-runtime"),s=require("./index-C47He6vl.js"),A=require("react"),ra=require("react-dom");function la(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 Re=la(A);/**
1
+ "use strict";const e=require("react/jsx-runtime"),s=require("./index-UnDhE_za.js"),A=require("react"),ra=require("react-dom");function la(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 Oe=la(A);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -138,7 +138,7 @@
138
138
  *
139
139
  * This source code is licensed under the ISC license.
140
140
  * See the LICENSE file in the root directory of this source tree.
141
- */const Ie=s.createLucideIcon("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);/**
141
+ */const Me=s.createLucideIcon("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);/**
142
142
  * @license lucide-react v0.453.0 - ISC
143
143
  *
144
144
  * This source code is licensed under the ISC license.
@@ -298,17 +298,17 @@
298
298
  *
299
299
  * This source code is licensed under the ISC license.
300
300
  * See the LICENSE file in the root directory of this source tree.
301
- */const Pe=s.createLucideIcon("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);/**
301
+ */const ze=s.createLucideIcon("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);/**
302
302
  * @license lucide-react v0.453.0 - ISC
303
303
  *
304
304
  * This source code is licensed under the ISC license.
305
305
  * See the LICENSE file in the root directory of this source tree.
306
- */const Se=s.createLucideIcon("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/**
306
+ */const we=s.createLucideIcon("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/**
307
307
  * @license lucide-react v0.453.0 - ISC
308
308
  *
309
309
  * This source code is licensed under the ISC license.
310
310
  * See the LICENSE file in the root directory of this source tree.
311
- */const Ka=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function Qa(){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(qa,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Fa,{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 is(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>ct(c))}})}})}}function ct(t){return{...t,customCfg:Ja(t.customCfg),data:[]}}function Ja(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 Xa(t,n,a,r,l){if(!l)return null;const o=JSON.stringify(a),c=`${t}/v1/lens`;return await s.postRequest(c,l,{name:n,template:o,filterValues:r,operation:"create"})}async function Ds(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:o,isDefault:c,shared:i}=n,d=`${t}/v1/lens`;return await s.postRequest(d,a,{lensId:r,template:l,filterValues:o,isDefault:c,shared:i,operation:"update"})}async function Za(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function en(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),l=s.useDashboardStore(j=>j.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=A.useState(!1),[u,m]=A.useState(!1),h=s.useDashboardStore(j=>j.dashboard),x=s.useDashboardStore(j=>j.filterValues),{authToken:g,tokenProps:b}=s.useSemaphorContext();async function p(){d(!0);const j=is(h),f=await Xa(b.apiServiceUrl,t,j,x,g==null?void 0:g.accessToken);f&&(o([...l||[],f]),c(f.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:j=>{n(j.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:p,disabled:i,children:i?"Creating...":"Add"})})]})]})}function sn(){const[t,n]=A.useState(!1),a=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c,tokenProps:i}=s.useSemaphorContext();async function d(h){o(h)}async function u(h){if(await Za(i.apiServiceUrl,h,c==null?void 0:c.accessToken)){const g=a==null?void 0:a.filter(b=>b.id!==h);l(g||[]),o("original")}}async function m(h){const x=a==null?void 0:a.map(p=>p.id===h.id?{...p,isDefault:!h.isDefault}:{...p,isDefault:!1});l(x||[]);const g={...h,isDefault:!h.isDefault};await Ds(i.apiServiceUrl,g,c==null?void 0:c.accessToken);const b=a==null?void 0:a.find(p=>p.isDefault);if(b&&b.id!==h.id){const p={...b,isDefault:!1};await Ds(i.apiServiceUrl,p,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Ta,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:d,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:x=>{x.preventDefault(),m(h)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:x=>{x.preventDefault(),u(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function tn({iconClassName:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(""),[o,c]=A.useState(!1),i=s.useDashboardStore(h=>h.isDownloadingPdf),{tokenProps:d}=s.useSemaphorContext();async function u(){const h=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl),s.ue.dismiss(h),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",x)}}async function m(){if(!r)return;a(!1),l(""),c(!1);const h=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl,r),s.ue.dismiss(h),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",x)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(s.Lock,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:n,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:h=>l(h.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:h=>{h.key==="Enter"&&r&&m()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:m,disabled:!r,children:"Download"})]})]})})]})}function dt({triggerButtonClassName:t}){const[n,a]=A.useState(!1),r=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.id}),l=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.title}),o=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.sheets}),c=s.useDashboardStore(i=>i.selectedSheetId);return o==null||o.find(i=>i.id===c),r?e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),onClick:()=>a(!0),children:e.jsx(s.Clock,{className:"size-4"})}),e.jsx(s.EmailScheduleDialog,{open:n,onOpenChange:a,dashboardId:r,dashboardName:l})]}):null}function cs({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 ze({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=a.find(u=>u.value===t))==null?void 0:d.label)||t,i=a.filter(u=>u.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>n(u.value),disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function ut({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>a(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(ze,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>a(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function mt({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 ht({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=n.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function xt(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=A.useRef(null);return A.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function we(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function an(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function pt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function nn(t,n,a){const r=pt(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function rn({user:t}){return pt(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 ln({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=an((r==null?void 0:r.type)||""),i=a.some(h=>h.id===t.id),d=a.find(h=>h.id===t.id),u=d?d.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(ze,{currentRole:u,onRoleChange:h=>{o(t.id,n.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:we(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function on({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(Ye,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function cn({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function dn({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((x,g)=>{var f,y;const b=((f=n.find(E=>E.id===x.orgUserId))==null?void 0:f.name)||"Unknown User",p=((y=n.find(E=>E.id===x.orgUserId))==null?void 0:y.type)||"",j=we(x.role,a(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((x,g)=>{var f,y;const b=((f=n.find(E=>E.id===x.tenantUserId))==null?void 0:f.name)||"Unknown User",p=((y=n.find(E=>E.id===x.tenantUserId))==null?void 0:y.type)||"",j=we(x.role,a(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((x,g)=>{const b=we(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((x,g)=>{const b=we(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((x,g)=>{const b=we(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),!i.length&&!d.length&&!u.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var g,b;const m=((g=n.find(p=>p.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((b=n.find(p=>p.id===d.tenantUserId))==null?void 0:b.type)||"",x=we(d.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:x})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=we(d.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var x,g;const u=((x=n.find(b=>b.id===i.tenantUserId))==null?void 0:x.name)||"Unknown User",m=((g=n.find(b=>b.id===i.tenantUserId))==null?void 0:g.type)||"",h=we(i.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=we(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function un({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 mn({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:x,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?a?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(rn,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(ze,{currentRole:n==null?void 0:n.role,onRoleChange:b=>x(t.id,n.role,b),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(ln,{user:t,userShare:n,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:x}),o&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(ze,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:b=>g(t.id,b),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(on,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(cn,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function ft({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),b=s.useShareManagementActions(),p=c||(C=>{const S=m.some(k=>k.id===C),v=h.includes(C);S?b.removeSelectedUser(C):v?b.removeUserFromRemove(C):b.addSelectedUser({id:C,role:"VIEWER"})}),j=i||b.updateSelectedUserRole,f=d||b.addUserToRemove,y=u||((C,S,v)=>{b.addUserToUpdate({id:C,currentRole:S,newRole:v})}),E=l,D=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(E??[]).length,")"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(dn,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(E==null?void 0:E.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===E.length?b.setSelectedUsers([]):b.setSelectedUsers(E.map(C=>({id:C.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===E.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(un,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:E||[]}),!n&&!a&&(E==null?void 0:E.length)>0&&E.map(C=>{const S=t?nn(C,t,o):void 0,v=D.includes(C.id),k=!!S,N=k&&!v,F=m.some(I=>I.id===C.id),T=m.find(I=>I.id===C.id),B=r(C.type);return e.jsx(mn,{user:C,userShare:S,isUserRemoving:v,hasAccess:N,hasAccessFromAPI:k,isSelected:F,selectedUser:T,roleOptions:B,currentUser:o,usersToUpdate:x,handleUserToggle:p,handleRemoveAccess:f,handleUpdateAccess:y,handleUserRoleChange:j},C.id)})]})]})}function Is({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(s.User,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const Ce=()=>[{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 hn({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=Ce().filter(y=>y.value==="VIEWER"||y.value==="EDITOR"||y.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",h=l?l.newRole:m,x=n.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,b=o,p=m==="NONE"||!m,j=y=>{switch(y){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(Ua,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},f=y=>{r(m,y)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!b&&!p?"border-orange-300 bg-orange-50":x?"border-green-300 bg-green-50":b||p?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",x&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),g&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(b||p)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:b||p?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(y=>e.jsxs(s.Button,{variant:h===y.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>f(y.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(y.value),e.jsx("span",{className:"font-medium",children:y.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:y.description})]},y.value))})]})})]})})}function gt({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=p=>p==="OWNER"?"CONTRIBUTOR":p,h=n?{role:u(n.role)}:{role:"NONE"},x=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,g=(p,j)=>{o(p,j)},b=()=>{c()};return e.jsx(hn,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:b,allUsersToUpdate:x,allUsersToRemove:d})}function He(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=A.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading:d,isError:u}=s.useUnifiedUsers(c),m=s.useResourceShares(r,a);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function xn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var _,W;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),x=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),b=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),j=s.useShareOrgWideRole(),f=s.useShareManagementActions(),[y,E]=A.useState("specific_users"),D=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},C=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:v,isLoadingUsers:k}=He({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:D(),tenantId:C()});A.useEffect(()=>{f.setCurrentContext("org-tab"),f.setCurrentMode(y==="all_users"?"allOrgUsers":"specificOrgUsers")},[f,y]);const N=$=>{var Y,K;const X=$;if(E(X),r==null||r(X),f.setCurrentContext("org-tab"),X==="specific_users")f.setCurrentMode("specificOrgUsers");else if(X==="all_users"){f.setCurrentMode("allOrgUsers");const U=(K=(Y=v==null?void 0:v.shares)==null?void 0:Y.orgUsersOnly)==null?void 0:K[0];U&&U.role!==void 0&&f.setOrgWideRole(U.role)}},F=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),T=S.filter($=>x.some(X=>X.id===$.id)),B=$=>{var U,ee;const X=x.some(ne=>ne.id===$),Y=g.includes($),K=(ee=(U=v==null?void 0:v.shares)==null?void 0:U.specificOrgUsers)==null?void 0:ee.some(ne=>ne.orgUserId===$);X?f.removeSelectedUser($):Y?f.removeUserFromRemove($):K||f.addSelectedUser({id:$,role:"VIEWER"})},I=($,X)=>{f.updateSelectedUserRole($,X)},w=$=>{f.addUserToRemove($),f.removeSelectedUser($)},M=$=>{f.removeUserFromRemove($)},L=$=>{f.removeUserFromUpdate($)},O=($,X)=>{f.setOrgWideRole(X)},R=()=>{f.setOrgWideRole((z==null?void 0:z.role)||"NONE")},z=(W=(_=v==null?void 0:v.shares)==null?void 0:_.orgUsersOnly)==null?void 0:W[0];A.useEffect(()=>{y==="all_users"&&z&&z.role!==void 0&&f.setOrgWideRole(z.role)},[y,z,f]);const G=k,Q=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(Is,{shareType:y,onShareTypeChange:N,currentUser:a,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),y==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(cs,{value:u,onChange:m}),e.jsx(ut,{selectedUsers:x,selectedUserObjects:T,onRemove:B,onRoleChange:I,getRoleOptions:Ce}),e.jsx(mt,{usersToRemove:g,allUsers:F,onRemove:M}),e.jsx(ht,{usersToUpdate:b,allUsers:F,onRemove:L,getRoleOptions:Ce}),e.jsx(ft,{existingShares:v,isInitialLoading:G,isSearching:Q,resource:t,onShare:()=>{},getRoleOptions:Ce,allUsers:F,currentUser:a,handleUserToggle:B,handleUserRoleChange:I,handleRemoveAccess:w,handleUpdateAccess:($,X,Y)=>{f.addUserToUpdate({id:$,currentRole:X,newRole:Y})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(gt,{currentUser:a,currentShare:z,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:O,onRemoveAccess:R,allUsersToUpdate:p==="allOrgUsers"&&j!==((z==null?void 0:z.role)||"NONE")?{currentRole:(z==null?void 0:z.role)||"NONE",newRole:j}:null,allUsersToRemove:p==="allOrgUsers"&&(z==null?void 0:z.role)===void 0})})]}):null}function pn(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function fn(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function jt({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:l,currentUser:o,handleGroupToggle:c,handleGroupRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),g=s.useShareManagementActions(),b=l(o==null?void 0:o.type);return a?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):t.length===0?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No groups available to share with"}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Available Groups"}),e.jsx("div",{className:"max-h-[300px] space-y-2 overflow-y-auto rounded-md border p-3",children:t.map(p=>{const j=n==null?void 0:n.find(v=>v.groupId===p.id),f=m.some(v=>v.id===p.id),y=h.includes(p.id),E=x.find(v=>v.id===p.id),D=!!j&&!y;let S=(j==null?void 0:j.role)||"VIEWER";if(f){const v=m.find(k=>k.id===p.id);S=(v==null?void 0:v.role)||"VIEWER"}else E&&(S=E.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",D&&!y?"border border-green-200 bg-green-50":y?"border border-red-200 bg-red-50":f?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(s.Checkbox,{id:`group-${p.id}`,checked:D?!y:f,disabled:!1,onCheckedChange:()=>{D?y?g.removeGroupFromRemove(p.id):d==null||d(p.id):c==null||c(p.id)}}),e.jsxs("label",{htmlFor:`group-${p.id}`,className:"flex cursor-pointer flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:p.name}),p.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-3 w-3 text-blue-600"}):e.jsx(s.Users,{className:"h-3 w-3 text-green-600"}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[p.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",fn(p.type)),children:pn(p.type)}),p.type==="TENANT_GROUP"&&p.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",p.tenantName]})]}),p.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[D&&!y?e.jsx(ze,{currentRole:S,onRoleChange:v=>{j&&v!==j.role&&(u==null||u(p.id,j.role,v))},roleOptions:b,disabled:!1,allowDropdown:!0,className:E?"border-orange-300 bg-orange-100":""}):f&&!D&&e.jsx(ze,{currentRole:S,onRoleChange:v=>i==null?void 0:i(p.id,v),roleOptions:b,disabled:!1}),D&&!y&&!E&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>d==null?void 0:d(p.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),y&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromRemove(p.id),children:"Undo"}),E&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromUpdate(p.id),children:"Cancel"})]})]},p.id)})})]})}function bt({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){if(t.length===0)return null;const o=l();return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",t.length,")"]}),e.jsx("div",{className:"space-y-1",children:t.map(c=>{const i=n.find(d=>d.id===c.id);return i?e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/50 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-4 w-4 text-blue-600"}):e.jsx(s.Users,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm font-medium",children:i.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[i.memberCount," members"]}),i.type==="TENANT_GROUP"&&i.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",i.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ze,{currentRole:c.role,onRoleChange:d=>r(c.id,d),roleOptions:o}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(c.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},c.id):null})})]})}function qs({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var H;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSelectedGroups(),b=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate(),j=s.useShareCurrentMode(),f=s.useShareTenantWideRole(),y=s.useShareAllTenantsRole(),E=s.useShareSelectedTenant(),D=s.useShareManagementActions(),{data:C,isLoading:S}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:v,isLoading:k}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||E),[N,F]=A.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(D.setCurrentContext("tenant-dialog"),D.setCurrentMode("specificTenantUsers")):(D.setCurrentContext("tenant-tab"),D.setCurrentMode("allTenants"))},[D,a==null?void 0:a.type]);const T=P=>{var se,oe,le,ue;F(P);let J;if(P==="specific_tenant_users"?J="specific_users":P==="all_tenant_users"||P==="all_tenants"?J="all_users":P==="groups"?J="groups":J="specific_users",r==null||r(J),P==="groups"?(D.setCurrentContext("group-share"),D.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(D.setCurrentContext("tenant-dialog"),P==="specific_tenant_users"?D.setCurrentMode("specificTenantUsers"):P==="all_tenant_users"&&(D.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&D.setSelectedTenant(a.tenantId))):(D.setCurrentContext("tenant-tab"),P==="specific_tenant_users"?D.setCurrentMode("specificTenantUsers"):P==="all_tenant_users"?D.setCurrentMode("allTenantUsers"):P==="all_tenants"&&D.setCurrentMode("allTenants")),P==="all_tenant_users"){const ce=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.tenantWide)==null?void 0:oe[0];ce&&ce.role!==void 0&&D.setTenantWideRole(ce.role)}else if(P==="all_tenants"){const ce=(ue=(le=w==null?void 0:w.shares)==null?void 0:le.allTenantsOnly)==null?void 0:ue[0];ce&&ce.role!==void 0&&D.setAllTenantsRole(ce.role)}},B=P=>{D.setSelectedTenant(P)},{allUsers:I,existingShares:w,isLoadingUsers:M,isErrorLoadingUsers:L,isLoadingShares:O,isErrorLoadingShares:R}=He({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:E}),z=P=>{var le,ue;const J=m.some(ce=>ce.id===P),se=h.includes(P),oe=(ue=(le=w==null?void 0:w.shares)==null?void 0:le.specificTenantUsers)==null?void 0:ue.some(ce=>ce.tenantUserId===P);J?D.removeSelectedUser(P):se?D.removeUserFromRemove(P):oe||D.addSelectedUser({id:P,role:"VIEWER"})},G=(P,J)=>{D.updateSelectedUserRole(P,J)},Q=P=>{D.addUserToRemove(P),D.removeSelectedUser(P)},_=P=>{D.removeUserFromRemove(P)},W=P=>{D.removeUserFromUpdate(P)},$=(P,J,se)=>{D.addUserToUpdate({id:P,currentRole:J,newRole:se})},X=(P,J)=>{N==="all_tenant_users"?D.setTenantWideRole(J):N==="all_tenants"&&D.setAllTenantsRole(J)},Y=()=>{N==="all_tenant_users"?D.setTenantWideRole("VIEWER"):N==="all_tenants"&&D.setAllTenantsRole("VIEWER")},U=(()=>{var P,J,se,oe;return j==="allTenants"?(J=(P=w==null?void 0:w.shares)==null?void 0:P.allTenantsOnly)==null?void 0:J[0]:j==="allTenantUsers"?(oe=(se=w==null?void 0:w.shares)==null?void 0:se.tenantWide)==null?void 0:oe[0]:null})();A.useEffect(()=>{var P,J,se,oe;if(N==="all_tenant_users"){const le=(J=(P=w==null?void 0:w.shares)==null?void 0:P.tenantWide)==null?void 0:J[0];le&&le.role!==void 0&&D.setTenantWideRole(le.role)}else if(N==="all_tenants"){const le=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:oe[0];le&&le.role!==void 0&&D.setAllTenantsRole(le.role)}},[N,w,D]);const ee=I.filter(P=>m.some(J=>J.id===P.id)),ne=P=>{const J=g.some(le=>le.id===P),se=b.includes(P),oe=re==null?void 0:re.some(le=>le.groupId===P);J?D.removeSelectedGroup(P):se?D.removeGroupFromRemove(P):oe||D.addSelectedGroup({id:P,role:"VIEWER"})},he=(P,J)=>{D.updateSelectedGroupRole(P,J)},ge=P=>{D.addGroupToRemove(P),D.removeSelectedGroup(P)},V=(P,J,se)=>{D.addGroupToUpdate({id:P,currentRole:J,newRole:se})},Z=v.filter(P=>g.some(J=>J.id===P.id)),te=A.useMemo(()=>N!=="groups"?[]:v.filter(P=>P.type!=="TENANT_GROUP"?!1:P.name.toLowerCase().includes(i.toLowerCase())||P.description&&P.description.toLowerCase().includes(i.toLowerCase())),[v,N,i]),re=A.useMemo(()=>{var J,se;const P=((J=w==null?void 0:w.shares)==null?void 0:J.specificGroups)||((se=w==null?void 0:w.shares)==null?void 0:se.groups)||[];return!P||P.length===0?[]:P.filter(oe=>{const le=v.find(ue=>ue.id===oe.groupId);return(le==null?void 0:le.type)==="TENANT_GROUP"})},[w,v]),ie=M||O||N==="groups"&&k,de=L||R,xe=()=>(a==null?void 0:a.type)==="tenant"||N==="all_tenants"||N==="groups"?!0:E&&(N==="specific_tenant_users"||N==="all_tenant_users");return e.jsxs(e.Fragment,{children:[de&&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"})]})}),!de&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Is,{shareType:N,onShareTypeChange:T,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(Gs,{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"&&(N==="specific_tenant_users"||N==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:E||"",onValueChange:B,disabled:S,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:S?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(H=C==null?void 0:C.tenants)==null?void 0:H.map(P=>e.jsx(s.SelectItem,{value:P.id,children:P.name},P.id))})]})]}),xe()?e.jsx(e.Fragment,{children:N==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(cs,{value:i,onChange:u}),e.jsx(ut,{selectedUsers:m,selectedUserObjects:ee,onRemove:P=>z(P),onRoleChange:G,getRoleOptions:Ce}),e.jsx(mt,{usersToRemove:h,allUsers:I,onRemove:_}),e.jsx(ht,{usersToUpdate:x,allUsers:I,onRemove:W,getRoleOptions:Ce}),e.jsx(ft,{existingShares:w,isInitialLoading:!!ie,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Ce,allUsers:I,currentUser:a,handleUserToggle:z,handleUserRoleChange:G,handleRemoveAccess:Q,handleUpdateAccess:$})]}):N==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(cs,{value:i,onChange:u,placeholder:"Search groups..."}),e.jsx(bt,{selectedGroups:g,groupObjects:Z,onRemove:ne,onRoleChange:he,getRoleOptions:Ce}),b.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",b.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),p.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",p.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(jt,{groups:te,existingGroupShares:re,isLoading:k,resource:t,getRoleOptions:Ce,currentUser:a,handleGroupToggle:ne,handleGroupRoleChange:he,handleRemoveAccess:ge,handleUpdateAccess:V})]}):N==="all_tenant_users"||N==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(gt,{currentUser:a,currentShare:U,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:X,onRemoveAccess:Y,allUsersToUpdate:j==="allTenantUsers"&&((U==null?void 0:U.role)===void 0||f!==U.role)||j==="allTenants"&&((U==null?void 0:U.role)===void 0||y!==U.role)?{currentRole:(U==null?void 0:U.role)||"VIEWER",newRole:j==="allTenantUsers"?f:y}:null,allUsersToRemove:j==="allTenantUsers"&&(U==null?void 0:U.role)===void 0||j==="allTenants"&&(U==null?void 0:U.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(N==="specific_tenant_users"||N==="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(Gs,{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 gn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var L,O;const{searchQuery:i,setSearchQuery:d}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),x=s.useShareManagementActions(),[g,b]=A.useState("org_groups"),[p,j]=A.useState(""),{data:f,isLoading:y}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&g==="tenant_groups"}),E=Array.isArray(f)?f:(f==null?void 0:f.tenants)||[],D=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:C,isLoading:S}=s.useShareableGroups(D(),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?p:a==null?void 0:a.tenantId),{existingShares:v}=He({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),k=C.filter(R=>g==="org_groups"&&R.type!=="ORG_GROUP"||g==="tenant_groups"&&R.type!=="TENANT_GROUP"||g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!p||R.tenantId&&R.tenantId!==p)?!1:R.name.toLowerCase().includes(i.toLowerCase())||R.description&&R.description.toLowerCase().includes(i.toLowerCase())),N=((L=v==null?void 0:v.shares)==null?void 0:L.specificGroups)||((O=v==null?void 0:v.shares)==null?void 0:O.groups)||[];A.useEffect(()=>{x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},[x]);const F=R=>{const z=R;b(z),z==="org_groups"&&j(""),r==null||r(z==="org_groups"?"specific_groups":"all_groups"),x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},T=C.filter(R=>u.some(z=>z.id===R.id)),B=R=>{const z=u.some(_=>_.id===R),G=m.includes(R),Q=N==null?void 0:N.some(_=>_.groupId===R);z?x.removeSelectedGroup(R):G?x.removeGroupFromRemove(R):Q||x.addSelectedGroup({id:R,role:"VIEWER"})},I=(R,z)=>{x.updateSelectedGroupRole(R,z)},w=R=>{x.addGroupToRemove(R),x.removeSelectedGroup(R)},M=(R,z,G)=>{x.addGroupToUpdate({id:R,currentRole:z,newRole:G})};return a?e.jsxs(e.Fragment,{children:[e.jsx(Is,{shareType:g,onShareTypeChange:F,currentUser:a,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:e.jsx(s.Building2,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"tenant_groups",label:"Tenant Groups",description:"Share with tenant-level groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]}),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(s.Label,{children:"Select Tenant"}),e.jsxs(s.Select,{value:p,onValueChange:j,disabled:y,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:y?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:E.map(R=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:R.id,children:R.name},R.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!p?e.jsx("div",{className:"rounded-md border border-dashed p-6 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant above to view and share with its groups"})}):e.jsxs(e.Fragment,{children:[e.jsx(cs,{value:i,onChange:d,placeholder:"Search groups..."}),e.jsx(bt,{selectedGroups:u,groupObjects:T,onRemove:B,onRoleChange:I,getRoleOptions:Ce}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",m.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",h.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(jt,{groups:k,existingGroupShares:N,isLoading:S,resource:t,getRoleOptions:Ce,currentUser:a,handleGroupToggle:B,handleGroupRoleChange:I,handleRemoveAccess:w,handleUpdateAccess:M})]})})]}):null}const vt=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedGroups(),c=s.useShareGroupsToRemove(),i=s.useShareGroupsToUpdate(),d=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),h=s.useShareTenantWideRole(),x=s.useShareGroupWideRole(),g=A.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedGroups:o,groupsToRemove:c,groupsToUpdate:i,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}),[t,n,a,r,l,o,c,i,d,u,m,h,x]),b=A.useMemo(()=>j=>s.validateShareData(j),[]),p=A.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!d)return!1}else if(n==="specificTenantUsers")return d?a.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||l.length>0:!0;case"group-share":return n==="specificGroups"?o.length>0||c.length>0||i.length>0:!0}return!1},[t,n,a,r,l,o,c,i,d]);return{buildShareData:g,validateShareData:b,isCurrentStateValid:p,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}};function Hs({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSelectedTenant(),b=s.useShareOrgWideRole(),p=s.useShareAllTenantsRole(),j=s.useShareTenantWideRole(),{buildShareData:f,validateShareData:y,isCurrentStateValid:E}=vt(),D=a||r||l,C=()=>{var F,T,B,I;if(D)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const w=m.length+h.length+x.length;return w===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${w} user${w!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&x.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Update access for ${x.length} user${x.length!==1?"s":""}`:`Update access for ${w} user${w!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const w=d.role;return b===w?"Remove Access":"Update Access"}else if(i==="all_tenants"){const w=(T=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:T[0];if(!w||w.role===void 0)return"Share with All Tenants";const M=w.role;return p===M?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const w=(I=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:I[0];if(!w||w.role===void 0)return"Share with All Tenant Users";const M=w.role;return j===M?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const w=m.length+h.length+x.length;return w===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${w} user${w!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&x.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Update access for ${x.length} user${x.length!==1?"s":""}`:`Update access for ${w} user${w!==1?"s":""}`}return"Share"},S=()=>D||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!E,v=()=>{const F=f();F&&y(F)&&o(F)},k=()=>{var F,T,B,I;if(i==="all_users")if(!d||d.role===void 0){const w=f();w&&y(w)&&o(w)}else{const w=d.role;if(b===w)u==null||u();else{const L=f();if(L&&y(L)){const O={...L,updateAccess:!0};o(O)}}}else if(i==="all_tenants"){const w=(T=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:T[0];if(!w||w.role===void 0){const M=f();M&&y(M)&&o(M)}else{const M=w.role;if(p===M)u==null||u();else{const O=f();if(O&&y(O)){const R={...O,updateAccess:!0};o(R)}}}}else if(i==="all_tenant_users"){const w=(I=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:I[0];if(!w||w.role===void 0){const M=f();M&&y(M)&&o(M)}else{const M=w.role;if(j===M)u==null||u();else{const O=f();if(O&&y(O)){const R={...O,updateAccess:!0};o(R)}}}}},N=()=>{var F,T,B,I;if(i==="all_users"){if(!d||d.role===void 0)return"default";const w=d.role;return b===w?"destructive":"default"}else if(i==="all_tenants"){const w=(T=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:T[0];if(!w||w.role===void 0)return"default";const M=w.role;return p===M?"destructive":"default"}else if(i==="all_tenant_users"){const w=(I=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:I[0];if(!w||w.role===void 0)return"default";const M=w.role;return j===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:D,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||x.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||D,variant:"default",children:[D?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!D&&C()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,disabled:S(),variant:N(),children:[D?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"}),!D&&C()]})]})}function jn({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),h=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),g=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const b=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:j,isCurrentStateValid:f}=vt(),y=n||a||r,E=()=>{if(y)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const N=d.length+u.length+m.length;return N===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${N} user${N!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${N} user${N!==1?"s":""}`}else if(c==="groups"){if(h.length===0&&x.length===0&&g.length===0)return"Select groups to share with";const N=h.length+x.length+g.length;return N===0?"Select groups to share with":h.length>0&&x.length>0?`Update access for ${N} group${N!==1?"s":""}`:x.length>0&&h.length===0&&g.length===0?`Remove access for ${x.length} group${x.length!==1?"s":""}`:h.length>0&&x.length===0&&g.length===0?`Share with ${h.length} group${h.length!==1?"s":""}`:g.length>0&&h.length===0&&x.length===0?`Update access for ${g.length} group${g.length!==1?"s":""}`:`Update access for ${N} group${N!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const N=i.role;return b===N?"Remove Access":"Update Access"}return"Share"},D=()=>y||!t?!0:!f,C=()=>{const N=p();N&&j(N)&&l(N)},S=()=>{const N=p();N&&j(N)&&l(N)},v=()=>{if(!i||i.role==="NONE"){const N=p();N&&j(N)&&l(N)}else{const N=i.role;if(b===N){const T=p();if(T&&j(T)){const B={...T,removeAccess:!0};l(B)}}else{const T=p();if(T&&j(T)){const B={...T,updateAccess:!0};l(B)}}}},k=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:y,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:C,disabled:!t||y,variant:"default",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!y&&E()]})}),c==="groups"&&e.jsx(e.Fragment,{children:(h.length>0||x.length>0||g.length>0)&&e.jsxs(s.Button,{onClick:S,disabled:!t||y,variant:"default",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!y&&E()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:v,disabled:D(),variant:k(),children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!y&&E()]})]})}function bn({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllGroupsShare:d,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const g=()=>{o({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:h,groupsToUpdate:x})},b=()=>m.length>0||h.length>0||x.length>0,p=()=>h.length>0&&m.length===0&&x.length===0?"Remove Access":x.length>0&&m.length===0&&h.length===0?"Update Access":"Share with Groups",j=a||r||l;return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[m.length>0&&e.jsxs("span",{children:[m.length," groups selected"]}),h.length>0&&e.jsxs("span",{className:"ml-2 text-destructive",children:["• ",h.length," to remove"]}),x.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",x.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:j,children:"Cancel"}),e.jsxs(s.Button,{onClick:g,disabled:!b()||j,children:[j&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),p()]})]})]})}function ye(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function ke(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function vn(t,n,a){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=ye(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const x=ye(r,l,u.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(x,{onSuccess:()=>{d()}})}if(m&&m.length>0){const x=ke(r,l,m.map(g=>{var p,j;const b=(j=(p=i==null?void 0:i.shares)==null?void 0:p.specificOrgUsers)==null?void 0:j.find(f=>f.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(x=>{const g=ye(r,l,[{scope:"specific_org_user",orgUserId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=ye(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=ye(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:x}=t;if(m&&m.length>0){const g=ke(r,l,m.map(b=>{var j,f;const p=(f=(j=i==null?void 0:i.shares)==null?void 0:j.specificTenantUsers)==null?void 0:f.find(y=>y.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,tenantId:x,role:(p==null?void 0:p.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const b=ye(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:x,role:g.newRole}]);o(b,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=ye(r,l,u.map(b=>({scope:"specific_tenant_user",tenantUserId:b.id,tenantId:x,role:b.role})));o(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=ke(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=ye(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=ye(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const x=ye(r,l,u.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(x,{onSuccess:()=>{d()}})}if(m&&m.length>0){const x=ke(r,l,m.map(g=>{var p,j;const b=(j=(p=i==null?void 0:i.shares)==null?void 0:p.specificTenantUsers)==null?void 0:j.find(f=>f.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(x=>{const g=ye(r,l,[{scope:"specific_tenant_user",tenantUserId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"group-share":if(t.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:m,groupsToUpdate:h}=t;if(u&&u.length>0){const x=ye(r,l,u.map(g=>({scope:"group",groupId:g.id,role:g.role})));o(x,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(m&&m.length>0){const x=ke(r,l,m.map(g=>({scope:"group",groupId:g,role:"VIEWER"})));c(x,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Removed access from ${m.length} group${m.length!==1?"s":""}`)}})}h&&h.length>0&&h.forEach(x=>{const g=ye(r,l,[{scope:"group",groupId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{var b;d(),(b=n.resetGroupSelections)==null||b.call(n),s.ue.success("Updated access for group")}})})}break}}function yn(t,n,a,r){var u,m,h,x,g,b;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const p=ke(l,o,t.map(j=>{var y,E;const f=(E=(y=i==null?void 0:i.shares)==null?void 0:y.specificTenantUsers)==null?void 0:E.find(D=>D.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,role:(f==null?void 0:f.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()},onError:j=>{console.error("Remove access failed:",j)}})}else{const p=n==="tenant"&&a==="allTenants",j=n==="tenant"&&a==="allTenantUsers";if(p){const f=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(f){const y=ke(l,o,[{scope:"all_tenants_only",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove all-tenants access failed:",E)}})}}else if(j){const f=(x=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:x[0];if(f){const y=ke(l,o,[{scope:"all_tenant_users",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove all-tenant-users access failed:",E)}})}}else{const f=(b=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:b[0];if(f){const y=ke(l,o,[{scope:"org_users_only",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove org-wide access failed:",E)}})}}}}function Nn(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=He({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=A.useCallback(()=>{r.resetUserSelections()},[r]),m=A.useCallback(()=>{r.resetGroupSelections()},[r]),h=A.useCallback(g=>{if(!t)return;const b={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:u,resetGroupSelections:m};vn(g,b,i)},[t,n,a,d,u,m,i]),x=A.useCallback(()=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:u};yn(l,o||"",c||"",g)},[t,n,a,d,u,m,l,o,c]);return{handleShareSubmit:h,handleRemoveAccess:x}}function hs({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var I,w,M,L,O,R,z,G;const{currentUser:o}=s.useCurrentUserInfo(),[c,i]=A.useState("specific_users"),[d,u]=A.useState("specific_users"),[m,h]=A.useState("specific_groups"),x=s.useShareManagementActions(),g=s.useShareSelectedTab(),b=s.useShareCurrentMode(),p=s.useShareResource(),j=s.useRemoveResourceShares(),{handleShareSubmit:f,handleRemoveAccess:y}=Nn(t.id,(Q,_)=>{p.mutate(Q,{..._,onSuccess:()=>{var W;(W=_==null?void 0:_.onSuccess)==null||W.call(_),r==null||r()}})},(Q,_)=>{j.mutate(Q,{..._,onSuccess:()=>{var W;(W=_==null?void 0:_.onSuccess)==null||W.call(_),l==null||l()}})}),E=p.isPending,D=j.isPending,C=p.isPending,{existingShares:S}=He({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:v}=He({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),k=(w=(I=S==null?void 0:S.shares)==null?void 0:I.tenantWide)==null?void 0:w[0],N=(L=(M=v==null?void 0:v.shares)==null?void 0:M.orgUsersOnly)==null?void 0:L[0],F=()=>{if(g==="org")return d;switch(b){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},T=A.useCallback(()=>{x.resetShareState(),a()},[x,a]),B=(o==null?void 0:o.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:T,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(Ye,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:B?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),B?e.jsxs(s.Tabs,{value:g,onValueChange:Q=>{const _=Q;x.setSelectedTab(_),x.resetUserSelections(),x.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-3",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"}),e.jsx(s.TabsTrigger,{value:"groups",children:"Groups"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(xn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:u,isSharing:E,isUpdating:C,isRemoving:D})})}),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(qs,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:Q=>i(Q),isSharing:E,isUpdating:C,isRemoving:D})})}),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(gn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:h,isSharing:E,isUpdating:C,isRemoving:D})})})]}):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(qs,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:Q=>i(Q),isSharing:E,isUpdating:C,isRemoving:D})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:B?g==="org"?e.jsx(Hs,{resource:t,existingShares:v,isSharing:E,isRemoving:D,isUpdating:C,onShare:f,onClose:a,shareTabType:d,currentAllUsersShare:N,onRemoveAccess:y}):g==="tenant"?e.jsx(Hs,{resource:t,existingShares:S,isSharing:E,isRemoving:D,isUpdating:C,onShare:f,onClose:a,shareTabType:F(),currentAllUsersShare:k,onRemoveAccess:y}):e.jsx(bn,{resource:t,existingShares:v,isSharing:E,isRemoving:D,isUpdating:C,onShare:f,onClose:a,shareTabType:m,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(R=(O=v==null?void 0:v.shares)==null?void 0:O.allOrgGroups)==null?void 0:R[0]:(G=(z=S==null?void 0:S.shares)==null?void 0:z.allTenantGroups)==null?void 0:G[0],onRemoveAccess:y}):e.jsx(jn,{resource:t,isSharing:E,isRemoving:D,isUpdating:C,onShare:f,onClose:a,shareTabType:c,currentAllUsersShare:k,onRemoveAccess:y})})]})})}function yt({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(u=>u.selectedFrameId),l=s.useManagementStore(u=>u.selectedVisual),o=s.useEditorStore(u=>u.frame);let c;if(t)c=t;else if(n!==void 0)c=n?"linked":"library";else if(!!!(o!=null&&o.visualId||l!=null&&l.id)&&r)c="local";else if(l&&!r)c="library";else if(o!=null&&o.visualId&&r)c="linked";else if(l!=null&&l.id&&r)c="library";else return null;const i={local:"bg-gray-100 text-gray-700",linked:"bg-purple-100 text-purple-700",library:"bg-blue-100 text-blue-700"},d={local:"Local Visual",linked:"Linked Visual",library:"Library Visual"};return e.jsx("span",{className:s.cn("rounded-full px-2.5 py-0.5 text-xs font-medium",i[c],a),children:d[c]})}const Cn=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},Sn=async(t,n,a)=>{const r=`${t}/management/v1/groups/${a}`,l=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!l.ok){const o=await l.text();throw new Error(o||"Failed to delete group")}},wn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},Dn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,o=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.text();throw new Error(c||"Failed to remove group members")}};function Tn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Cn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:()=>{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 kn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Sn(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})=>wn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members added successfully")},onError:r=>{console.error("Failed to add group members:",r),s.ue.error("Failed to add members",{description:r.message})}})}function In(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Dn(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 An({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=A.useState(""),[o,c]=A.useState(""),[i,d]=A.useState({}),u=Tn(),m=()=>{const x={};return r.trim()?r.length<3?x.name="Group name must be at least 3 characters":r.length>50&&(x.name="Group name must be less than 50 characters"):x.name="Group name is required",o&&o.length>200&&(x.description="Description must be less than 200 characters"),d(x),Object.keys(x).length===0},h=async x=>{if(x.preventDefault(),!m())return;const g={name:r.trim(),description:o.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(g),l(""),c(""),d({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:h,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-name",children:["Group Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(s.Input,{id:"group-name",placeholder:"e.g., Marketing Team, Engineering Squad",value:r,onChange:x=>{l(x.target.value),i.name&&d(g=>({...g,name:""}))},className:i.name?"border-destructive":"",disabled:u.isPending}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-description",children:["Description",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(optional)"})]}),e.jsx(s.Textarea,{id:"group-description",placeholder:"Describe the purpose of this group...",value:o,onChange:x=>{c(x.target.value),i.description&&d(g=>({...g,description:""}))},className:i.description?"border-destructive":"",disabled:u.isPending,rows:3}),i.description&&e.jsx("p",{className:"text-sm text-destructive",children:i.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.length,"/200 characters"]})]}),e.jsx("div",{className:"rounded-lg border bg-muted/50 p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This group will be accessible to users in your workspace. You can add members after creating the group."})]})})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(s.Button,{type:"button",variant:"outline",onClick:()=>{l(""),c(""),d({})},disabled:u.isPending,children:"Clear"}),e.jsx(s.Button,{type:"submit",disabled:u.isPending||!r.trim(),children:u.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),"Create Group"]})})]})]})}function Mn({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,o]=A.useState("members"),[c,i]=A.useState(""),[d,u]=A.useState([]),[m,h]=A.useState([]),{data:x,isLoading:g,refetch:b}=s.useGroupMembers(a.id),p=a.type==="TENANT_GROUP"?"tenant":"organization",{users:j,isLoading:f}=s.useUnifiedUsers({type:p,tenantId:a.tenantId||void 0,active:!0,limit:100}),y=En(),E=In(),D=(x==null?void 0:x.members)||[],C=A.useMemo(()=>new Set(D.map(I=>I.userId)),[D]),S=A.useMemo(()=>j.filter(I=>!C.has(I.id)),[j,C]),v=A.useMemo(()=>{if(!c)return S;const I=c.toLowerCase();return S.filter(w=>{var M,L;return((M=w.name)==null?void 0:M.toLowerCase().includes(I))||((L=w.email)==null?void 0:L.toLowerCase().includes(I))})},[S,c]),k=A.useMemo(()=>{if(!c)return D;const I=c.toLowerCase();return D.filter(w=>{var M,L,O,R;return((L=(M=w.user)==null?void 0:M.name)==null?void 0:L.toLowerCase().includes(I))||((R=(O=w.user)==null?void 0:O.email)==null?void 0:R.toLowerCase().includes(I))})},[D,c]),N=async()=>{if(d.length!==0)try{await y.mutateAsync({groupId:a.id,data:{userIds:d,userType:p==="tenant"?"tenant":"org"}}),u([]),o("members"),b(),r==null||r()}catch(I){console.error("Failed to add members:",I)}},F=async()=>{if(m.length!==0)try{await E.mutateAsync({groupId:a.id,data:{userIds:m}}),h([]),b(),r==null||r()}catch(I){console.error("Failed to remove members:",I)}},T=I=>{u(w=>w.includes(I)?w.filter(M=>M!==I):[...w,I])},B=I=>{h(w=>w.includes(I)?w.filter(M=>M!==I):[...w,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:[D.length," ",D.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=>{o(I),i(""),h([])},className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"members",children:"Current Members"}),e.jsx(s.TabsTrigger,{value:"add",children:"Add Members"})]}),e.jsxs(s.TabsContent,{value:"members",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search members...",value:c,onChange:I=>i(I.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:g?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):k.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:c?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:k.map(I=>e.jsx(Ln,{member:I,selected:m.includes(I.userId),onToggle:()=>B(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:F,disabled:E.isPending,children:E.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Removing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove Selected"]})})]})]}),e.jsxs(s.TabsContent,{value:"add",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search users to add...",value:c,onChange:I=>i(I.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:f?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):v.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.UserPlus,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No available users"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:v.map(I=>e.jsx(Rn,{user:I,selected:d.includes(I.id),onToggle:()=>T(I.id)},I.id))})}),d.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[d.length," user",d.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:N,disabled:y.isPending,children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.UserPlus,{className:"mr-2 h-4 w-4"}),"Add Members"]})})]})]})]})]})})})}function Ln({member:t,selected:n,onToggle:a}){var l,o,c,i;const r=((o=(l=t.user)==null?void 0:l.name)==null?void 0:o.split(" ").map(d=>d[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:((c=t.user)==null?void 0:c.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(i=t.user)==null?void 0:i.email})]})]})}function Rn({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(o=>o[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.email})]})]})}function On({open:t,onOpenChange:n}){const[a,r]=A.useState("groups"),[l,o]=A.useState(""),[c,i]=A.useState(null),[d,u]=A.useState(!1),[m,h]=A.useState(null),{tokenProps:x}=s.useSemaphorContext(),{currentUser:g}=s.useCurrentUserInfo(),b=kn(),p=(g==null?void 0:g.type)==="tenant",j=x==null?void 0:x.tenantId,{groups:f,isLoading:y,refetch:E}=s.useGroups({type:p?"TENANT_GROUP":"all",tenantId:p?j:void 0,includeMembers:!1}),D=f.filter(k=>{var N;return k.name.toLowerCase().includes(l.toLowerCase())||((N=k.description)==null?void 0:N.toLowerCase().includes(l.toLowerCase()))}),C=async()=>{if(m)try{await b.mutateAsync(m.id),h(null),E()}catch(k){console.error("Failed to delete group:",k)}},S=k=>{i(k),u(!0)},v=()=>{r("groups"),E()};return e.jsxs(e.Fragment,{children:[e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-4xl max-h-[80vh]",children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Group Management"]}),e.jsx(s.DialogDescription,{children:"Manage your groups, create new groups, and control group membership"})]}),e.jsxs(s.Tabs,{value:a,onValueChange:r,className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsxs(s.TabsTrigger,{value:"groups",className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4"}),"Groups"]}),e.jsxs(s.TabsTrigger,{value:"create",className:"flex items-center gap-2",children:[e.jsx(s.Plus,{className:"h-4 w-4"}),"Create Group"]})]}),e.jsx(s.TabsContent,{value:"groups",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search groups...",value:l,onChange:k=>o(k.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:y?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(k=>e.jsx(s.Skeleton,{className:"h-24 w-full"},k))}):D.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:D.map(k=>e.jsx(Fn,{group:k,onManageMembers:()=>S(k),onDelete:()=>h(k),currentUserId:g==null?void 0:g.id},k.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(An,{onSuccess:v,tenantId:j,isTenantUser:p})})]})]})}),c&&e.jsx(Mn,{open:d,onOpenChange:u,group:c,onUpdate:()=>E()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>h(null),children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Group"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.name,'"? This action cannot be undone and will remove all members from the group.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:C,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 Fn({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 As(t){const[n,a]=A.useState(null),[r,l]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),a(null)}})()},[t]),n}function Bn(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Pn(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return n}}return t[0].id}async function Ws(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],o=r.getQueryData(l);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const c=s.ue.loading("Loading visual...",{position:"top-center"});try{const i=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!i.ok)throw new Error("Failed to load visual");const d=await i.json();return r.setQueryData(l,d),s.ue.dismiss(c),{data:d,fromCache:!1}}catch(i){throw s.ue.dismiss(c),i}}function Nt(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function zn(t,n){var o,c;const a=(t==null?void 0:t.frameObject)??((o=t==null?void 0:t.visual)==null?void 0:o.frameObject);if(!a)return!1;const r=Nt(a);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(c=r.cards)==null?void 0:c.find(i=>i.id===r.activeCardId);return l?(s.setupEditorWithCard({...n,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function Vn(){var x;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=As(((x=a.customCardPreferences)==null?void 0:x.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),d=s.useEditorStore(g=>g.selectedConnectionId),u=s.useEditorStore(g=>g.isShowingVisual),m=a.sql;return{getUpdatedFrame:A.useCallback(()=>{var f;let g=m;m&&!m.includes("{{")&&(g=Bn(m),t(g));const b=(f=r==null?void 0:r.getState())==null?void 0:f.settings,p={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:u?a.customCfg:null,preferences:a.preferences,...b&&{customCardPreferences:{...a.customCardPreferences,settings:b}}},j=n.cards.map(y=>y.id===a.id?p:y);return{...n,cards:j,activeCardId:Pn(j,n.activeCardId)}},[a,n,u,l,o,c,i,d,t,r,m])}}function Ve(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:g,setSelectedTableName:b,setSelectedDatamodelId:p,setFilterValues:j,setApplyFilters:f}=s.useEditorActions(),{setIsDashboardEditing:y,setIsVisualEditing:E,setSelectedFrameId:D,clearSelectedFrameId:C,addFrame:S,setIsDashboardPanelOpen:v}=s.useDashboardActions(),k=s.useDashboardStore(M=>M.selectedSheetId),N=s.useDashboardStore(M=>M.selectedFrameId),F=s.useDashboardStore(M=>M.dashboard),T=s.useDashboardStore(M=>M.filterValues),B=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),I=A.useCallback(async M=>{try{l(M),C();const{data:L,fromCache:O}=await Ws(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a);if(!zn(L,{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:g,setSelectedTableName:b,setSelectedDatamodelId:p,setFilterValues:j,setApplyFilters:f,setIsDashboardEditing:y,setIsVisualEditing:E,dashboard:F,selectedSheetId:k,selectedFrameId:N,filterValues:T}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:O}}catch(L){return console.error("Error editing visual:",L),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,o,c,y,E,i,d,u,m,h,x,g,b,p,j,f,C,F,k,N,T]),w=A.useCallback(async M=>{var L;try{if(l(M),!k)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:O,fromCache:R}=await Ws(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a),z=(O==null?void 0:O.frameObject)??((L=O==null?void 0:O.visual)==null?void 0:L.frameObject);if(!z)return{success:!1,error:"Visual has no frame data"};const G=Nt(z);if(!(G!=null&&G.cards)||G.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const Q={...G,id:s.v4(),visualId:M.id};return S(k,Q,"end"),y(!0),D(Q.id),v(!1),{success:!0,fromCache:R}}catch(O){return console.error("Error adding visual:",O),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,k,S,y,D,v]);return{visual:B.data,isLoading:B.isLoading,isError:B.isError,error:B.error,handleEditLibraryVisual:I,handleAddLibraryVisual:w,getUpdatedFrame:Vn().getUpdatedFrame,refetch:B.refetch}}function _n({open:t,onOpenChange:n,isLibraryVisual:a,currentVisualName:r,isSaving:l=!1,onConfirm:o}){const[c,i]=A.useState(a&&r?`Copy of ${r}`:r||""),[d,u]=A.useState(""),[m,h]=A.useState(!a),[x,g]=A.useState(!0);A.useEffect(()=>{t&&(i(a&&r?`Copy of ${r}`:r||""),u(""),h(!a),g(!0))},[t,a,r]);const b=()=>{c.trim()&&(!m&&!x||o({name:c.trim(),description:d.trim()||void 0,saveToLibrary:m,saveToCurrentDashboard:x}))},p=c.trim()&&(m||x);return e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Save Visual As"}),e.jsx(s.DialogDescription,{children:a?"Create a copy of this visual with a new name":"Save this visual to make it reusable"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:c,onChange:j=>i(j.target.value),placeholder:"Enter visual name",disabled:l})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Textarea,{id:"description",value:d,onChange:j=>u(j.target.value),placeholder:"Enter visual description",rows:3,disabled:l})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Label,{children:"Save to:"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-dashboard",checked:x,onCheckedChange:j=>g(!!j),disabled:l}),e.jsxs("label",{htmlFor:"save-to-dashboard",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Current Dashboard",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(add copy to this dashboard)":"(keep as local visual)"})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-library",checked:m,onCheckedChange:j=>h(!!j),disabled:l}),e.jsxs("label",{htmlFor:"save-to-library",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Visual Library",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!m&&!x&&e.jsx("p",{className:"text-sm text-destructive",children:"Please select at least one destination"})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),disabled:l,children:"Cancel"}),e.jsxs(s.Button,{onClick:b,disabled:!p||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function Ct({className:t,variant:n="outline"}){var i;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(d=>d.frame);const r=s.useEditorStore(d=>d.card);As(((i=r.customCardPreferences)==null?void 0:i.url)||""),s.useEditorStore(d=>d.selectedSchemaName),s.useEditorStore(d=>d.selectedDatamodelId),s.useEditorStore(d=>d.selectedDatabaseName),s.useEditorStore(d=>d.selectedTableName),s.useEditorStore(d=>d.selectedConnectionId),s.useEditorStore(d=>d.isShowingVisual),r.sql;const l=s.useEditorStore(d=>d.onSave),{getUpdatedFrame:o}=Ve();function c(){const d=o();l==null||l(d)}return e.jsxs(s.Button,{onClick:c,className:s.cn("h-8",t),size:"sm",variant:n,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Un({className:t,variant:n="default"}){const a=s.useQueryClient(),[r,l]=A.useState(!1),o=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),{setIsVisualEditing:c}=s.useDashboardActions(),{getUpdatedFrame:i}=Ve(),d=s.useSelectedVisual(),u=s.useEditorStore(x=>x.frame),m=s.useUpdateVisualMutation(),h=()=>{const x=i(),g=(u==null?void 0:u.visualId)||(d==null?void 0:d.id);if(!g){s.ue.error("No visual to save");return}l(!0),m.mutate({visualId:g,data:{frameObject:x}},{onSuccess:()=>{l(!1),o(!0),s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["resource-by-id","visual",g],exact:!0})},onError:()=>{l(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:n,children:[r&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!r&&e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"mr-2 size-4 font-bold"}),"Save to Library"]})]})}function Gn({className:t}){const n=s.useQueryClient(),[a,r]=A.useState(!1),l=s.useSelectedVisual(),o=s.useEditorStore(x=>x.frame),c=s.useDashboardStore(x=>x.selectedSheetId),{updateFrame:i,setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:u}=Ve(),m=s.useUpdateVisualMutation(),h=async()=>{if(!c){s.ue.error("No sheet selected");return}const x=(o==null?void 0:o.visualId)||(l==null?void 0:l.id);if(!x){s.ue.error("No visual to update");return}r(!0);try{const g=u();await m.mutateAsync({visualId:x,data:{frameObject:g}});const b={...g,visualId:x};i(c,b),n.invalidateQueries({queryKey:["visuals"]}),n.invalidateQueries({queryKey:["visual",x]}),s.ue.success("Saved to library and applied locally"),setTimeout(()=>{d(!1)},300)}catch(g){console.error("Failed to save and apply:",g),s.ue.error("Failed to save and apply changes")}finally{r(!1)}};return e.jsx(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:"default",disabled:a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"mr-2 size-4 font-bold"}),"Save & Apply"]})})}function Yn({className:t}){const{getUpdatedFrame:n}=Ve();s.useEditorStore(d=>d.frame);const a=s.useDashboardStore(d=>d.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[o,c]=A.useState(!1),i=()=>{if(!a){s.ue.error("No sheet selected");return}c(!0);const u={...n(),visualId:void 0};r(a,u),setTimeout(()=>{c(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:i,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function St({className:t}){const{setTempQueryData:n,setSqlGen:a}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),o=s.useEditorStore(u=>u.onClose),c=s.useEditorStore(u=>u.card),{queryKey:i}=s.useDashboardCardQuery(c);function d(){if(l){const{queryKey:u,queryData:m}=l;u&&m&&r.setQueryData(u,m)}a({}),o==null||o()}return e.jsxs(s.Button,{onClick:d,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function xs(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(j=>j.isDevMode),r=s.useEditorStore(j=>j.tempQueryData),l=s.useEditorStore(j=>j.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:x,setCardConfig:g,setCardType:b}=s.useEditorActions();function p(){const j=n.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:j}),n.setQueryData(o,null),n.removeQueries({queryKey:o,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),x(),g(void 0),d(""),u(""),m({}),b("bar")}return e.jsxs(s.Button,{onClick:p,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function $n(){const[t,n]=A.useState(!1),[a,r]=A.useState(!1),[l,o]=A.useState(null),c=s.useEditorStore(D=>D.frame),i=s.useEditorStore(D=>D.card),d=s.useSelectedVisual(),u=s.useDashboardStore(D=>D.selectedSheetId),m=s.useDashboardStore(D=>D.actions.setIsDashboardPanelOpen),{getUpdatedFrame:h}=Ve(),{selectVisual:x}=s.useManagementActions(),{addFrame:g,setSelectedFrameId:b,setIsVisualEditing:p}=s.useDashboardActions(),j=!!(c!=null&&c.visualId),f=(d==null?void 0:d.title)||(i==null?void 0:i.title)||"Untitled Visual",y=s.useCreateVisualWithFrame(D=>{if(D!=null&&D.id){if(x(D),a&&l&&u){const C={...l,id:s.v4(),visualId:D.id};g(u,C,"end"),b(C.id),r(!1),o(null),p(!1)}m(!0),n(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:n,handleSaveAs:async D=>{if(!u){s.ue.error("No sheet selected");return}const C=h();if(D.saveToLibrary){r(D.saveToCurrentDashboard),o(C);const S={title:D.name,description:D.description,frameObject:C,isPrivate:!1};y.mutate(S)}else if(D.saveToCurrentDashboard){const S={...C,id:s.v4(),visualId:void 0,cards:C.cards.map(v=>({...v,title:v.id===i.id?D.name:v.title}))};g(u,S,"end"),b(S.id),s.ue.success("Visual saved to dashboard"),n(!1),p(!1)}},isLibraryVisual:j,currentVisualName:f,isSaving:y.isPending}}function wt({className:t}){const n=s.useEditorStore(y=>y.frame),a=s.useEditorStore(y=>y.card),r=s.useManagementStore(y=>y.selectedVisual),l=s.useDashboardStore(y=>y.selectedFrameId),o=s.useDashboardStore(y=>y.selectedSheetId),{setIsVisualEditing:c}=s.useDashboardActions(),i=!!(n!=null&&n.visualId||r!=null&&r.id),d=!!(n!=null&&n.visualId&&l),u=i&&!d,{saveAsDialogOpen:m,setSaveAsDialogOpen:h,handleSaveAs:x,isLibraryVisual:g,currentVisualName:b,isSaving:p}=$n(),{handleAddLibraryVisual:j}=Ve(),f=async()=>{if(!o){s.ue.error("No dashboard sheet selected");return}if(!r){s.ue.error("No visual selected");return}const y=await j(r);y.success?(s.ue.success("Visual added to dashboard"),c(!1)):s.ue.error(y.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[e.jsx(St,{className:t}),!i&&e.jsx(Ct,{className:t,variant:"default"}),i&&e.jsxs(e.Fragment,{children:[d&&e.jsx(Yn,{className:t}),u&&o&&a&&(a.sql||s.hasValidCardConfig(a.config))&&e.jsxs(s.Button,{onClick:f,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(fa,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),u&&e.jsx(Un,{className:t,variant:"outline"}),d&&e.jsx(Gn,{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:y=>{y.stopPropagation(),h(!0)},children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]})]}),!i&&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:()=>h(!0),children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(_n,{open:m,onOpenChange:y=>{p||h(y)},isLibraryVisual:g,currentVisualName:b,isSaving:p,onConfirm:x})]})}function Dt({className:t,labelClassName:n,switchClassName:a}){const r=s.useEditorStore(d=>d.isDevMode),l=s.useDashboardStore(d=>d.isVisualEditing),{setIsDevMode:o}=s.useEditorActions(),{config:c}=A.useContext(s.SemaphorContext).tokenProps,i=(c==null?void 0:c.showAdvancedMode)!==!1;return!l||!i?null:e.jsxs("div",{className:s.cn("flex items-center space-x-2",t),children:[e.jsx(s.Switch,{className:s.cn("",a),checked:r,onCheckedChange:()=>o(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:s.cn("text-sm font-medium",n),children:"Advanced Mode"})]})}function qn(){var ie,de,xe;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:o}=s.useRoleAwareDisplayPreferences(),c=s.useHasDashboardId();s.useDashboardStore(H=>H.theme);const i=s.useDashboardStore(H=>H.lenses),d=s.useDashboardStore(H=>H.selectedLensId),u=i==null?void 0:i.find(H=>H.id===d),m=s.useDashboardStore(H=>H.dashboard);s.useDashboardStore(H=>H.selectedSheetId);const h=s.useDashboardStore(H=>H.isDashboardEditing),[x,g]=A.useState(!1),[b,p]=A.useState(!1),[j,f]=A.useState(!1),y=s.useDashboardStore(H=>H.isDashboardPanelOpen),E=s.useDashboardStore(H=>H.actions.setIsDashboardPanelOpen),D=s.useDashboardStore(H=>H.filterValues),C=s.useDashboardStore(H=>H.isVisualEditing),S=s.useEditorStore(H=>H.card),v=s.useManagementStore(H=>H.selectedDashboard),k=s.useManagementStore(H=>H.initialDashboard),N=s.useManagementStore(H=>H.selectedVisual);s.useDashboardStore(H=>H.selectedFrameId),s.useEditorStore(H=>H.frame);const F=v?(de=v==null?void 0:v.permissions)==null?void 0:de.canEdit:(ie=k==null?void 0:k.permissions)==null?void 0:ie.canEdit,T=s.useDashboardStore(H=>H.showFilters),B=s.useDashboardStore(H=>H.showDashboardJSON),I=s.useDashboardStore(H=>H.onSaveFunction),w=s.useDashboardStore(H=>H.actions.setShowFilters),{setIsDashboardEditing:M,setShowDashboardJSON:L}=s.useDashboardStore(H=>H.actions),{setInitialDashboard:O,clearSelectedDashboard:R}=s.useManagementStore(H=>H.actions),{resources:z}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:G}=s.useCurrentUserInfo(),Q=s.canUserManageGroups(G),_=v||k,W=_?{id:_.id,title:(m==null?void 0:m.title)||_.title||"Dashboard"}:null,{handleAddNewFrame:$}=s.useAddNewFrame(),[X,Y]=A.useState(!1),K=s.useUpdateResource(s.ResourceType.DASHBOARD);A.useEffect(()=>{if(z&&z.length>0){const H=m==null?void 0:m.id;if(H){const P=z.find(J=>J.id===H);P&&O(P)}}},[z,m==null?void 0:m.id,O]);const U=n.orgUserId||n.tenantId,ee=h&&!C&&U&&F,ne=()=>{M(!0)};async function he(){const H=is(m);Y(!0);const P={template:H};K.mutate({resourceId:H.id,data:P},{onSuccess:()=>{Y(!1),s.ue.success("Dashboard saved!")},onError:()=>{Y(!1),s.ue.error("Failed to save dashboard")}})}async function ge(){if(g(!0),!d||!u)return;const H=is(m),P=JSON.stringify(H),J={...u,template:P,filterValues:D};await Ds(n.apiServiceUrl,J,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),I==null||I(H),g(!1)}const V=(u==null?void 0:u.name)||m.title,te=z&&z.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),re=v&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-11 items-center justify-between gap-2 border-b px-4 py-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[te&&e.jsxs(e.Fragment,{children:[re&&!C&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>R(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:c?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>{c&&E(!y)},className:"h-7 p-2",buttonProps:{disabled:!c},children:e.jsx(Ra,{className:"h-4 w-4"})})]}),!C&&c&&e.jsx(s.Label,{children:V}),C&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm font-medium",children:(N==null?void 0:N.title)||(S==null?void 0:S.title)||"Untitled Visual"}),e.jsx(yt,{})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[C&&e.jsxs(e.Fragment,{children:[e.jsx(Dt,{className:"mr-2"}),e.jsx(wt,{className:"h-7"})]}),r&&!C&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(Ga,{className:"h-4 w-4"})}),!C&&c&&e.jsx(tn,{}),!C&&c&&e.jsx(dt,{}),!C&&c&&Q&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!C&&c&&((xe=_==null?void 0:_.permissions)==null?void 0:xe.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),h&&!C&&U&&r&&c&&e.jsx(en,{}),!C&&U&&r&&c&&e.jsx(sn,{}),h&&!C&&U&&u&&r&&c&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:x,onClick:ge,size:"sm",children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),h&&!C&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!h,onClick:()=>$(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!C&&!h&&o.canEdit&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:ne,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),h&&!C&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{M(!1),L(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),ee&&c&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:X,onClick:he,size:"sm",children:[X?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(qe,{className:"mr-2 h-4 w-4"}),X?"Saving...":"Save"]}),!T&&!C&&h&&o.canUseFilters&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>w(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!C&&h&&r&&c&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>L(!B),size:"sm",variant:"ghost",children:e.jsx($e,{className:"h-4 w-4"})})}),!C&&r&&e.jsx(Qa,{}),b&&W&&e.jsx(hs,{resource:W,resourceType:s.ResourceType.DASHBOARD,onClose:()=>p(!1)}),e.jsx(On,{open:j,onOpenChange:f})]})]})}function Hn({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:u=!1}){const m=Re.useRef(null),[h,x]=Re.useState(!1),[g,b]=Re.useState("100%"),p=u?[...n||[],{id:"none",name:"None"}]:n;Re.useLayoutEffect(()=>{m.current&&b(m.current.offsetWidth)},[]);function j(){var y;return l?"Loading...":o?"Error":a?(y=n==null?void 0:n.find(E=>E.id===a))==null?void 0:y.name:`Select ${t}`}function f(y,E){r(E),x(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:x,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:j()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:g},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(rt,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:p==null?void 0:p.map(y=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:y.name,onSelect:E=>f(E,y.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===y.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:y.name,children:y.name})]})},y.id))})]})]})})]})}function Ge({title:t,items:n,value:a,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":a;function x(){if(t==="Connection")return e.jsx(Va,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Ba,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(xa,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:u,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(rt,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((p,j)=>e.jsx(s.SelectItem,{value:p.id,children:p.name},j))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function b(){return e.jsx(Hn,{icon:x(),items:n,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?g():b()})})}function Wn({column:t}){const[n,a]=A.useState(!1),r=s.useEditorStore(p=>p.selectedTableName),l=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedDatabaseName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(p=>p.actions.setSqlGen),h=s.useEditorStore(p=>p.actions.setCardSql),x=s.useEditorStore(p=>p.actions.setRunSql);function g(p,j){var D;const f=s.createSqlGenConfig(p,i,j),y=(D=d==null?void 0:d.find(C=>C.id===c))==null?void 0:D.name;m(f);const E=s.getSql(f,s.fmt(l||""),s.fmt(r),y||"",u,o||"");E&&(h(E),x(!0)),a(!1)}function b(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>g(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>g(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>g(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>g(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>g(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]})}function Kn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Se,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ie,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Pe,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx($e,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Xe,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ss,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Se,{className:"h-3 w-3"})})}function gs({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",n),children:[e.jsx(Kn,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Qn({id:t,children:n,type:a="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:a}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:n})}function Jn({onClick:t,column:n}){const a=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function u(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(n),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(gs,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(gs,{column:n})}),e.jsx(Qn,{id:n.column_name,type:"column",children:e.jsx(gs,{column:n})})]})}const js={id:"__placeholder__",role:"groupby",type:"string"},bs={id:"__placeholder__",role:"groupby",type:"string"},vs={id:"__placeholder__",role:"metric",type:"number"},ys={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},Tt={id:"__placeholder__"},Oe="droppable-group-by",Fe="droppable-metrics",Be="droppable-pivot-by",ds="sortable-group-by",Ts="sortable-metrics",us="sortable-pivot-by",ks="droppable-filters",Es="sortable-filters",Ms="sortable-order-by";function Xn(){const t=s.useDndStore(w=>w.insertIndex),n=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.groupByColumns)||[]}),a=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.metricColumns)||[]}),r=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.filterColumns)||[]}),l=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.orderBy)||[]}),o=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:x,setMetricColumns:g,setFilterColumns:b,setOrderByColumns:p,setPivotByColumns:j}=s.useEditorActions(),{columns:f}=s.useDataColumns(),{formattedTableName:y}=s.useEditorAside(),E=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),D=w=>{var O;const{active:M,over:L}=w;if(((O=M.data.current)==null?void 0:O.type)==="column"&&L){const R=L.id,z=f.find(W=>W.column_name===M.id);if(!z)return;const G=s.isNumberDataType(z.data_type),Q=s.isTextDataType(z.data_type),_=s.isDateDataType(z.data_type);if(Q||_){if(n.some($=>$.id===R)){const $=n.findIndex(Y=>Y.id===R);c($);const X=n.filter(Y=>Y.id!==js.id);X.splice($,0,js),d(X)}else if(L.id===Oe){c(n.length);const $=[...n,js];d($),u(a),m(r)}}if(Q||_){if(o.some($=>$.id===R)){const $=o.findIndex(Y=>Y.id===R);c($);const X=o.filter(Y=>Y.id!==bs.id);X.splice($,0,bs),h(X)}else if(L.id===Be){c(o.length);const $=[...o,bs];h($),d(n),u(a),m(r)}}if(G||Q){if(a.some($=>$.id===R)){console.log("isOverMetricSortable",R);const $=a.findIndex(Y=>Y.id===R);c($);const X=a.filter(Y=>Y.id!==vs.id);X.splice($,0,vs),u(X)}else if(L.id===Fe){c(a.length);const $=[...a,vs];u($),m(r),d(n),h(o)}}if(S(z)){if(r.some($=>$.id===R)){const $=r.findIndex(Y=>Y.id===R);c($);const X=r.filter(Y=>Y.id!==ys.id);X.splice($,0,ys),m(X)}else if(L.id===ks){c(r.length);const $=[...r,ys];m($),u(a),d(n),h(o)}}}else d(n),u(a),m(r),h(o)};function C(w){i(w.active.id),c(null),d(n),u(a),m(r),h(o)}function S(w){return!r.some(M=>M.name===w.column_name)}function v(w,M="SUM"){const{column_name:L,data_type:O}=w,R=[...a],z=t!==null?t:a.length,G={...w,id:De(L),name:L,label:es(L,M),type:O,role:"metric",aggregate:M};R.splice(z,0,G),g(R)}function k(w){const M=s.isTextDataType(w.data_type);s.isDateDataType(w.data_type);const L=[...o],O=t!==null?t:o.length;let R;M?R={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,role:"groupby"}:R={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,role:"groupby",label:We(w.column_name,"month"),granularity:"month"},L.splice(O,0,R),j(L)}function N(w){const M=s.isTextDataType(w.data_type);s.isDateDataType(w.data_type);const L=[...n],O=t!==null?t:n.length;let R;M?R={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,role:"groupby"}:R={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,role:"groupby",label:We(w.column_name,"month"),granularity:"month"},L.splice(O,0,R),x(L)}function F(w){const M=[...r],L=t!==null?t:r.length,O={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,sql:s.getDefaultFilterSql(w.data_type,y,s.fmt(w.column_name)),role:"filter"};M.splice(L,0,O),b(M)}function T(w){var R,z,G,Q,_,W,$,X;const{active:M,over:L}=w,O=M.data.current;if((O==null?void 0:O.type)==="column"&&L){const Y=f.find(ne=>ne.column_name===M.id);if(!Y)return;const K=s.isNumberDataType(Y.data_type),U=s.isTextDataType(Y.data_type),ee=s.isDateDataType(Y.data_type);(U||ee)&&(L.id===Oe||((R=L.data.current)==null?void 0:R.type)===ds)&&N(Y),(U||ee)&&(L.id===Be||((z=L.data.current)==null?void 0:z.type)===us)?k(Y):(K||U)&&(L.id===Fe||((G=L.data.current)==null?void 0:G.type)===Ts)?(K&&v(Y),U&&v(Y,"COUNT")):S(Y)&&(L.id===ks||((Q=L.data.current)==null?void 0:Q.type)===Es)&&F(Y)}if(L&&((_=L.data.current)==null?void 0:_.type)===ds&&n.some(Y=>Y.id===M.id)){const Y=n.findIndex(U=>U.id===M.id),K=n.findIndex(U=>U.id===L.id);if(Y!==-1&&K!==-1&&Y!==K){const U=[...n],[ee]=U.splice(Y,1);U.splice(K,0,ee),x(U)}}if(L&&((W=L.data.current)==null?void 0:W.type)===us&&o.some(Y=>Y.id===M.id)){const Y=o.findIndex(U=>U.id===M.id),K=o.findIndex(U=>U.id===L.id);if(Y!==-1&&K!==-1&&Y!==K){const U=[...o],[ee]=U.splice(Y,1);U.splice(K,0,ee),j(U)}}if(L&&(($=L.data.current)==null?void 0:$.type)===Ts&&a.some(Y=>Y.id===M.id)){const Y=a.findIndex(U=>U.id===M.id),K=a.findIndex(U=>U.id===L.id);if(Y!==-1&&K!==-1&&Y!==K){const U=[...a],[ee]=U.splice(Y,1);U.splice(K,0,ee),g(U)}}if(L&&((X=L.data.current)==null?void 0:X.type)===Es&&r.some(Y=>Y.id===M.id)){const Y=r.findIndex(U=>U.id===M.id),K=r.findIndex(U=>U.id===L.id);if(Y!==-1&&K!==-1&&Y!==K){const U=[...r],[ee]=U.splice(Y,1);U.splice(K,0,ee),b(U)}}B(w),i(null),c(null),d(n),u(a),m(r),h(o)}function B(w){const{active:M,over:L}=w,O=M.data.current;if((O==null?void 0:O.type)===Ms&&L){const R=l.findIndex(G=>Je(G.columnId)===M.id),z=l.findIndex(G=>Je(G.columnId)===L.id);if(R!==-1&&z!==-1&&R!==z){const G=[...l],[Q]=G.splice(R,1);G.splice(z,0,Q),p(G)}}}function I(){i(null),c(null),d(n),u(a),m(r)}return{handleDragOver:D,handleDragEnd:T,handleDragStart:C,handleDragCancel:I,sensors:E}}function De(t){return`${t}-${s.v4()}`}function es(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 Je(t){return`${Ms}-${t}`}function We(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 Zn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Se,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ie,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Pe,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx($e,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Xe,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ss,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Se,{className:"h-3 w-3"})})}function er({schemaName:t,tableName:n,columns:a,status:r}){const[l,o]=A.useState(""),[c,i]=A.useState("all"),d=s.useEditorStore(R=>R.sqlGen),u=s.useEditorStore(R=>R.isDevMode);s.useEditorStore(R=>R.selectedConnectionId);const m=s.useEditorStore(R=>{var z,G;return(G=(z=R.card)==null?void 0:z.queryConfig)==null?void 0:G.metricColumns});s.useEditorStore(R=>{var z,G;return(G=(z=R.card)==null?void 0:z.queryConfig)==null?void 0:G.groupByColumns});const h=s.useEditorStore(R=>R.selectedDatabaseName);s.useEditorStore(R=>R.selectedSchemaName),s.useEditorStore(R=>R.selectedTableName);const x=s.useEditorStore(R=>R.selectedDatamodelId);s.useDashboardStore(R=>R.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:b}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:j,setCardSql:f,setRunSql:y,setSqlGen:E,setIsShowingVisual:D}=s.useEditorActions(),{connectionType:C,modelItems:S,selectedDatamodelName:v}=s.useEditorAside();function k(R){var z;if(u){const G=s.createSqlGenConfig(R,d);E(G);const Q=(z=S==null?void 0:S.find(W=>W.id===x))==null?void 0:z.name,_=s.getSql(G,s.fmt(t),s.fmt(n),Q||"",C,h||"");_&&(f(_),y(!0))}if(!u){if(s.isTextDataType(R.data_type))if(m&&m.length>0){const G={...R,role:"groupby",id:De(R.column_name),name:R.column_name,type:R.data_type};j(G)}else{const G={...R,role:"metric",id:De(R.column_name),name:R.column_name,label:es(R.column_name,"COUNT"),type:R.data_type,aggregate:"COUNT"};p(G)}if(s.isDateDataType(R.data_type)){const G={...R,role:"groupby",id:De(R.column_name),name:R.column_name,type:R.data_type,label:We(R.column_name,"month"),granularity:"month"};j(G)}if(s.isNumberDataType(R.data_type)){const G={...R,role:"metric",id:De(R.column_name),name:R.column_name,label:es(R.column_name,"SUM"),type:R.data_type,aggregate:"SUM"};p(G)}}}function N(){const R=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:C,databaseName:h||""});D(!1);const z=C==="MSSQL"?`SELECT top 10 * FROM ${R}`:`SELECT * FROM ${R} LIMIT 10`;f(z),y(!0)}function F(){const R=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:C,databaseName:h||""});f(`SELECT COUNT(*) as count FROM ${R}`),y(!0)}const T=(a==null?void 0:a.filter(R=>R.column_name.toLowerCase().includes(l.toLowerCase())))||[],B=R=>s.isNumberDataType(R.data_type)?"number":"text",I=c==="all"?T:T.filter(R=>B(R)===c),w=T.filter(R=>B(R)==="text").length,M=T.filter(R=>B(R)==="number").length;function L(R){return u?e.jsxs("div",{className:"group flex cursor-pointer items-center justify-between border border-dashed border-background px-2 py-[6px] text-sm transition-colors hover:bg-muted/50",onClick:()=>k(R),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zn,{dataType:R.data_type}),e.jsx("span",{children:R.column_name})]}),e.jsx("div",{onClick:z=>z.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(R.data_type)&&e.jsx(Wn,{column:R})})]}):e.jsx(Jn,{onClick:k,column:R})}function O(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:N,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(La,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:F,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(lt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-4",children:Array.from({length:3}).map((R,z)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},z))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[u&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:O()}),a&&a.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:R=>o(R.target.value)})]}),T.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:R=>i(R),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:T.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:w})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:M})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[I.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),I.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:I==null?void 0:I.map(R=>e.jsx("div",{children:L(R)},R.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function kt({ColumnsComponent:t,type:n}){var H;const[a,r]=A.useState(!1),{isConsoleMode:l}=s.useDashboardPreferences(),o=s.useEditorStore(P=>P.card),c=s.useEditorStore(P=>P.selectedConnectionId),i=s.useDashboardStore(P=>P.showFilters),d=s.useEditorStore(P=>P.selectedDatamodelId),u=s.useEditorStore(P=>P.selectedDatabaseName),m=s.useEditorStore(P=>P.selectedSchemaName),h=s.useEditorStore(P=>P.selectedTableName);s.useEditorStore(P=>P.isDevMode);const{setSelectedTableName:x,setIsDevMode:g,setCardSql:b}=s.useEditorActions(),{connectionItems:p,modelItems:j,schemaItems:f,databaseItems:y,tableItems:E,columns:D,isConnectionsLoading:C,isModelsLoading:S,isConnectionsError:v,isModelsError:k,isDatabasesLoadingOrFetching:N,isDatabaseError:F,isSchemaLoadingOrFetching:T,isSchemaError:B,isColumnsError:I,isColumnsLoadingOrFetching:w,isTableLoadingOrFetching:M,isTableError:L,connectionType:O,isNonDbConnection:R,refetchDatabases:z,refetchModels:G,refetchSchemas:Q,refetchTables:_,refetchColumns:W,refetchConnections:$,handleConnectionChange:X,handleDatabaseChange:Y,handleSchemaChange:K,handleDatamodelChange:U,handleTableChange:ee,tableName:ne,schemaName:he}=s.useEditorAside(),{data:ge,refetch:V}=s.useDashboardCardQuery(o);function Z(){return t?t(he,ne,D):e.jsx(er,{schemaName:he,tableName:ne,columns:D,status:w?"Loading...":I?"Error":"Success"})}function te(){if(!c||O==="S3"||O==="API")return null;if(!d||d==="none")return e.jsx(Ge,{refetch:z,showNone:!0,onChange:Y,isError:F,isLoading:N,items:y,value:u||"",title:"Database",type:"combobox"})}function re(){if(c&&!R&&(!u||u==="none")&&(!d||d==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function ie(){if(!c||O==="S3"||O==="API")return null;if(!u||u==="none")return e.jsx(Ge,{refetch:G,showNone:!0,onChange:U,isError:k,isLoading:S,items:j,value:d||"",title:"Model",type:"combobox"})}function de(){return!c||O==="S3"||O==="API"||!u||u==="none"?null:e.jsx(Ge,{refetch:Q,onChange:K,isError:B,isLoading:T,items:f,value:m||"",title:"Schema",type:"combobox"})}function xe(){function P(){let J=!1;return O==="API"?(J=!1,J):((O==="S3"||c&&u&&u!=="none"&&m)&&(J=!0),J)}return P()?e.jsx(Ge,{refetch:_,onChange:ee,isError:L,items:E,isLoading:M,value:h||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!i}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":a,"px-4 py-4":!a}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!a),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:a?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!a&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ge,{refetch:$,items:p,title:"Connection",value:c||"",onChange:X,isLoading:C,isError:v,type:"combobox",connectionTooltip:((H=p==null?void 0:p.find(P=>P.id===c))==null?void 0:H.type)||""}),te(),re(),ie(),de(),xe()]})]}),Z(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&l&&e.jsx(e.Fragment,{})})]})}function Et({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:l=!0}){const[o,c]=A.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",r),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Query Error"}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),l&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function It({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){o(!l),c(t),setTimeout(()=>{i(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[n&&e.jsx(Et,{error:n,errorSql:a,showFeedbackButton:!1}),!n&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!n&&e.jsxs(s.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(Na,{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(ka,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function At({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(ga,{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(It,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function sr(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 Mt(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(p=>p.theme),r=s.useEditorStore(p=>p.frame),l=s.useEditorStore(p=>p.card),o=s.useEditorStore(p=>p.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=A.useRef(),h=A.useRef({}),x=r.cards.find(p=>p.id===o),g=A.useCallback(()=>{let p="";return t==="python"&&(p=(x==null?void 0:x.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(p=(x==null?void 0:x.sql)||""),p},[t,x]);A.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const p=m.current.getModel();p&&(h.current[l.id]=p);let j=h.current[o];if(!j){const f=g();j=c.editor.createModel(f,t),h.current[o]=j}m.current.setModel(j)}d(o,l),u(!0)}},[o,l,d,c,u,t,g]),A.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=a==="system"?p:a;c.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),A.useEffect(()=>{const p=m.current;p&&c&&l&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function b(p,j){if(m.current=p,!h.current[l.id]){const f=p.getModel(),y=g();h.current[l.id]=f||(j==null?void 0:j.editor.createModel(y,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:b}}function tr(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Mt("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function ar(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Mt("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 nr({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 rr(){const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=A.useState(!1),[l,o]=A.useState(!1);s.useEditorStore(_=>_.frame);const c=s.useEditorStore(_=>_.card);s.useEditorStore(_=>_.isShowingVisual),s.useEditorStore(_=>_.selectedConnectionId),s.useEditorStore(_=>_.tempQueryData),s.useEditorStore(_=>_.selectedDatabaseName),s.useEditorStore(_=>_.selectedDatamodelId),s.useEditorStore(_=>_.selectedSchemaName);const i=s.useEditorStore(_=>_.showAIDialog);s.useEditorStore(_=>_.selectedTableName);const d=s.useEditorStore(_=>{var W;return(W=_==null?void 0:_.card)==null?void 0:W.sql}),u=s.useEditorStore(_=>{var W;return(W=_==null?void 0:_.card)==null?void 0:W.python}),{cardFilterValues:m}=s.useCardFilterValues((c==null?void 0:c.id)??""),{setCardCustomCfg:h,setQueryResultColumns:x,setCardSql:g,setTempQueryData:b,setPythonStdOut:p,setCardPreferences:j,setCardType:f,setCardPython:y,runAssistant:E,setShowAIDialog:D}=s.useEditorActions();s.useEditorStore(_=>_.onSave),s.useEditorStore(_=>_.onClose),s.useEditorStore(_=>_.actions.setSqlGen);const C=s.useEditorStore(_=>_.runSql),S=s.useEditorStore(_=>_.actions.setRunSql),v=s.useEditorStore(_=>_.actions.setIsSqlRunning),{data:k,isLoading:N,isFetching:F,isSuccess:T,isError:B,error:I,errorSql:w,queryKey:M,refetch:L,errorMessage:O}=s.useDashboardCardQuery(c);A.useEffect(()=>{if(k&&(k.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),p((k==null?void 0:k.output)||""),k.records.length>0)){const{dimensionKeys:_}=s.getKeys(k.records);x(_)}},[k,x,p]),A.useEffect(()=>{(N||F)&&v(!0),(B||T)&&v(!1),B&&(x([]),p(""))},[N,F,k,p,B,T,v,x,I]),A.useEffect(()=>{C&&(t.getQueryData(M)||L(),S(!1))},[C,L,S,M,t]);async function R(){const _=`Can you help me debug this query?
311
+ */const Ka=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function Qa(){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(qa,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Fa,{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 is(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>ct(c))}})}})}}function ct(t){return{...t,customCfg:Ja(t.customCfg),data:[]}}function Ja(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 Xa(t,n,a,r,l){if(!l)return null;const o=JSON.stringify(a),c=`${t}/v1/lens`;return await s.postRequest(c,l,{name:n,template:o,filterValues:r,operation:"create"})}async function Ds(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:o,isDefault:c,shared:i}=n,d=`${t}/v1/lens`;return await s.postRequest(d,a,{lensId:r,template:l,filterValues:o,isDefault:c,shared:i,operation:"update"})}async function Za(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function en(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),l=s.useDashboardStore(j=>j.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=A.useState(!1),[u,m]=A.useState(!1),h=s.useDashboardStore(j=>j.dashboard),x=s.useDashboardStore(j=>j.filterValues),{authToken:g,tokenProps:b}=s.useSemaphorContext();async function p(){d(!0);const j=is(h),f=await Xa(b.apiServiceUrl,t,j,x,g==null?void 0:g.accessToken);f&&(o([...l||[],f]),c(f.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:j=>{n(j.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:p,disabled:i,children:i?"Creating...":"Add"})})]})]})}function sn(){const[t,n]=A.useState(!1),a=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c,tokenProps:i}=s.useSemaphorContext();async function d(h){o(h)}async function u(h){if(await Za(i.apiServiceUrl,h,c==null?void 0:c.accessToken)){const g=a==null?void 0:a.filter(b=>b.id!==h);l(g||[]),o("original")}}async function m(h){const x=a==null?void 0:a.map(p=>p.id===h.id?{...p,isDefault:!h.isDefault}:{...p,isDefault:!1});l(x||[]);const g={...h,isDefault:!h.isDefault};await Ds(i.apiServiceUrl,g,c==null?void 0:c.accessToken);const b=a==null?void 0:a.find(p=>p.isDefault);if(b&&b.id!==h.id){const p={...b,isDefault:!1};await Ds(i.apiServiceUrl,p,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Ta,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:d,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:x=>{x.preventDefault(),m(h)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:x=>{x.preventDefault(),u(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function tn({iconClassName:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(""),[o,c]=A.useState(!1),i=s.useDashboardStore(h=>h.isDownloadingPdf),{tokenProps:d}=s.useSemaphorContext();async function u(){const h=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl),s.ue.dismiss(h),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",x)}}async function m(){if(!r)return;a(!1),l(""),c(!1);const h=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl,r),s.ue.dismiss(h),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",x)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(s.Lock,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:n,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:h=>l(h.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:h=>{h.key==="Enter"&&r&&m()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:m,disabled:!r,children:"Download"})]})]})})]})}function dt({triggerButtonClassName:t}){const[n,a]=A.useState(!1),r=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.id}),l=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.title}),o=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.sheets}),c=s.useDashboardStore(i=>i.selectedSheetId);return o==null||o.find(i=>i.id===c),r?e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),onClick:()=>a(!0),children:e.jsx(s.Clock,{className:"size-4"})}),e.jsx(s.EmailScheduleDialog,{open:n,onOpenChange:a,dashboardId:r,dashboardName:l})]}):null}function cs({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 Ve({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=a.find(u=>u.value===t))==null?void 0:d.label)||t,i=a.filter(u=>u.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>n(u.value),disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function ut({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>a(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(Ve,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>a(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function mt({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 ht({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=n.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function xt(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=A.useRef(null);return A.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function De(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function an(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function pt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function nn(t,n,a){const r=pt(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function rn({user:t}){return pt(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 ln({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=an((r==null?void 0:r.type)||""),i=a.some(h=>h.id===t.id),d=a.find(h=>h.id===t.id),u=d?d.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Ve,{currentRole:u,onRoleChange:h=>{o(t.id,n.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:De(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function on({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(Ye,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function cn({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function dn({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((x,g)=>{var f,y;const b=((f=n.find(I=>I.id===x.orgUserId))==null?void 0:f.name)||"Unknown User",p=((y=n.find(I=>I.id===x.orgUserId))==null?void 0:y.type)||"",j=De(x.role,a(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((x,g)=>{var f,y;const b=((f=n.find(I=>I.id===x.tenantUserId))==null?void 0:f.name)||"Unknown User",p=((y=n.find(I=>I.id===x.tenantUserId))==null?void 0:y.type)||"",j=De(x.role,a(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((x,g)=>{const b=De(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((x,g)=>{const b=De(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((x,g)=>{const b=De(x.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),!i.length&&!d.length&&!u.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var g,b;const m=((g=n.find(p=>p.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((b=n.find(p=>p.id===d.tenantUserId))==null?void 0:b.type)||"",x=De(d.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:x})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=De(d.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var x,g;const u=((x=n.find(b=>b.id===i.tenantUserId))==null?void 0:x.name)||"Unknown User",m=((g=n.find(b=>b.id===i.tenantUserId))==null?void 0:g.type)||"",h=De(i.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=De(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function un({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 mn({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:x,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?a?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(rn,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Ve,{currentRole:n==null?void 0:n.role,onRoleChange:b=>x(t.id,n.role,b),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(ln,{user:t,userShare:n,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:x}),o&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(Ve,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:b=>g(t.id,b),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(on,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(cn,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function ft({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),b=s.useShareManagementActions(),p=c||(N=>{const S=m.some(k=>k.id===N),v=h.includes(N);S?b.removeSelectedUser(N):v?b.removeUserFromRemove(N):b.addSelectedUser({id:N,role:"VIEWER"})}),j=i||b.updateSelectedUserRole,f=d||b.addUserToRemove,y=u||((N,S,v)=>{b.addUserToUpdate({id:N,currentRole:S,newRole:v})}),I=l,D=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(I??[]).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(dn,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(I==null?void 0:I.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===I.length?b.setSelectedUsers([]):b.setSelectedUsers(I.map(N=>({id:N.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===I.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(un,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:I||[]}),!n&&!a&&(I==null?void 0:I.length)>0&&I.map(N=>{const S=t?nn(N,t,o):void 0,v=D.includes(N.id),k=!!S,C=k&&!v,F=m.some(E=>E.id===N.id),T=m.find(E=>E.id===N.id),B=r(N.type);return e.jsx(mn,{user:N,userShare:S,isUserRemoving:v,hasAccess:C,hasAccessFromAPI:k,isSelected:F,selectedUser:T,roleOptions:B,currentUser:o,usersToUpdate:x,handleUserToggle:p,handleRemoveAccess:f,handleUpdateAccess:y,handleUserRoleChange:j},N.id)})]})]})}function Is({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(s.User,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const Se=()=>[{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 hn({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=Se().filter(y=>y.value==="VIEWER"||y.value==="EDITOR"||y.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",h=l?l.newRole:m,x=n.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,b=o,p=m==="NONE"||!m,j=y=>{switch(y){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(Ua,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},f=y=>{r(m,y)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!b&&!p?"border-orange-300 bg-orange-50":x?"border-green-300 bg-green-50":b||p?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",x&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),g&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(b||p)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:b||p?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(y=>e.jsxs(s.Button,{variant:h===y.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>f(y.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(y.value),e.jsx("span",{className:"font-medium",children:y.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:y.description})]},y.value))})]})})]})})}function gt({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=p=>p==="OWNER"?"CONTRIBUTOR":p,h=n?{role:u(n.role)}:{role:"NONE"},x=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,g=(p,j)=>{o(p,j)},b=()=>{c()};return e.jsx(hn,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:b,allUsersToUpdate:x,allUsersToRemove:d})}function He(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=A.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading:d,isError:u}=s.useUnifiedUsers(c),m=s.useResourceShares(r,a);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function xn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var V,K;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),x=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),b=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),j=s.useShareOrgWideRole(),f=s.useShareManagementActions(),[y,I]=A.useState("specific_users"),D=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},N=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:v,isLoadingUsers:k}=He({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:D(),tenantId:N()});A.useEffect(()=>{f.setCurrentContext("org-tab"),f.setCurrentMode(y==="all_users"?"allOrgUsers":"specificOrgUsers")},[f,y]);const C=$=>{var q,Q;const X=$;if(I(X),r==null||r(X),f.setCurrentContext("org-tab"),X==="specific_users")f.setCurrentMode("specificOrgUsers");else if(X==="all_users"){f.setCurrentMode("allOrgUsers");const _=(Q=(q=v==null?void 0:v.shares)==null?void 0:q.orgUsersOnly)==null?void 0:Q[0];_&&_.role!==void 0&&f.setOrgWideRole(_.role)}},F=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),T=S.filter($=>x.some(X=>X.id===$.id)),B=$=>{var _,te;const X=x.some(re=>re.id===$),q=g.includes($),Q=(te=(_=v==null?void 0:v.shares)==null?void 0:_.specificOrgUsers)==null?void 0:te.some(re=>re.orgUserId===$);X?f.removeSelectedUser($):q?f.removeUserFromRemove($):Q||f.addSelectedUser({id:$,role:"VIEWER"})},E=($,X)=>{f.updateSelectedUserRole($,X)},w=$=>{f.addUserToRemove($),f.removeSelectedUser($)},M=$=>{f.removeUserFromRemove($)},L=$=>{f.removeUserFromUpdate($)},O=($,X)=>{f.setOrgWideRole(X)},R=()=>{f.setOrgWideRole((P==null?void 0:P.role)||"NONE")},P=(K=(V=v==null?void 0:v.shares)==null?void 0:V.orgUsersOnly)==null?void 0:K[0];A.useEffect(()=>{y==="all_users"&&P&&P.role!==void 0&&f.setOrgWideRole(P.role)},[y,P,f]);const G=k,J=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(Is,{shareType:y,onShareTypeChange:C,currentUser:a,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),y==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(cs,{value:u,onChange:m}),e.jsx(ut,{selectedUsers:x,selectedUserObjects:T,onRemove:B,onRoleChange:E,getRoleOptions:Se}),e.jsx(mt,{usersToRemove:g,allUsers:F,onRemove:M}),e.jsx(ht,{usersToUpdate:b,allUsers:F,onRemove:L,getRoleOptions:Se}),e.jsx(ft,{existingShares:v,isInitialLoading:G,isSearching:J,resource:t,onShare:()=>{},getRoleOptions:Se,allUsers:F,currentUser:a,handleUserToggle:B,handleUserRoleChange:E,handleRemoveAccess:w,handleUpdateAccess:($,X,q)=>{f.addUserToUpdate({id:$,currentRole:X,newRole:q})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(gt,{currentUser:a,currentShare:P,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:O,onRemoveAccess:R,allUsersToUpdate:p==="allOrgUsers"&&j!==((P==null?void 0:P.role)||"NONE")?{currentRole:(P==null?void 0:P.role)||"NONE",newRole:j}:null,allUsersToRemove:p==="allOrgUsers"&&(P==null?void 0:P.role)===void 0})})]}):null}function pn(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function fn(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function jt({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:l,currentUser:o,handleGroupToggle:c,handleGroupRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),g=s.useShareManagementActions(),b=l(o==null?void 0:o.type);return a?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):t.length===0?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No groups available to share with"}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Available Groups"}),e.jsx("div",{className:"max-h-[300px] space-y-2 overflow-y-auto rounded-md border p-3",children:t.map(p=>{const j=n==null?void 0:n.find(v=>v.groupId===p.id),f=m.some(v=>v.id===p.id),y=h.includes(p.id),I=x.find(v=>v.id===p.id),D=!!j&&!y;let S=(j==null?void 0:j.role)||"VIEWER";if(f){const v=m.find(k=>k.id===p.id);S=(v==null?void 0:v.role)||"VIEWER"}else I&&(S=I.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",D&&!y?"border border-green-200 bg-green-50":y?"border border-red-200 bg-red-50":f?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(s.Checkbox,{id:`group-${p.id}`,checked:D?!y:f,disabled:!1,onCheckedChange:()=>{D?y?g.removeGroupFromRemove(p.id):d==null||d(p.id):c==null||c(p.id)}}),e.jsxs("label",{htmlFor:`group-${p.id}`,className:"flex cursor-pointer flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:p.name}),p.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-3 w-3 text-blue-600"}):e.jsx(s.Users,{className:"h-3 w-3 text-green-600"}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[p.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",fn(p.type)),children:pn(p.type)}),p.type==="TENANT_GROUP"&&p.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",p.tenantName]})]}),p.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[D&&!y?e.jsx(Ve,{currentRole:S,onRoleChange:v=>{j&&v!==j.role&&(u==null||u(p.id,j.role,v))},roleOptions:b,disabled:!1,allowDropdown:!0,className:I?"border-orange-300 bg-orange-100":""}):f&&!D&&e.jsx(Ve,{currentRole:S,onRoleChange:v=>i==null?void 0:i(p.id,v),roleOptions:b,disabled:!1}),D&&!y&&!I&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>d==null?void 0:d(p.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),y&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromRemove(p.id),children:"Undo"}),I&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromUpdate(p.id),children:"Cancel"})]})]},p.id)})})]})}function bt({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){if(t.length===0)return null;const o=l();return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",t.length,")"]}),e.jsx("div",{className:"space-y-1",children:t.map(c=>{const i=n.find(d=>d.id===c.id);return i?e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/50 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-4 w-4 text-blue-600"}):e.jsx(s.Users,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm font-medium",children:i.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[i.memberCount," members"]}),i.type==="TENANT_GROUP"&&i.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",i.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ve,{currentRole:c.role,onRoleChange:d=>r(c.id,d),roleOptions:o}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(c.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},c.id):null})})]})}function qs({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var W;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSelectedGroups(),b=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate(),j=s.useShareCurrentMode(),f=s.useShareTenantWideRole(),y=s.useShareAllTenantsRole(),I=s.useShareSelectedTenant(),D=s.useShareManagementActions(),{data:N,isLoading:S}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:v,isLoading:k}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||I),[C,F]=A.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(D.setCurrentContext("tenant-dialog"),D.setCurrentMode("specificTenantUsers")):(D.setCurrentContext("tenant-tab"),D.setCurrentMode("allTenants"))},[D,a==null?void 0:a.type]);const T=U=>{var Y,le,se,ie;F(U);let ee;if(U==="specific_tenant_users"?ee="specific_users":U==="all_tenant_users"||U==="all_tenants"?ee="all_users":U==="groups"?ee="groups":ee="specific_users",r==null||r(ee),U==="groups"?(D.setCurrentContext("group-share"),D.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(D.setCurrentContext("tenant-dialog"),U==="specific_tenant_users"?D.setCurrentMode("specificTenantUsers"):U==="all_tenant_users"&&(D.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&D.setSelectedTenant(a.tenantId))):(D.setCurrentContext("tenant-tab"),U==="specific_tenant_users"?D.setCurrentMode("specificTenantUsers"):U==="all_tenant_users"?D.setCurrentMode("allTenantUsers"):U==="all_tenants"&&D.setCurrentMode("allTenants")),U==="all_tenant_users"){const ce=(le=(Y=w==null?void 0:w.shares)==null?void 0:Y.tenantWide)==null?void 0:le[0];ce&&ce.role!==void 0&&D.setTenantWideRole(ce.role)}else if(U==="all_tenants"){const ce=(ie=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:ie[0];ce&&ce.role!==void 0&&D.setAllTenantsRole(ce.role)}},B=U=>{D.setSelectedTenant(U)},{allUsers:E,existingShares:w,isLoadingUsers:M,isErrorLoadingUsers:L,isLoadingShares:O,isErrorLoadingShares:R}=He({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:I}),P=U=>{var se,ie;const ee=m.some(ce=>ce.id===U),Y=h.includes(U),le=(ie=(se=w==null?void 0:w.shares)==null?void 0:se.specificTenantUsers)==null?void 0:ie.some(ce=>ce.tenantUserId===U);ee?D.removeSelectedUser(U):Y?D.removeUserFromRemove(U):le||D.addSelectedUser({id:U,role:"VIEWER"})},G=(U,ee)=>{D.updateSelectedUserRole(U,ee)},J=U=>{D.addUserToRemove(U),D.removeSelectedUser(U)},V=U=>{D.removeUserFromRemove(U)},K=U=>{D.removeUserFromUpdate(U)},$=(U,ee,Y)=>{D.addUserToUpdate({id:U,currentRole:ee,newRole:Y})},X=(U,ee)=>{C==="all_tenant_users"?D.setTenantWideRole(ee):C==="all_tenants"&&D.setAllTenantsRole(ee)},q=()=>{C==="all_tenant_users"?D.setTenantWideRole("VIEWER"):C==="all_tenants"&&D.setAllTenantsRole("VIEWER")},_=(()=>{var U,ee,Y,le;return j==="allTenants"?(ee=(U=w==null?void 0:w.shares)==null?void 0:U.allTenantsOnly)==null?void 0:ee[0]:j==="allTenantUsers"?(le=(Y=w==null?void 0:w.shares)==null?void 0:Y.tenantWide)==null?void 0:le[0]:null})();A.useEffect(()=>{var U,ee,Y,le;if(C==="all_tenant_users"){const se=(ee=(U=w==null?void 0:w.shares)==null?void 0:U.tenantWide)==null?void 0:ee[0];se&&se.role!==void 0&&D.setTenantWideRole(se.role)}else if(C==="all_tenants"){const se=(le=(Y=w==null?void 0:w.shares)==null?void 0:Y.allTenantsOnly)==null?void 0:le[0];se&&se.role!==void 0&&D.setAllTenantsRole(se.role)}},[C,w,D]);const te=E.filter(U=>m.some(ee=>ee.id===U.id)),re=U=>{const ee=g.some(se=>se.id===U),Y=b.includes(U),le=oe==null?void 0:oe.some(se=>se.groupId===U);ee?D.removeSelectedGroup(U):Y?D.removeGroupFromRemove(U):le||D.addSelectedGroup({id:U,role:"VIEWER"})},he=(U,ee)=>{D.updateSelectedGroupRole(U,ee)},ge=U=>{D.addGroupToRemove(U),D.removeSelectedGroup(U)},z=(U,ee,Y)=>{D.addGroupToUpdate({id:U,currentRole:ee,newRole:Y})},Z=v.filter(U=>g.some(ee=>ee.id===U.id)),ae=A.useMemo(()=>C!=="groups"?[]:v.filter(U=>U.type!=="TENANT_GROUP"?!1:U.name.toLowerCase().includes(i.toLowerCase())||U.description&&U.description.toLowerCase().includes(i.toLowerCase())),[v,C,i]),oe=A.useMemo(()=>{var ee,Y;const U=((ee=w==null?void 0:w.shares)==null?void 0:ee.specificGroups)||((Y=w==null?void 0:w.shares)==null?void 0:Y.groups)||[];return!U||U.length===0?[]:U.filter(le=>{const se=v.find(ie=>ie.id===le.groupId);return(se==null?void 0:se.type)==="TENANT_GROUP"})},[w,v]),de=M||O||C==="groups"&&k,ue=L||R,xe=()=>(a==null?void 0:a.type)==="tenant"||C==="all_tenants"||C==="groups"?!0:I&&(C==="specific_tenant_users"||C==="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(Is,{shareType:C,onShareTypeChange:T,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(Gs,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.type)==="organization"&&(C==="specific_tenant_users"||C==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:I||"",onValueChange:B,disabled:S,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:S?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(W=N==null?void 0:N.tenants)==null?void 0:W.map(U=>e.jsx(s.SelectItem,{value:U.id,children:U.name},U.id))})]})]}),xe()?e.jsx(e.Fragment,{children:C==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(cs,{value:i,onChange:u}),e.jsx(ut,{selectedUsers:m,selectedUserObjects:te,onRemove:U=>P(U),onRoleChange:G,getRoleOptions:Se}),e.jsx(mt,{usersToRemove:h,allUsers:E,onRemove:V}),e.jsx(ht,{usersToUpdate:x,allUsers:E,onRemove:K,getRoleOptions:Se}),e.jsx(ft,{existingShares:w,isInitialLoading:!!de,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Se,allUsers:E,currentUser:a,handleUserToggle:P,handleUserRoleChange:G,handleRemoveAccess:J,handleUpdateAccess:$})]}):C==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(cs,{value:i,onChange:u,placeholder:"Search groups..."}),e.jsx(bt,{selectedGroups:g,groupObjects:Z,onRemove:re,onRoleChange:he,getRoleOptions:Se}),b.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",b.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),p.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",p.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(jt,{groups:ae,existingGroupShares:oe,isLoading:k,resource:t,getRoleOptions:Se,currentUser:a,handleGroupToggle:re,handleGroupRoleChange:he,handleRemoveAccess:ge,handleUpdateAccess:z})]}):C==="all_tenant_users"||C==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(gt,{currentUser:a,currentShare:_,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:X,onRemoveAccess:q,allUsersToUpdate:j==="allTenantUsers"&&((_==null?void 0:_.role)===void 0||f!==_.role)||j==="allTenants"&&((_==null?void 0:_.role)===void 0||y!==_.role)?{currentRole:(_==null?void 0:_.role)||"VIEWER",newRole:j==="allTenantUsers"?f:y}:null,allUsersToRemove:j==="allTenantUsers"&&(_==null?void 0:_.role)===void 0||j==="allTenants"&&(_==null?void 0:_.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(C==="specific_tenant_users"||C==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Gs,{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 gn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var L,O;const{searchQuery:i,setSearchQuery:d}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),x=s.useShareManagementActions(),[g,b]=A.useState("org_groups"),[p,j]=A.useState(""),{data:f,isLoading:y}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&g==="tenant_groups"}),I=Array.isArray(f)?f:(f==null?void 0:f.tenants)||[],D=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:N,isLoading:S}=s.useShareableGroups(D(),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?p:a==null?void 0:a.tenantId),{existingShares:v}=He({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),k=N.filter(R=>g==="org_groups"&&R.type!=="ORG_GROUP"||g==="tenant_groups"&&R.type!=="TENANT_GROUP"||g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!p||R.tenantId&&R.tenantId!==p)?!1:R.name.toLowerCase().includes(i.toLowerCase())||R.description&&R.description.toLowerCase().includes(i.toLowerCase())),C=((L=v==null?void 0:v.shares)==null?void 0:L.specificGroups)||((O=v==null?void 0:v.shares)==null?void 0:O.groups)||[];A.useEffect(()=>{x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},[x]);const F=R=>{const P=R;b(P),P==="org_groups"&&j(""),r==null||r(P==="org_groups"?"specific_groups":"all_groups"),x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},T=N.filter(R=>u.some(P=>P.id===R.id)),B=R=>{const P=u.some(V=>V.id===R),G=m.includes(R),J=C==null?void 0:C.some(V=>V.groupId===R);P?x.removeSelectedGroup(R):G?x.removeGroupFromRemove(R):J||x.addSelectedGroup({id:R,role:"VIEWER"})},E=(R,P)=>{x.updateSelectedGroupRole(R,P)},w=R=>{x.addGroupToRemove(R),x.removeSelectedGroup(R)},M=(R,P,G)=>{x.addGroupToUpdate({id:R,currentRole:P,newRole:G})};return a?e.jsxs(e.Fragment,{children:[e.jsx(Is,{shareType:g,onShareTypeChange:F,currentUser:a,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:e.jsx(s.Building2,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"tenant_groups",label:"Tenant Groups",description:"Share with tenant-level groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]}),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(s.Label,{children:"Select Tenant"}),e.jsxs(s.Select,{value:p,onValueChange:j,disabled:y,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:y?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:I.map(R=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:R.id,children:R.name},R.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!p?e.jsx("div",{className:"rounded-md border border-dashed p-6 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant above to view and share with its groups"})}):e.jsxs(e.Fragment,{children:[e.jsx(cs,{value:i,onChange:d,placeholder:"Search groups..."}),e.jsx(bt,{selectedGroups:u,groupObjects:T,onRemove:B,onRoleChange:E,getRoleOptions:Se}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",m.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",h.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(jt,{groups:k,existingGroupShares:C,isLoading:S,resource:t,getRoleOptions:Se,currentUser:a,handleGroupToggle:B,handleGroupRoleChange:E,handleRemoveAccess:w,handleUpdateAccess:M})]})})]}):null}const vt=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedGroups(),c=s.useShareGroupsToRemove(),i=s.useShareGroupsToUpdate(),d=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),h=s.useShareTenantWideRole(),x=s.useShareGroupWideRole(),g=A.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedGroups:o,groupsToRemove:c,groupsToUpdate:i,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}),[t,n,a,r,l,o,c,i,d,u,m,h,x]),b=A.useMemo(()=>j=>s.validateShareData(j),[]),p=A.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!d)return!1}else if(n==="specificTenantUsers")return d?a.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||l.length>0:!0;case"group-share":return n==="specificGroups"?o.length>0||c.length>0||i.length>0:!0}return!1},[t,n,a,r,l,o,c,i,d]);return{buildShareData:g,validateShareData:b,isCurrentStateValid:p,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}};function Hs({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSelectedTenant(),b=s.useShareOrgWideRole(),p=s.useShareAllTenantsRole(),j=s.useShareTenantWideRole(),{buildShareData:f,validateShareData:y,isCurrentStateValid:I}=vt(),D=a||r||l,N=()=>{var F,T,B,E;if(D)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const w=m.length+h.length+x.length;return w===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${w} user${w!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&x.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Update access for ${x.length} user${x.length!==1?"s":""}`:`Update access for ${w} user${w!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const w=d.role;return b===w?"Remove Access":"Update Access"}else if(i==="all_tenants"){const w=(T=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:T[0];if(!w||w.role===void 0)return"Share with All Tenants";const M=w.role;return p===M?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const w=(E=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:E[0];if(!w||w.role===void 0)return"Share with All Tenant Users";const M=w.role;return j===M?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const w=m.length+h.length+x.length;return w===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${w} user${w!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&x.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Update access for ${x.length} user${x.length!==1?"s":""}`:`Update access for ${w} user${w!==1?"s":""}`}return"Share"},S=()=>D||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!I,v=()=>{const F=f();F&&y(F)&&o(F)},k=()=>{var F,T,B,E;if(i==="all_users")if(!d||d.role===void 0){const w=f();w&&y(w)&&o(w)}else{const w=d.role;if(b===w)u==null||u();else{const L=f();if(L&&y(L)){const O={...L,updateAccess:!0};o(O)}}}else if(i==="all_tenants"){const w=(T=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:T[0];if(!w||w.role===void 0){const M=f();M&&y(M)&&o(M)}else{const M=w.role;if(p===M)u==null||u();else{const O=f();if(O&&y(O)){const R={...O,updateAccess:!0};o(R)}}}}else if(i==="all_tenant_users"){const w=(E=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:E[0];if(!w||w.role===void 0){const M=f();M&&y(M)&&o(M)}else{const M=w.role;if(j===M)u==null||u();else{const O=f();if(O&&y(O)){const R={...O,updateAccess:!0};o(R)}}}}},C=()=>{var F,T,B,E;if(i==="all_users"){if(!d||d.role===void 0)return"default";const w=d.role;return b===w?"destructive":"default"}else if(i==="all_tenants"){const w=(T=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:T[0];if(!w||w.role===void 0)return"default";const M=w.role;return p===M?"destructive":"default"}else if(i==="all_tenant_users"){const w=(E=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:E[0];if(!w||w.role===void 0)return"default";const M=w.role;return j===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:D,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||x.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||D,variant:"default",children:[D?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!D&&N()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,disabled:S(),variant:C(),children:[D?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"}),!D&&N()]})]})}function jn({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),h=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),g=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const b=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:j,isCurrentStateValid:f}=vt(),y=n||a||r,I=()=>{if(y)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const C=d.length+u.length+m.length;return C===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${C} user${C!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${C} user${C!==1?"s":""}`}else if(c==="groups"){if(h.length===0&&x.length===0&&g.length===0)return"Select groups to share with";const C=h.length+x.length+g.length;return C===0?"Select groups to share with":h.length>0&&x.length>0?`Update access for ${C} group${C!==1?"s":""}`:x.length>0&&h.length===0&&g.length===0?`Remove access for ${x.length} group${x.length!==1?"s":""}`:h.length>0&&x.length===0&&g.length===0?`Share with ${h.length} group${h.length!==1?"s":""}`:g.length>0&&h.length===0&&x.length===0?`Update access for ${g.length} group${g.length!==1?"s":""}`:`Update access for ${C} group${C!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const C=i.role;return b===C?"Remove Access":"Update Access"}return"Share"},D=()=>y||!t?!0:!f,N=()=>{const C=p();C&&j(C)&&l(C)},S=()=>{const C=p();C&&j(C)&&l(C)},v=()=>{if(!i||i.role==="NONE"){const C=p();C&&j(C)&&l(C)}else{const C=i.role;if(b===C){const T=p();if(T&&j(T)){const B={...T,removeAccess:!0};l(B)}}else{const T=p();if(T&&j(T)){const B={...T,updateAccess:!0};l(B)}}}},k=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:y,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:N,disabled:!t||y,variant:"default",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!y&&I()]})}),c==="groups"&&e.jsx(e.Fragment,{children:(h.length>0||x.length>0||g.length>0)&&e.jsxs(s.Button,{onClick:S,disabled:!t||y,variant:"default",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!y&&I()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:v,disabled:D(),variant:k(),children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!y&&I()]})]})}function bn({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllGroupsShare:d,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const g=()=>{o({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:h,groupsToUpdate:x})},b=()=>m.length>0||h.length>0||x.length>0,p=()=>h.length>0&&m.length===0&&x.length===0?"Remove Access":x.length>0&&m.length===0&&h.length===0?"Update Access":"Share with Groups",j=a||r||l;return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[m.length>0&&e.jsxs("span",{children:[m.length," groups selected"]}),h.length>0&&e.jsxs("span",{className:"ml-2 text-destructive",children:["• ",h.length," to remove"]}),x.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",x.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:j,children:"Cancel"}),e.jsxs(s.Button,{onClick:g,disabled:!b()||j,children:[j&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),p()]})]})]})}function Ne(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Ie(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function vn(t,n,a){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=Ne(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const x=Ne(r,l,u.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(x,{onSuccess:()=>{d()}})}if(m&&m.length>0){const x=Ie(r,l,m.map(g=>{var p,j;const b=(j=(p=i==null?void 0:i.shares)==null?void 0:p.specificOrgUsers)==null?void 0:j.find(f=>f.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(x=>{const g=Ne(r,l,[{scope:"specific_org_user",orgUserId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=Ne(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=Ne(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:x}=t;if(m&&m.length>0){const g=Ie(r,l,m.map(b=>{var j,f;const p=(f=(j=i==null?void 0:i.shares)==null?void 0:j.specificTenantUsers)==null?void 0:f.find(y=>y.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,tenantId:x,role:(p==null?void 0:p.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const b=Ne(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:x,role:g.newRole}]);o(b,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=Ne(r,l,u.map(b=>({scope:"specific_tenant_user",tenantUserId:b.id,tenantId:x,role:b.role})));o(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=Ie(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=Ne(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=Ne(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const x=Ne(r,l,u.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(x,{onSuccess:()=>{d()}})}if(m&&m.length>0){const x=Ie(r,l,m.map(g=>{var p,j;const b=(j=(p=i==null?void 0:i.shares)==null?void 0:p.specificTenantUsers)==null?void 0:j.find(f=>f.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(x=>{const g=Ne(r,l,[{scope:"specific_tenant_user",tenantUserId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"group-share":if(t.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:m,groupsToUpdate:h}=t;if(u&&u.length>0){const x=Ne(r,l,u.map(g=>({scope:"group",groupId:g.id,role:g.role})));o(x,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(m&&m.length>0){const x=Ie(r,l,m.map(g=>({scope:"group",groupId:g,role:"VIEWER"})));c(x,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Removed access from ${m.length} group${m.length!==1?"s":""}`)}})}h&&h.length>0&&h.forEach(x=>{const g=Ne(r,l,[{scope:"group",groupId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{var b;d(),(b=n.resetGroupSelections)==null||b.call(n),s.ue.success("Updated access for group")}})})}break}}function yn(t,n,a,r){var u,m,h,x,g,b;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const p=Ie(l,o,t.map(j=>{var y,I;const f=(I=(y=i==null?void 0:i.shares)==null?void 0:y.specificTenantUsers)==null?void 0:I.find(D=>D.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,role:(f==null?void 0:f.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()},onError:j=>{console.error("Remove access failed:",j)}})}else{const p=n==="tenant"&&a==="allTenants",j=n==="tenant"&&a==="allTenantUsers";if(p){const f=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(f){const y=Ie(l,o,[{scope:"all_tenants_only",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:I=>{console.error("Remove all-tenants access failed:",I)}})}}else if(j){const f=(x=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:x[0];if(f){const y=Ie(l,o,[{scope:"all_tenant_users",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:I=>{console.error("Remove all-tenant-users access failed:",I)}})}}else{const f=(b=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:b[0];if(f){const y=Ie(l,o,[{scope:"org_users_only",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:I=>{console.error("Remove org-wide access failed:",I)}})}}}}function Nn(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=He({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=A.useCallback(()=>{r.resetUserSelections()},[r]),m=A.useCallback(()=>{r.resetGroupSelections()},[r]),h=A.useCallback(g=>{if(!t)return;const b={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:u,resetGroupSelections:m};vn(g,b,i)},[t,n,a,d,u,m,i]),x=A.useCallback(()=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:u};yn(l,o||"",c||"",g)},[t,n,a,d,u,m,l,o,c]);return{handleShareSubmit:h,handleRemoveAccess:x}}function hs({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var E,w,M,L,O,R,P,G;const{currentUser:o}=s.useCurrentUserInfo(),[c,i]=A.useState("specific_users"),[d,u]=A.useState("specific_users"),[m,h]=A.useState("specific_groups"),x=s.useShareManagementActions(),g=s.useShareSelectedTab(),b=s.useShareCurrentMode(),p=s.useShareResource(),j=s.useRemoveResourceShares(),{handleShareSubmit:f,handleRemoveAccess:y}=Nn(t.id,(J,V)=>{p.mutate(J,{...V,onSuccess:()=>{var K;(K=V==null?void 0:V.onSuccess)==null||K.call(V),r==null||r()}})},(J,V)=>{j.mutate(J,{...V,onSuccess:()=>{var K;(K=V==null?void 0:V.onSuccess)==null||K.call(V),l==null||l()}})}),I=p.isPending,D=j.isPending,N=p.isPending,{existingShares:S}=He({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:v}=He({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),k=(w=(E=S==null?void 0:S.shares)==null?void 0:E.tenantWide)==null?void 0:w[0],C=(L=(M=v==null?void 0:v.shares)==null?void 0:M.orgUsersOnly)==null?void 0:L[0],F=()=>{if(g==="org")return d;switch(b){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},T=A.useCallback(()=>{x.resetShareState(),a()},[x,a]),B=(o==null?void 0:o.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:T,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(Ye,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:B?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),B?e.jsxs(s.Tabs,{value:g,onValueChange:J=>{const V=J;x.setSelectedTab(V),x.resetUserSelections(),x.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-3",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"}),e.jsx(s.TabsTrigger,{value:"groups",children:"Groups"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(xn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:u,isSharing:I,isUpdating:N,isRemoving:D})})}),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(qs,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:J=>i(J),isSharing:I,isUpdating:N,isRemoving:D})})}),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(gn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:h,isSharing:I,isUpdating:N,isRemoving:D})})})]}):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(qs,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:J=>i(J),isSharing:I,isUpdating:N,isRemoving:D})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:B?g==="org"?e.jsx(Hs,{resource:t,existingShares:v,isSharing:I,isRemoving:D,isUpdating:N,onShare:f,onClose:a,shareTabType:d,currentAllUsersShare:C,onRemoveAccess:y}):g==="tenant"?e.jsx(Hs,{resource:t,existingShares:S,isSharing:I,isRemoving:D,isUpdating:N,onShare:f,onClose:a,shareTabType:F(),currentAllUsersShare:k,onRemoveAccess:y}):e.jsx(bn,{resource:t,existingShares:v,isSharing:I,isRemoving:D,isUpdating:N,onShare:f,onClose:a,shareTabType:m,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(R=(O=v==null?void 0:v.shares)==null?void 0:O.allOrgGroups)==null?void 0:R[0]:(G=(P=S==null?void 0:S.shares)==null?void 0:P.allTenantGroups)==null?void 0:G[0],onRemoveAccess:y}):e.jsx(jn,{resource:t,isSharing:I,isRemoving:D,isUpdating:N,onShare:f,onClose:a,shareTabType:c,currentAllUsersShare:k,onRemoveAccess:y})})]})})}function yt({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(u=>u.selectedFrameId),l=s.useManagementStore(u=>u.selectedVisual),o=s.useEditorStore(u=>u.frame);let c;if(t)c=t;else if(n!==void 0)c=n?"linked":"library";else if(!!!(o!=null&&o.visualId||l!=null&&l.id)&&r)c="local";else if(l&&!r)c="library";else if(o!=null&&o.visualId&&r)c="linked";else if(l!=null&&l.id&&r)c="library";else return null;const i={local:"bg-gray-100 text-gray-700",linked:"bg-purple-100 text-purple-700",library:"bg-blue-100 text-blue-700"},d={local:"Local Visual",linked:"Linked Visual",library:"Library Visual"};return e.jsx("span",{className:s.cn("rounded-full px-2.5 py-0.5 text-xs font-medium",i[c],a),children:d[c]})}const Cn=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},Sn=async(t,n,a)=>{const r=`${t}/management/v1/groups/${a}`,l=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!l.ok){const o=await l.text();throw new Error(o||"Failed to delete group")}},wn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},Dn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,o=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.text();throw new Error(c||"Failed to remove group members")}};function Tn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Cn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:()=>{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 kn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Sn(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})=>wn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members added successfully")},onError:r=>{console.error("Failed to add group members:",r),s.ue.error("Failed to add members",{description:r.message})}})}function In(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Dn(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 An({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=A.useState(""),[o,c]=A.useState(""),[i,d]=A.useState({}),u=Tn(),m=()=>{const x={};return r.trim()?r.length<3?x.name="Group name must be at least 3 characters":r.length>50&&(x.name="Group name must be less than 50 characters"):x.name="Group name is required",o&&o.length>200&&(x.description="Description must be less than 200 characters"),d(x),Object.keys(x).length===0},h=async x=>{if(x.preventDefault(),!m())return;const g={name:r.trim(),description:o.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(g),l(""),c(""),d({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:h,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-name",children:["Group Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(s.Input,{id:"group-name",placeholder:"e.g., Marketing Team, Engineering Squad",value:r,onChange:x=>{l(x.target.value),i.name&&d(g=>({...g,name:""}))},className:i.name?"border-destructive":"",disabled:u.isPending}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-description",children:["Description",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(optional)"})]}),e.jsx(s.Textarea,{id:"group-description",placeholder:"Describe the purpose of this group...",value:o,onChange:x=>{c(x.target.value),i.description&&d(g=>({...g,description:""}))},className:i.description?"border-destructive":"",disabled:u.isPending,rows:3}),i.description&&e.jsx("p",{className:"text-sm text-destructive",children:i.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.length,"/200 characters"]})]}),e.jsx("div",{className:"rounded-lg border bg-muted/50 p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This group will be accessible to users in your workspace. You can add members after creating the group."})]})})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(s.Button,{type:"button",variant:"outline",onClick:()=>{l(""),c(""),d({})},disabled:u.isPending,children:"Clear"}),e.jsx(s.Button,{type:"submit",disabled:u.isPending||!r.trim(),children:u.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),"Create Group"]})})]})]})}function Mn({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,o]=A.useState("members"),[c,i]=A.useState(""),[d,u]=A.useState([]),[m,h]=A.useState([]),{data:x,isLoading:g,refetch:b}=s.useGroupMembers(a.id),p=a.type==="TENANT_GROUP"?"tenant":"organization",{users:j,isLoading:f}=s.useUnifiedUsers({type:p,tenantId:a.tenantId||void 0,active:!0,limit:100}),y=En(),I=In(),D=(x==null?void 0:x.members)||[],N=A.useMemo(()=>new Set(D.map(E=>E.userId)),[D]),S=A.useMemo(()=>j.filter(E=>!N.has(E.id)),[j,N]),v=A.useMemo(()=>{if(!c)return S;const E=c.toLowerCase();return S.filter(w=>{var M,L;return((M=w.name)==null?void 0:M.toLowerCase().includes(E))||((L=w.email)==null?void 0:L.toLowerCase().includes(E))})},[S,c]),k=A.useMemo(()=>{if(!c)return D;const E=c.toLowerCase();return D.filter(w=>{var M,L,O,R;return((L=(M=w.user)==null?void 0:M.name)==null?void 0:L.toLowerCase().includes(E))||((R=(O=w.user)==null?void 0:O.email)==null?void 0:R.toLowerCase().includes(E))})},[D,c]),C=async()=>{if(d.length!==0)try{await y.mutateAsync({groupId:a.id,data:{userIds:d,userType:p==="tenant"?"tenant":"org"}}),u([]),o("members"),b(),r==null||r()}catch(E){console.error("Failed to add members:",E)}},F=async()=>{if(m.length!==0)try{await I.mutateAsync({groupId:a.id,data:{userIds:m}}),h([]),b(),r==null||r()}catch(E){console.error("Failed to remove members:",E)}},T=E=>{u(w=>w.includes(E)?w.filter(M=>M!==E):[...w,E])},B=E=>{h(w=>w.includes(E)?w.filter(M=>M!==E):[...w,E])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:a.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[D.length," ",D.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",a.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:E=>{o(E),i(""),h([])},className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"members",children:"Current Members"}),e.jsx(s.TabsTrigger,{value:"add",children:"Add Members"})]}),e.jsxs(s.TabsContent,{value:"members",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search members...",value:c,onChange:E=>i(E.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:g?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(E=>e.jsx(s.Skeleton,{className:"h-16 w-full"},E))}):k.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:c?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:k.map(E=>e.jsx(Ln,{member:E,selected:m.includes(E.userId),onToggle:()=>B(E.userId)},E.id))})}),m.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m.length," member",m.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:F,disabled:I.isPending,children:I.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Removing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove Selected"]})})]})]}),e.jsxs(s.TabsContent,{value:"add",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search users to add...",value:c,onChange:E=>i(E.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:f?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(E=>e.jsx(s.Skeleton,{className:"h-16 w-full"},E))}):v.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.UserPlus,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No available users"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:v.map(E=>e.jsx(Rn,{user:E,selected:d.includes(E.id),onToggle:()=>T(E.id)},E.id))})}),d.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[d.length," user",d.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:C,disabled:y.isPending,children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.UserPlus,{className:"mr-2 h-4 w-4"}),"Add Members"]})})]})]})]})]})})})}function Ln({member:t,selected:n,onToggle:a}){var l,o,c,i;const r=((o=(l=t.user)==null?void 0:l.name)==null?void 0:o.split(" ").map(d=>d[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:((c=t.user)==null?void 0:c.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(i=t.user)==null?void 0:i.email})]})]})}function Rn({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(o=>o[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.email})]})]})}function On({open:t,onOpenChange:n}){const[a,r]=A.useState("groups"),[l,o]=A.useState(""),[c,i]=A.useState(null),[d,u]=A.useState(!1),[m,h]=A.useState(null),{tokenProps:x}=s.useSemaphorContext(),{currentUser:g}=s.useCurrentUserInfo(),b=kn(),p=(g==null?void 0:g.type)==="tenant",j=x==null?void 0:x.tenantId,{groups:f,isLoading:y,refetch:I}=s.useGroups({type:p?"TENANT_GROUP":"all",tenantId:p?j:void 0,includeMembers:!1}),D=f.filter(k=>{var C;return k.name.toLowerCase().includes(l.toLowerCase())||((C=k.description)==null?void 0:C.toLowerCase().includes(l.toLowerCase()))}),N=async()=>{if(m)try{await b.mutateAsync(m.id),h(null),I()}catch(k){console.error("Failed to delete group:",k)}},S=k=>{i(k),u(!0)},v=()=>{r("groups"),I()};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:k=>o(k.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:y?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(k=>e.jsx(s.Skeleton,{className:"h-24 w-full"},k))}):D.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:D.map(k=>e.jsx(Fn,{group:k,onManageMembers:()=>S(k),onDelete:()=>h(k),currentUserId:g==null?void 0:g.id},k.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(An,{onSuccess:v,tenantId:j,isTenantUser:p})})]})]})}),c&&e.jsx(Mn,{open:d,onOpenChange:u,group:c,onUpdate:()=>I()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>h(null),children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Group"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.name,'"? This action cannot be undone and will remove all members from the group.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:N,disabled:b.isPending,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete Group"})]})]})})]})}function Fn({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 As(t){const[n,a]=A.useState(null),[r,l]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),a(null)}})()},[t]),n}function Bn(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Pn(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return n}}return t[0].id}async function Ws(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],o=r.getQueryData(l);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const c=s.ue.loading("Loading visual...",{position:"top-center"});try{const i=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!i.ok)throw new Error("Failed to load visual");const d=await i.json();return r.setQueryData(l,d),s.ue.dismiss(c),{data:d,fromCache:!1}}catch(i){throw s.ue.dismiss(c),i}}function Nt(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function zn(t,n){var o,c;const a=(t==null?void 0:t.frameObject)??((o=t==null?void 0:t.visual)==null?void 0:o.frameObject);if(!a)return!1;const r=Nt(a);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(c=r.cards)==null?void 0:c.find(i=>i.id===r.activeCardId);return l?(s.setupEditorWithCard({...n,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function Vn(){var x;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=As(((x=a.customCardPreferences)==null?void 0:x.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),d=s.useEditorStore(g=>g.selectedConnectionId),u=s.useEditorStore(g=>g.isShowingVisual),m=a.sql;return{getUpdatedFrame:A.useCallback(()=>{var f;let g=m;m&&!m.includes("{{")&&(g=Bn(m),t(g));const b=(f=r==null?void 0:r.getState())==null?void 0:f.settings,p={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:u?a.customCfg:null,preferences:a.preferences,...b&&{customCardPreferences:{...a.customCardPreferences,settings:b}}},j=n.cards.map(y=>y.id===a.id?p:y);return{...n,cards:j,activeCardId:Pn(j,n.activeCardId)}},[a,n,u,l,o,c,i,d,t,r,m])}}function _e(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:g,setSelectedTableName:b,setSelectedDatamodelId:p,setFilterValues:j,setApplyFilters:f}=s.useEditorActions(),{setIsDashboardEditing:y,setIsVisualEditing:I,setSelectedFrameId:D,clearSelectedFrameId:N,addFrame:S,setIsDashboardPanelOpen:v}=s.useDashboardActions(),k=s.useDashboardStore(M=>M.selectedSheetId),C=s.useDashboardStore(M=>M.selectedFrameId),F=s.useDashboardStore(M=>M.dashboard),T=s.useDashboardStore(M=>M.filterValues),B=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),E=A.useCallback(async M=>{try{l(M),N();const{data:L,fromCache:O}=await Ws(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a);if(!zn(L,{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:g,setSelectedTableName:b,setSelectedDatamodelId:p,setFilterValues:j,setApplyFilters:f,setIsDashboardEditing:y,setIsVisualEditing:I,dashboard:F,selectedSheetId:k,selectedFrameId:C,filterValues:T}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:O}}catch(L){return console.error("Error editing visual:",L),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,o,c,y,I,i,d,u,m,h,x,g,b,p,j,f,N,F,k,C,T]),w=A.useCallback(async M=>{var L;try{if(l(M),!k)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:O,fromCache:R}=await Ws(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a),P=(O==null?void 0:O.frameObject)??((L=O==null?void 0:O.visual)==null?void 0:L.frameObject);if(!P)return{success:!1,error:"Visual has no frame data"};const G=Nt(P);if(!(G!=null&&G.cards)||G.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const J={...G,id:s.v4(),visualId:M.id};return S(k,J,"end"),y(!0),D(J.id),v(!1),{success:!0,fromCache:R}}catch(O){return console.error("Error adding visual:",O),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,k,S,y,D,v]);return{visual:B.data,isLoading:B.isLoading,isError:B.isError,error:B.error,handleEditLibraryVisual:E,handleAddLibraryVisual:w,getUpdatedFrame:Vn().getUpdatedFrame,refetch:B.refetch}}function _n({open:t,onOpenChange:n,isLibraryVisual:a,currentVisualName:r,isSaving:l=!1,onConfirm:o}){const[c,i]=A.useState(a&&r?`Copy of ${r}`:r||""),[d,u]=A.useState(""),[m,h]=A.useState(!a),[x,g]=A.useState(!0);A.useEffect(()=>{t&&(i(a&&r?`Copy of ${r}`:r||""),u(""),h(!a),g(!0))},[t,a,r]);const b=()=>{c.trim()&&(!m&&!x||o({name:c.trim(),description:d.trim()||void 0,saveToLibrary:m,saveToCurrentDashboard:x}))},p=c.trim()&&(m||x);return e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Save Visual As"}),e.jsx(s.DialogDescription,{children:a?"Create a copy of this visual with a new name":"Save this visual to make it reusable"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:c,onChange:j=>i(j.target.value),placeholder:"Enter visual name",disabled:l})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Textarea,{id:"description",value:d,onChange:j=>u(j.target.value),placeholder:"Enter visual description",rows:3,disabled:l})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Label,{children:"Save to:"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-dashboard",checked:x,onCheckedChange:j=>g(!!j),disabled:l}),e.jsxs("label",{htmlFor:"save-to-dashboard",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Current Dashboard",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(add copy to this dashboard)":"(keep as local visual)"})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-library",checked:m,onCheckedChange:j=>h(!!j),disabled:l}),e.jsxs("label",{htmlFor:"save-to-library",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Visual Library",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!m&&!x&&e.jsx("p",{className:"text-sm text-destructive",children:"Please select at least one destination"})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),disabled:l,children:"Cancel"}),e.jsxs(s.Button,{onClick:b,disabled:!p||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function Ct({className:t,variant:n="outline"}){var i;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(d=>d.frame);const r=s.useEditorStore(d=>d.card);As(((i=r.customCardPreferences)==null?void 0:i.url)||""),s.useEditorStore(d=>d.selectedSchemaName),s.useEditorStore(d=>d.selectedDatamodelId),s.useEditorStore(d=>d.selectedDatabaseName),s.useEditorStore(d=>d.selectedTableName),s.useEditorStore(d=>d.selectedConnectionId),s.useEditorStore(d=>d.isShowingVisual),r.sql;const l=s.useEditorStore(d=>d.onSave),{getUpdatedFrame:o}=_e();function c(){const d=o();l==null||l(d)}return e.jsxs(s.Button,{onClick:c,className:s.cn("h-8",t),size:"sm",variant:n,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Un({className:t,variant:n="default"}){const a=s.useQueryClient(),[r,l]=A.useState(!1),o=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),{setIsVisualEditing:c}=s.useDashboardActions(),{getUpdatedFrame:i}=_e(),d=s.useSelectedVisual(),u=s.useEditorStore(x=>x.frame),m=s.useUpdateVisualMutation(),h=()=>{const x=i(),g=(u==null?void 0:u.visualId)||(d==null?void 0:d.id);if(!g){s.ue.error("No visual to save");return}l(!0),m.mutate({visualId:g,data:{frameObject:x}},{onSuccess:()=>{l(!1),o(!0),s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["resource-by-id","visual",g],exact:!0})},onError:()=>{l(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:n,children:[r&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!r&&e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"mr-2 size-4 font-bold"}),"Save to Library"]})]})}function Gn({className:t}){const n=s.useQueryClient(),[a,r]=A.useState(!1),l=s.useSelectedVisual(),o=s.useEditorStore(x=>x.frame),c=s.useDashboardStore(x=>x.selectedSheetId),{updateFrame:i,setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:u}=_e(),m=s.useUpdateVisualMutation(),h=async()=>{if(!c){s.ue.error("No sheet selected");return}const x=(o==null?void 0:o.visualId)||(l==null?void 0:l.id);if(!x){s.ue.error("No visual to update");return}r(!0);try{const g=u();await m.mutateAsync({visualId:x,data:{frameObject:g}});const b={...g,visualId:x};i(c,b),n.invalidateQueries({queryKey:["visuals"]}),n.invalidateQueries({queryKey:["visual",x]}),s.ue.success("Saved to library and applied locally"),setTimeout(()=>{d(!1)},300)}catch(g){console.error("Failed to save and apply:",g),s.ue.error("Failed to save and apply changes")}finally{r(!1)}};return e.jsx(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:"default",disabled:a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"mr-2 size-4 font-bold"}),"Save & Apply"]})})}function Yn({className:t}){const{getUpdatedFrame:n}=_e();s.useEditorStore(d=>d.frame);const a=s.useDashboardStore(d=>d.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[o,c]=A.useState(!1),i=()=>{if(!a){s.ue.error("No sheet selected");return}c(!0);const u={...n(),visualId:void 0};r(a,u),setTimeout(()=>{c(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:i,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function St({className:t}){const{setTempQueryData:n,setSqlGen:a}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),o=s.useEditorStore(u=>u.onClose),c=s.useEditorStore(u=>u.card),{queryKey:i}=s.useDashboardCardQuery(c);function d(){if(l){const{queryKey:u,queryData:m}=l;u&&m&&r.setQueryData(u,m)}a({}),o==null||o()}return e.jsxs(s.Button,{onClick:d,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function xs(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(j=>j.isDevMode),r=s.useEditorStore(j=>j.tempQueryData),l=s.useEditorStore(j=>j.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:x,setCardConfig:g,setCardType:b}=s.useEditorActions();function p(){const j=n.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:j}),n.setQueryData(o,null),n.removeQueries({queryKey:o,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),x(),g(void 0),d(""),u(""),m({}),b("bar")}return e.jsxs(s.Button,{onClick:p,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function $n(){const[t,n]=A.useState(!1),[a,r]=A.useState(!1),[l,o]=A.useState(null),c=s.useEditorStore(D=>D.frame),i=s.useEditorStore(D=>D.card),d=s.useSelectedVisual(),u=s.useDashboardStore(D=>D.selectedSheetId),m=s.useDashboardStore(D=>D.actions.setIsDashboardPanelOpen),{getUpdatedFrame:h}=_e(),{selectVisual:x}=s.useManagementActions(),{addFrame:g,setSelectedFrameId:b,setIsVisualEditing:p}=s.useDashboardActions(),j=!!(c!=null&&c.visualId),f=(d==null?void 0:d.title)||(i==null?void 0:i.title)||"Untitled Visual",y=s.useCreateVisualWithFrame(D=>{if(D!=null&&D.id){if(x(D),a&&l&&u){const N={...l,id:s.v4(),visualId:D.id};g(u,N,"end"),b(N.id),r(!1),o(null),p(!1)}m(!0),n(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:n,handleSaveAs:async D=>{if(!u){s.ue.error("No sheet selected");return}const N=h();if(D.saveToLibrary){r(D.saveToCurrentDashboard),o(N);const S={title:D.name,description:D.description,frameObject:N,isPrivate:!1};y.mutate(S)}else if(D.saveToCurrentDashboard){const S={...N,id:s.v4(),visualId:void 0,cards:N.cards.map(v=>({...v,title:v.id===i.id?D.name:v.title}))};g(u,S,"end"),b(S.id),s.ue.success("Visual saved to dashboard"),n(!1),p(!1)}},isLibraryVisual:j,currentVisualName:f,isSaving:y.isPending}}function wt({className:t}){const n=s.useEditorStore(y=>y.frame),a=s.useEditorStore(y=>y.card),r=s.useManagementStore(y=>y.selectedVisual),l=s.useDashboardStore(y=>y.selectedFrameId),o=s.useDashboardStore(y=>y.selectedSheetId),{setIsVisualEditing:c}=s.useDashboardActions(),i=!!(n!=null&&n.visualId||r!=null&&r.id),d=!!(n!=null&&n.visualId&&l),u=i&&!d,{saveAsDialogOpen:m,setSaveAsDialogOpen:h,handleSaveAs:x,isLibraryVisual:g,currentVisualName:b,isSaving:p}=$n(),{handleAddLibraryVisual:j}=_e(),f=async()=>{if(!o){s.ue.error("No dashboard sheet selected");return}if(!r){s.ue.error("No visual selected");return}const y=await j(r);y.success?(s.ue.success("Visual added to dashboard"),c(!1)):s.ue.error(y.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[!i&&e.jsx(Ct,{className:t,variant:"default"}),i&&e.jsxs(e.Fragment,{children:[d&&e.jsx(Yn,{className:t}),u&&o&&a&&(a.sql||s.hasValidCardConfig(a.config))&&e.jsxs(s.Button,{onClick:f,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(fa,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),u&&e.jsx(Un,{className:t,variant:"default"}),d&&e.jsx(Gn,{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:y=>{y.stopPropagation(),h(!0)},children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]})]}),!i&&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:()=>h(!0),children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(St,{className:t}),e.jsx(_n,{open:m,onOpenChange:y=>{p||h(y)},isLibraryVisual:g,currentVisualName:b,isSaving:p,onConfirm:x})]})}function Dt({className:t,labelClassName:n,switchClassName:a}){const r=s.useEditorStore(d=>d.isDevMode),l=s.useDashboardStore(d=>d.isVisualEditing),{setIsDevMode:o}=s.useEditorActions(),{config:c}=A.useContext(s.SemaphorContext).tokenProps,i=(c==null?void 0:c.showAdvancedMode)!==!1;return!l||!i?null:e.jsxs("div",{className:s.cn("flex items-center space-x-2",t),children:[e.jsx(s.Switch,{className:s.cn("",a),checked:r,onCheckedChange:()=>o(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:s.cn("text-sm font-medium",n),children:"Advanced Mode"})]})}function qn(){var de,ue,xe;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:o}=s.useRoleAwareDisplayPreferences(),c=s.useHasDashboardId();s.useDashboardStore(W=>W.theme);const i=s.useDashboardStore(W=>W.lenses),d=s.useDashboardStore(W=>W.selectedLensId),u=i==null?void 0:i.find(W=>W.id===d),m=s.useDashboardStore(W=>W.dashboard);s.useDashboardStore(W=>W.selectedSheetId);const h=s.useDashboardStore(W=>W.isDashboardEditing),[x,g]=A.useState(!1),[b,p]=A.useState(!1),[j,f]=A.useState(!1),y=s.useDashboardStore(W=>W.isDashboardPanelOpen),I=s.useDashboardStore(W=>W.actions.setIsDashboardPanelOpen),D=s.useDashboardStore(W=>W.filterValues),N=s.useDashboardStore(W=>W.isVisualEditing),S=s.useEditorStore(W=>W.card),v=s.useManagementStore(W=>W.selectedDashboard),k=s.useManagementStore(W=>W.initialDashboard),C=s.useManagementStore(W=>W.selectedVisual);s.useDashboardStore(W=>W.selectedFrameId),s.useEditorStore(W=>W.frame);const F=v?(ue=v==null?void 0:v.permissions)==null?void 0:ue.canEdit:(de=k==null?void 0:k.permissions)==null?void 0:de.canEdit,T=s.useDashboardStore(W=>W.showFilters),B=s.useDashboardStore(W=>W.showDashboardJSON),E=s.useDashboardStore(W=>W.onSaveFunction),w=s.useDashboardStore(W=>W.actions.setShowFilters),{setIsDashboardEditing:M,setShowDashboardJSON:L}=s.useDashboardStore(W=>W.actions),{setInitialDashboard:O,clearSelectedDashboard:R}=s.useManagementStore(W=>W.actions),{resources:P}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:G}=s.useCurrentUserInfo(),J=s.canUserManageGroups(G),V=v||k,K=V?{id:V.id,title:(m==null?void 0:m.title)||V.title||"Dashboard"}:null,{handleAddNewFrame:$}=s.useAddNewFrame(),[X,q]=A.useState(!1),Q=s.useUpdateResource(s.ResourceType.DASHBOARD);A.useEffect(()=>{if(P&&P.length>0){const W=m==null?void 0:m.id;if(W){const U=P.find(ee=>ee.id===W);U&&O(U)}}},[P,m==null?void 0:m.id,O]);const _=n.orgUserId||n.tenantId,te=h&&!N&&_&&F,re=()=>{M(!0)};async function he(){const W=is(m);q(!0);const U={template:W};Q.mutate({resourceId:W.id,data:U},{onSuccess:()=>{q(!1),s.ue.success("Dashboard saved!")},onError:()=>{q(!1),s.ue.error("Failed to save dashboard")}})}async function ge(){if(g(!0),!d||!u)return;const W=is(m),U=JSON.stringify(W),ee={...u,template:U,filterValues:D};await Ds(n.apiServiceUrl,ee,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),E==null||E(W),g(!1)}const z=(u==null?void 0:u.name)||m.title,ae=P&&P.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),oe=v&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-11 items-center justify-between gap-2 border-b px-4 py-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[ae&&e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>{I(!y)},className:"h-7 p-2",children:e.jsx(Ra,{className:"h-4 w-4"})}),oe&&!N&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Dashboard Hub",onClick:()=>R(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})})]}),!N&&c&&e.jsx(s.Label,{children:z}),N&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm font-medium",children:(C==null?void 0:C.title)||(S==null?void 0:S.title)||"Untitled Visual"}),e.jsx(yt,{})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[N&&e.jsxs(e.Fragment,{children:[e.jsx(Dt,{className:"mr-2"}),e.jsx(wt,{className:"h-7"})]}),r&&!N&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(Ga,{className:"h-4 w-4"})}),!N&&c&&e.jsx(tn,{}),!N&&c&&e.jsx(dt,{}),!N&&c&&J&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!N&&c&&((xe=V==null?void 0:V.permissions)==null?void 0:xe.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),!T&&!N&&h&&o.canUseFilters&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>w(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),h&&!N&&_&&r&&c&&e.jsx(en,{}),!N&&_&&r&&c&&e.jsx(sn,{}),h&&!N&&_&&u&&r&&c&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:x,onClick:ge,size:"sm",children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),h&&!N&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!h,onClick:()=>$(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!N&&!h&&o.canEdit&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:re,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),te&&c&&e.jsxs(s.Button,{className:"h-7 p-2",disabled:X,onClick:he,size:"sm",children:[X?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(qe,{className:"mr-2 h-4 w-4"}),X?"Saving...":"Save"]}),!N&&h&&r&&c&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>L(!B),size:"sm",variant:"ghost",children:e.jsx($e,{className:"h-4 w-4"})})}),!N&&r&&e.jsx(Qa,{}),h&&!N&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{M(!1),L(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),b&&K&&e.jsx(hs,{resource:K,resourceType:s.ResourceType.DASHBOARD,onClose:()=>p(!1)}),e.jsx(On,{open:j,onOpenChange:f})]})]})}function Hn({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:u=!1}){const m=Oe.useRef(null),[h,x]=Oe.useState(!1),[g,b]=Oe.useState("100%"),p=u?[...n||[],{id:"none",name:"None"}]:n;Oe.useLayoutEffect(()=>{m.current&&b(m.current.offsetWidth)},[]);function j(){var y;return l?"Loading...":o?"Error":a?(y=n==null?void 0:n.find(I=>I.id===a))==null?void 0:y.name:`Select ${t}`}function f(y,I){r(I),x(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:x,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:j()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:g},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(rt,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:p==null?void 0:p.map(y=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:y.name,onSelect:I=>f(I,y.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===y.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:y.name,children:y.name})]})},y.id))})]})]})})]})}function Ge({title:t,items:n,value:a,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":a;function x(){if(t==="Connection")return e.jsx(Va,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Ba,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(xa,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:u,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(rt,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((p,j)=>e.jsx(s.SelectItem,{value:p.id,children:p.name},j))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function b(){return e.jsx(Hn,{icon:x(),items:n,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?g():b()})})}function Wn({column:t}){const[n,a]=A.useState(!1),r=s.useEditorStore(p=>p.selectedTableName),l=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedDatabaseName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(p=>p.actions.setSqlGen),h=s.useEditorStore(p=>p.actions.setCardSql),x=s.useEditorStore(p=>p.actions.setRunSql);function g(p,j){var D;const f=s.createSqlGenConfig(p,i,j),y=(D=d==null?void 0:d.find(N=>N.id===c))==null?void 0:D.name;m(f);const I=s.getSql(f,s.fmt(l||""),s.fmt(r),y||"",u,o||"");I&&(h(I),x(!0)),a(!1)}function b(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>g(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>g(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>g(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>g(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>g(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]})}function Kn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(we,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Me,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ze,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx($e,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Xe,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ss,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(we,{className:"h-3 w-3"})})}function gs({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",n),children:[e.jsx(Kn,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Qn({id:t,children:n,type:a="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:a}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:n})}function Jn({onClick:t,column:n}){const a=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function u(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(n),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(gs,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(gs,{column:n})}),e.jsx(Qn,{id:n.column_name,type:"column",children:e.jsx(gs,{column:n})})]})}const js={id:"__placeholder__",role:"groupby",type:"string"},bs={id:"__placeholder__",role:"groupby",type:"string"},vs={id:"__placeholder__",role:"metric",type:"number"},ys={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},Tt={id:"__placeholder__"},Fe="droppable-group-by",Be="droppable-metrics",Pe="droppable-pivot-by",ds="sortable-group-by",Ts="sortable-metrics",us="sortable-pivot-by",ks="droppable-filters",Es="sortable-filters",Ms="sortable-order-by";function Xn(){const t=s.useDndStore(w=>w.insertIndex),n=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.groupByColumns)||[]}),a=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.metricColumns)||[]}),r=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.filterColumns)||[]}),l=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.orderBy)||[]}),o=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:x,setMetricColumns:g,setFilterColumns:b,setOrderByColumns:p,setPivotByColumns:j}=s.useEditorActions(),{columns:f}=s.useDataColumns(),{formattedTableName:y}=s.useEditorAside(),I=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),D=w=>{var O;const{active:M,over:L}=w;if(((O=M.data.current)==null?void 0:O.type)==="column"&&L){const R=L.id,P=f.find(K=>K.column_name===M.id);if(!P)return;const G=s.isNumberDataType(P.data_type),J=s.isTextDataType(P.data_type),V=s.isDateDataType(P.data_type);if(J||V){if(n.some($=>$.id===R)){const $=n.findIndex(q=>q.id===R);c($);const X=n.filter(q=>q.id!==js.id);X.splice($,0,js),d(X)}else if(L.id===Fe){c(n.length);const $=[...n,js];d($),u(a),m(r)}}if(J||V){if(o.some($=>$.id===R)){const $=o.findIndex(q=>q.id===R);c($);const X=o.filter(q=>q.id!==bs.id);X.splice($,0,bs),h(X)}else if(L.id===Pe){c(o.length);const $=[...o,bs];h($),d(n),u(a),m(r)}}if(G||J){if(a.some($=>$.id===R)){console.log("isOverMetricSortable",R);const $=a.findIndex(q=>q.id===R);c($);const X=a.filter(q=>q.id!==vs.id);X.splice($,0,vs),u(X)}else if(L.id===Be){c(a.length);const $=[...a,vs];u($),m(r),d(n),h(o)}}if(S(P)){if(r.some($=>$.id===R)){const $=r.findIndex(q=>q.id===R);c($);const X=r.filter(q=>q.id!==ys.id);X.splice($,0,ys),m(X)}else if(L.id===ks){c(r.length);const $=[...r,ys];m($),u(a),d(n),h(o)}}}else d(n),u(a),m(r),h(o)};function N(w){i(w.active.id),c(null),d(n),u(a),m(r),h(o)}function S(w){return!r.some(M=>M.name===w.column_name)}function v(w,M="SUM"){const{column_name:L,data_type:O}=w,R=[...a],P=t!==null?t:a.length,G={...w,id:Te(L),name:L,label:es(L,M),type:O,role:"metric",aggregate:M};R.splice(P,0,G),g(R)}function k(w){const M=s.isTextDataType(w.data_type);s.isDateDataType(w.data_type);const L=[...o],O=t!==null?t:o.length;let R;M?R={...w,id:Te(w.column_name),name:w.column_name,type:w.data_type,role:"groupby"}:R={...w,id:Te(w.column_name),name:w.column_name,type:w.data_type,role:"groupby",label:We(w.column_name,"month"),granularity:"month"},L.splice(O,0,R),j(L)}function C(w){const M=s.isTextDataType(w.data_type);s.isDateDataType(w.data_type);const L=[...n],O=t!==null?t:n.length;let R;M?R={...w,id:Te(w.column_name),name:w.column_name,type:w.data_type,role:"groupby"}:R={...w,id:Te(w.column_name),name:w.column_name,type:w.data_type,role:"groupby",label:We(w.column_name,"month"),granularity:"month"},L.splice(O,0,R),x(L)}function F(w){const M=[...r],L=t!==null?t:r.length,O={...w,id:Te(w.column_name),name:w.column_name,type:w.data_type,sql:s.getDefaultFilterSql(w.data_type,y,s.fmt(w.column_name)),role:"filter"};M.splice(L,0,O),b(M)}function T(w){var R,P,G,J,V,K,$,X;const{active:M,over:L}=w,O=M.data.current;if((O==null?void 0:O.type)==="column"&&L){const q=f.find(re=>re.column_name===M.id);if(!q)return;const Q=s.isNumberDataType(q.data_type),_=s.isTextDataType(q.data_type),te=s.isDateDataType(q.data_type);(_||te)&&(L.id===Fe||((R=L.data.current)==null?void 0:R.type)===ds)&&C(q),(_||te)&&(L.id===Pe||((P=L.data.current)==null?void 0:P.type)===us)?k(q):(Q||_)&&(L.id===Be||((G=L.data.current)==null?void 0:G.type)===Ts)?(Q&&v(q),_&&v(q,"COUNT")):S(q)&&(L.id===ks||((J=L.data.current)==null?void 0:J.type)===Es)&&F(q)}if(L&&((V=L.data.current)==null?void 0:V.type)===ds&&n.some(q=>q.id===M.id)){const q=n.findIndex(_=>_.id===M.id),Q=n.findIndex(_=>_.id===L.id);if(q!==-1&&Q!==-1&&q!==Q){const _=[...n],[te]=_.splice(q,1);_.splice(Q,0,te),x(_)}}if(L&&((K=L.data.current)==null?void 0:K.type)===us&&o.some(q=>q.id===M.id)){const q=o.findIndex(_=>_.id===M.id),Q=o.findIndex(_=>_.id===L.id);if(q!==-1&&Q!==-1&&q!==Q){const _=[...o],[te]=_.splice(q,1);_.splice(Q,0,te),j(_)}}if(L&&(($=L.data.current)==null?void 0:$.type)===Ts&&a.some(q=>q.id===M.id)){const q=a.findIndex(_=>_.id===M.id),Q=a.findIndex(_=>_.id===L.id);if(q!==-1&&Q!==-1&&q!==Q){const _=[...a],[te]=_.splice(q,1);_.splice(Q,0,te),g(_)}}if(L&&((X=L.data.current)==null?void 0:X.type)===Es&&r.some(q=>q.id===M.id)){const q=r.findIndex(_=>_.id===M.id),Q=r.findIndex(_=>_.id===L.id);if(q!==-1&&Q!==-1&&q!==Q){const _=[...r],[te]=_.splice(q,1);_.splice(Q,0,te),b(_)}}B(w),i(null),c(null),d(n),u(a),m(r),h(o)}function B(w){const{active:M,over:L}=w,O=M.data.current;if((O==null?void 0:O.type)===Ms&&L){const R=l.findIndex(G=>Je(G.columnId)===M.id),P=l.findIndex(G=>Je(G.columnId)===L.id);if(R!==-1&&P!==-1&&R!==P){const G=[...l],[J]=G.splice(R,1);G.splice(P,0,J),p(G)}}}function E(){i(null),c(null),d(n),u(a),m(r)}return{handleDragOver:D,handleDragEnd:T,handleDragStart:N,handleDragCancel:E,sensors:I}}function Te(t){return`${t}-${s.v4()}`}function es(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 Je(t){return`${Ms}-${t}`}function We(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 Zn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(we,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Me,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ze,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx($e,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Xe,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ss,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(we,{className:"h-3 w-3"})})}function er({schemaName:t,tableName:n,columns:a,status:r}){const[l,o]=A.useState(""),[c,i]=A.useState("all"),d=s.useEditorStore(R=>R.sqlGen),u=s.useEditorStore(R=>R.isDevMode);s.useEditorStore(R=>R.selectedConnectionId);const m=s.useEditorStore(R=>{var P,G;return(G=(P=R.card)==null?void 0:P.queryConfig)==null?void 0:G.metricColumns});s.useEditorStore(R=>{var P,G;return(G=(P=R.card)==null?void 0:P.queryConfig)==null?void 0:G.groupByColumns});const h=s.useEditorStore(R=>R.selectedDatabaseName);s.useEditorStore(R=>R.selectedSchemaName),s.useEditorStore(R=>R.selectedTableName);const x=s.useEditorStore(R=>R.selectedDatamodelId);s.useDashboardStore(R=>R.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:b}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:j,setCardSql:f,setRunSql:y,setSqlGen:I,setIsShowingVisual:D}=s.useEditorActions(),{connectionType:N,modelItems:S,selectedDatamodelName:v}=s.useEditorAside();function k(R){var P;if(u){const G=s.createSqlGenConfig(R,d);I(G);const J=(P=S==null?void 0:S.find(K=>K.id===x))==null?void 0:P.name,V=s.getSql(G,s.fmt(t),s.fmt(n),J||"",N,h||"");V&&(f(V),y(!0))}if(!u){if(s.isTextDataType(R.data_type))if(m&&m.length>0){const G={...R,role:"groupby",id:Te(R.column_name),name:R.column_name,type:R.data_type};j(G)}else{const G={...R,role:"metric",id:Te(R.column_name),name:R.column_name,label:es(R.column_name,"COUNT"),type:R.data_type,aggregate:"COUNT"};p(G)}if(s.isDateDataType(R.data_type)){const G={...R,role:"groupby",id:Te(R.column_name),name:R.column_name,type:R.data_type,label:We(R.column_name,"month"),granularity:"month"};j(G)}if(s.isNumberDataType(R.data_type)){const G={...R,role:"metric",id:Te(R.column_name),name:R.column_name,label:es(R.column_name,"SUM"),type:R.data_type,aggregate:"SUM"};p(G)}}}function C(){const R=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:N,databaseName:h||""});D(!1);const P=N==="MSSQL"?`SELECT top 10 * FROM ${R}`:`SELECT * FROM ${R} LIMIT 10`;f(P),y(!0)}function F(){const R=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:N,databaseName:h||""});f(`SELECT COUNT(*) as count FROM ${R}`),y(!0)}const T=(a==null?void 0:a.filter(R=>R.column_name.toLowerCase().includes(l.toLowerCase())))||[],B=R=>s.isNumberDataType(R.data_type)?"number":"text",E=c==="all"?T:T.filter(R=>B(R)===c),w=T.filter(R=>B(R)==="text").length,M=T.filter(R=>B(R)==="number").length;function L(R){return u?e.jsxs("div",{className:"group flex cursor-pointer items-center justify-between border border-dashed border-background px-2 py-[6px] text-sm transition-colors hover:bg-muted/50",onClick:()=>k(R),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zn,{dataType:R.data_type}),e.jsx("span",{children:R.column_name})]}),e.jsx("div",{onClick:P=>P.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(R.data_type)&&e.jsx(Wn,{column:R})})]}):e.jsx(Jn,{onClick:k,column:R})}function O(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:C,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(La,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:F,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(lt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-4",children:Array.from({length:3}).map((R,P)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},P))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[u&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:O()}),a&&a.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:R=>o(R.target.value)})]}),T.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:R=>i(R),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:T.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:w})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:M})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[E.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),E.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:E==null?void 0:E.map(R=>e.jsx("div",{children:L(R)},R.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function kt({ColumnsComponent:t,type:n}){var W;const[a,r]=A.useState(!1),{isConsoleMode:l}=s.useDashboardPreferences(),o=s.useEditorStore(U=>U.card),c=s.useEditorStore(U=>U.selectedConnectionId),i=s.useDashboardStore(U=>U.showFilters),d=s.useEditorStore(U=>U.selectedDatamodelId),u=s.useEditorStore(U=>U.selectedDatabaseName),m=s.useEditorStore(U=>U.selectedSchemaName),h=s.useEditorStore(U=>U.selectedTableName);s.useEditorStore(U=>U.isDevMode);const{setSelectedTableName:x,setIsDevMode:g,setCardSql:b}=s.useEditorActions(),{connectionItems:p,modelItems:j,schemaItems:f,databaseItems:y,tableItems:I,columns:D,isConnectionsLoading:N,isModelsLoading:S,isConnectionsError:v,isModelsError:k,isDatabasesLoadingOrFetching:C,isDatabaseError:F,isSchemaLoadingOrFetching:T,isSchemaError:B,isColumnsError:E,isColumnsLoadingOrFetching:w,isTableLoadingOrFetching:M,isTableError:L,connectionType:O,isNonDbConnection:R,refetchDatabases:P,refetchModels:G,refetchSchemas:J,refetchTables:V,refetchColumns:K,refetchConnections:$,handleConnectionChange:X,handleDatabaseChange:q,handleSchemaChange:Q,handleDatamodelChange:_,handleTableChange:te,tableName:re,schemaName:he}=s.useEditorAside(),{data:ge,refetch:z}=s.useDashboardCardQuery(o);function Z(){return t?t(he,re,D):e.jsx(er,{schemaName:he,tableName:re,columns:D,status:w?"Loading...":E?"Error":"Success"})}function ae(){if(!c||O==="S3"||O==="API")return null;if(!d||d==="none")return e.jsx(Ge,{refetch:P,showNone:!0,onChange:q,isError:F,isLoading:C,items:y,value:u||"",title:"Database",type:"combobox"})}function oe(){if(c&&!R&&(!u||u==="none")&&(!d||d==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function de(){if(!c||O==="S3"||O==="API")return null;if(!u||u==="none")return e.jsx(Ge,{refetch:G,showNone:!0,onChange:_,isError:k,isLoading:S,items:j,value:d||"",title:"Model",type:"combobox"})}function ue(){return!c||O==="S3"||O==="API"||!u||u==="none"?null:e.jsx(Ge,{refetch:J,onChange:Q,isError:B,isLoading:T,items:f,value:m||"",title:"Schema",type:"combobox"})}function xe(){function U(){let ee=!1;return O==="API"?(ee=!1,ee):((O==="S3"||c&&u&&u!=="none"&&m)&&(ee=!0),ee)}return U()?e.jsx(Ge,{refetch:V,onChange:te,isError:L,items:I,isLoading:M,value:h||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!i}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":a,"px-4 py-4":!a}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!a),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:a?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!a&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ge,{refetch:$,items:p,title:"Connection",value:c||"",onChange:X,isLoading:N,isError:v,type:"combobox",connectionTooltip:((W=p==null?void 0:p.find(U=>U.id===c))==null?void 0:W.type)||""}),ae(),oe(),de(),ue(),xe()]})]}),Z(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&l&&e.jsx(e.Fragment,{})})]})}function Et({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:l=!0}){const[o,c]=A.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",r),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Query Error"}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),l&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function It({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){o(!l),c(t),setTimeout(()=>{i(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[n&&e.jsx(Et,{error:n,errorSql:a,showFeedbackButton:!1}),!n&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!n&&e.jsxs(s.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(Na,{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(ka,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function At({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(ga,{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(It,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function sr(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 Mt(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(p=>p.theme),r=s.useEditorStore(p=>p.frame),l=s.useEditorStore(p=>p.card),o=s.useEditorStore(p=>p.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=A.useRef(),h=A.useRef({}),x=r.cards.find(p=>p.id===o),g=A.useCallback(()=>{let p="";return t==="python"&&(p=(x==null?void 0:x.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(p=(x==null?void 0:x.sql)||""),p},[t,x]);A.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const p=m.current.getModel();p&&(h.current[l.id]=p);let j=h.current[o];if(!j){const f=g();j=c.editor.createModel(f,t),h.current[o]=j}m.current.setModel(j)}d(o,l),u(!0)}},[o,l,d,c,u,t,g]),A.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=a==="system"?p:a;c.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),A.useEffect(()=>{const p=m.current;p&&c&&l&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function b(p,j){if(m.current=p,!h.current[l.id]){const f=p.getModel(),y=g();h.current[l.id]=f||(j==null?void 0:j.editor.createModel(y,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:b}}function tr(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Mt("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function ar(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Mt("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 nr({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 rr(){const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=A.useState(!1),[l,o]=A.useState(!1);s.useEditorStore(V=>V.frame);const c=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.isShowingVisual),s.useEditorStore(V=>V.selectedConnectionId),s.useEditorStore(V=>V.tempQueryData),s.useEditorStore(V=>V.selectedDatabaseName),s.useEditorStore(V=>V.selectedDatamodelId),s.useEditorStore(V=>V.selectedSchemaName);const i=s.useEditorStore(V=>V.showAIDialog);s.useEditorStore(V=>V.selectedTableName);const d=s.useEditorStore(V=>{var K;return(K=V==null?void 0:V.card)==null?void 0:K.sql}),u=s.useEditorStore(V=>{var K;return(K=V==null?void 0:V.card)==null?void 0:K.python}),{cardFilterValues:m}=s.useCardFilterValues((c==null?void 0:c.id)??""),{setCardCustomCfg:h,setQueryResultColumns:x,setCardSql:g,setTempQueryData:b,setPythonStdOut:p,setCardPreferences:j,setCardType:f,setCardPython:y,runAssistant:I,setShowAIDialog:D}=s.useEditorActions();s.useEditorStore(V=>V.onSave),s.useEditorStore(V=>V.onClose),s.useEditorStore(V=>V.actions.setSqlGen);const N=s.useEditorStore(V=>V.runSql),S=s.useEditorStore(V=>V.actions.setRunSql),v=s.useEditorStore(V=>V.actions.setIsSqlRunning),{data:k,isLoading:C,isFetching:F,isSuccess:T,isError:B,error:E,errorSql:w,queryKey:M,refetch:L,errorMessage:O}=s.useDashboardCardQuery(c);A.useEffect(()=>{if(k&&(k.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),p((k==null?void 0:k.output)||""),k.records.length>0)){const{dimensionKeys:V}=s.getKeys(k.records);x(V)}},[k,x,p]),A.useEffect(()=>{(C||F)&&v(!0),(B||T)&&v(!1),B&&(x([]),p(""))},[C,F,k,p,B,T,v,x,E]),A.useEffect(()=>{N&&(t.getQueryData(M)||L(),S(!1))},[N,L,S,M,t]);async function R(){const V=`Can you help me debug this query?
312
312
 
313
313
  Error:
314
314
 
@@ -324,12 +324,12 @@
324
324
 
325
325
  ${u?`Python:
326
326
  ${u}`:""}
327
- `;E(_)}function z(){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(nr,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>o(!l),className:"absolute bottom-0 right-6 size-7 p-1",children:l?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function G(){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(tr,{})}),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(ar,{})}),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:N||F,onClick:()=>{L()},className:"h-8 shrink-0",size:"sm",children:[N||F?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(At,{errorSql:w,sql:k==null?void 0:k.sql,error:O,onDebugWithAssistant:R}),e.jsx(xs,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:_=>r(_),className:"h-8",size:"sm",variant:"outline",children:e.jsx(sr,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:i,onClick:()=>{D(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:i?"":"Type your question..."})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[G(),z()]}),Q()]})}const lr=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:ms}];function or({className:t}){const n=s.useEditorStore(d=>d.card),{setCardType:a,setCard:r,updateCardInFrame:l}=s.useEditorActions(),o=["table","aggregateTable","pivotTable"].includes(n.type),c=s.hasValidCardConfig(n.config);if(!o||!c)return null;const i=d=>{var m;const u=d;if(u==="aggregateTable"&&((m=n.config)!=null&&m.pivotByColumns)&&n.config.pivotByColumns.length>0){const h={...n,type:u,config:{...n.config,pivotByColumns:[]}};r(h),l(h)}else{a(u);const h={...n,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:i,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:lr.map(d=>{const u=d.icon,m=n.type===d.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:d.value,id:`table-type-${d.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${d.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",m?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),d.label]})]},d.value)})})})}function ir({card:t}){var E,D,C,S,v,k,N,F,T,B,I;const[n,a]=A.useState(!1),[r,l]=A.useState([]),{authToken:o}=s.useSemaphorContext(),{theme:c}=s.useTheme(),i=s.getTokenParams(o==null?void 0:o.accessToken),d=s.useDashboardStore(w=>w.themeStyle),u={mode:c||"system",colors:((D=(E=d==null?void 0:d.chart)==null?void 0:E.dataset)==null?void 0:D.backgroundColor)||[]};(C=t.customCardPreferences)!=null&&C.inputData;const{getCard:m}=s.useCustomVisual(((S=t.customCardPreferences)==null?void 0:S.url)||""),h=((v=t.customCardPreferences)==null?void 0:v.visualType)||"single",x=s.useEditorStore(w=>w.frame),{setCustomCardPreferences:g}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(t),p=A.useCallback((w,M)=>{l(L=>({...L,[w]:M}))},[]);if(!((k=t.customCardPreferences)!=null&&k.componentName))return null;const j=m((N=t.customCardPreferences)==null?void 0:N.componentName);function f(w){a(w)}const y=Object.keys(((F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)||{}).map(w=>{var O,R,z;const M=(R=(O=t.customCardPreferences)==null?void 0:O.dataInputCardIds)==null?void 0:R[w].cardId,L=(z=x==null?void 0:x.cards)==null?void 0:z.find(G=>G.id===M);return L||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(A.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[j&&h==="single"&&e.jsx(j,{editing:!0,params:i,theme:u,settings:(T=t.customCardPreferences)==null?void 0:T.settings,onDataChange:p,data:(b==null?void 0:b.records)||[]}),j&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((B=t.customCardPreferences)==null?void 0:B.dataInputCardIds)||{}).map(w=>{var O,R,z;const M=(R=(O=t.customCardPreferences)==null?void 0:O.dataInputCardIds)==null?void 0:R[w].cardId,L=(z=x==null?void 0:x.cards)==null?void 0:z.find(G=>G.id===M);if(L)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:f,onDataChange:p,dataInputIndex:w,card:L},L.id+w)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(j,{theme:u,onDataChange:p,settings:y.map(w=>{var M;return(M=w==null?void 0:w.customCardPreferences)==null?void 0:M.settings}),data:y.map(w=>w!=null&&w.id?r==null?void 0:r[w.id]:[])})})]})]},(I=t.customCardPreferences)==null?void 0:I.componentName)})}function Lt({className:t,...n}){var k;const a=s.useEditorStore(N=>N.card),r=s.isExplorerCard(a),l=((k=a.customCardPreferences)==null?void 0:k.showCardHeader)??!0,o=s.useEditorStore(N=>N.frame),c=s.useDashboardStore(N=>N.dashboard.filters),i=s.useEditorStore(N=>N.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),u=c==null?void 0:c.find(N=>N.id===o.filterId),{data:m,isLoading:h,isFetching:x,errorMessage:g,pagination:b}=s.useDashboardCardQuery(a),{setCard:p,updateCardInFrame:j}=s.useEditorActions(),{data:f}=s.useTopoJson(a),y=A.useMemo(()=>{var N;return a.type!=="pivotTable"||!((N=m==null?void 0:m.records)!=null&&N.length)?null:{records:m.records,columnSubtotalMeta:m.columnSubtotalMeta,subtotalColumns:m.subtotalColumns||[],pivotSchema:m.pivotSchema||[],groupByColumns:m.groupByColumns}},[a.type,m==null?void 0:m.records,m==null?void 0:m.columnSubtotalMeta,m==null?void 0:m.subtotalColumns,m==null?void 0:m.pivotSchema,m==null?void 0:m.groupByColumns]),E=s.usePivotTableConfig(a,y),D=(N,F)=>{var B,I;const T={...a,paginationConfig:{page:N+1,pageSize:F}};p(T),j(T),a.sql&&((I=(B=a.preferences)==null?void 0:B.tablePrefs)!=null&&I.enableDevModePagination)&&i(!0)},C=A.useMemo(()=>!a.id||!(m!=null&&m.records)?null:s.createChartConfig({card:a,data:m==null?void 0:m.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:f}),[a.id,m==null?void 0:m.records,a.type,a.queryConfig,a.customCfg,a.preferences,f]);function S(N){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(ir,{card:N})})}function v(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!x)return g?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||x)&&a.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return S(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&C)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:h||x?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:C})});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:D,isLoading:h||x})});if(a.type==="pivotTable"&&E)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:a,data:E.data,options:E.options,onAggregationChange:N=>{const F=s.handleAggregationChange(N,a.config),T={...a,config:F};p(T),j(T)},onAggregationLabelChange:N=>{const F=s.handleAggregationLabelChange(N,a.config),T={...a,config:F};p(T),j(T)}})});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:D,onAggregationChange:N=>{const F=s.handleAggregationChange(N,a.config),T={...a,config:F};p(T),j(T)},isLoading:h||x})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-5",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:N=>p({...a,title:N}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(or,{})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:N=>p({...a,description:N}),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:N=>d({...u,title:N}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:u})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:v()})]})}const Ns=({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}),cr=()=>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."})]})]}),dr=({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(Ns,{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(Ns,{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(Ns,{language:"javascript",value:t,onChange:l})})]}),ur=({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 mr(){const[t,n]=A.useState(!1),[a,r]=A.useState(""),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(""),m=s.useEditorStore(C=>C.card),h=s.useEditorStore(C=>C.card.customCfg),x=h?JSON.stringify(h,null,2):"",{data:g}=s.useDashboardCardQuery(m),{data:b}=s.useTopoJson(m),{setCardCustomCfg:p,setCustomVisualCode:j}=s.useEditorActions(),f=C=>{var S,v;return JSON.stringify({...C,data:{...C.data,datasets:(v=(S=C.data)==null?void 0:S.datasets)==null?void 0:v.map(k=>({...k,data:[]}))}},null,2)},y=()=>{var S,v;if(!((S=g==null?void 0:g.records)!=null&&S.length))return;const C=s.createChartConfig({card:m,data:g.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:b});if(C){r(f(C)),i(((v=m.preferences)==null?void 0:v.customVisualCode)||"");const k=s.merge(C,h);o(f(k))}},E=()=>{try{if(c&&j(c),l){const C=JSON.parse(l),S=s.getObjectDiff(JSON.parse(a),C);p(S),u("")}}catch{u("Invalid JSON configuration")}},D=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:y,className:D?"":"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(cr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Lt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(dr,{customCode:c,cardCustomCfgString:x,mergedConfig:l,onConfigChange:C=>o(C??""),onCodeChange:C=>i(C??"")})]}),e.jsx(ur,{error:d,hasCardCustomConfig:!!h,onReset:()=>{o(a),p(null)},onApply:E,onClose:()=>n(!1)})]})]})}function ps(t){const[n,a]=A.useState(null);return n}function Rt(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{data:a,isLoading:r,isFetching:l,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(n.apiServiceUrl,t==null?void 0:t.accessToken)});return{data:a,isLoading:r,isFetching:l,isError:o}}function Ot(){const{data:t,isLoading:n,isError:a}=Rt(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let o=n,c=a;return r.forEach((i,d)=>{var u;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const m=t.plugins[d],h=i.data.visuals.map(x=>({name:x.name,pluginName:m.label,componentType:x.componentType,pluginType:m.type,icon:x.icon,chartType:x.chartType,url:m.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function hr({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=Ot(),d=A.useCallback((u,m)=>{n(null),a({}),r(u),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[n,a,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((u,m)=>e.jsx(xr,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const xr=({text:t,icon:n,onClick:a})=>{const r=ps(),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 Ft({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(m,h){o(null),r({}),a(m),["custom","text","map"].includes(m)&&(l(!0),i(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(s.Table2,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnIncreasing,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(s.ChartLine,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnStacked,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(s.MdStackedLineChart,{className:s.cn("size-5",n),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(s.ChartScatter,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(s.TbChartBubble,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(s.ChartPie,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(s.Donut,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(s.TbChartFunnel,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(s.Radar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(s.PiChartPolar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(s.Tornado,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(s.ChartNoAxesGantt,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(s.TiSortNumerically,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(s.Map,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Ze,{className:s.cn("size-5",n)})})]})}function pr({chartType:t,className:n,customIcon:a,componentName:r}){const l=ps();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(Se,{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 o,c;const[n,a]=A.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(pr,{className:"size-4",chartType:l,customIcon:(o=r.customCardPreferences)==null?void 0:o.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"z-[51] w-72 p-1",children:[e.jsx(Ft,{onChartTypeChange:()=>a(!1)}),e.jsx(hr,{onChartTypeChange:()=>a(!1)})]})]})}function fr({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,o]=A.useState(!1),c=A.useRef(null),i=A.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(x){(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d())}function m(){const x=window.getSelection();if(x&&x.toString().trim()!==""){const g=x.toString();navigator.clipboard.writeText(g),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function gr(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx($s,{className:"size-4"}):e.jsx(Ys,{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($s,{className:"size-4"}):e.jsx(Ys,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function jr({className:t}){var x,g,b,p,j,f,y,E;const n=s.useEditorStore(D=>D.card),{setCardPreferences:a,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[o,c]=A.useState(!1),i=((g=(x=n.preferences)==null?void 0:x.displayOptions)==null?void 0:g.showFilterInfo)??!0,d=((p=(b=n.preferences)==null?void 0:b.displayOptions)==null?void 0:p.showCardToolbar)??!0,u=((f=(j=n.preferences)==null?void 0:j.displayOptions)==null?void 0:f.showChrome)??!0,m=((E=(y=n.preferences)==null?void 0:y.displayOptions)==null?void 0:E.allowScroll)??!0,h=(D,C)=>{var k;const S={...n.preferences,displayOptions:{...(k=n.preferences)==null?void 0:k.displayOptions,[D]:C}};a(S);const v={...n,preferences:S};l(v),r(v)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:o,onOpenChange:c,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(ot,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:D=>{h("showFilterInfo",D)},onSelect:D=>D.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:D=>{h("showCardToolbar",D)},onSelect:D=>D.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:D=>{h("showChrome",D)},onSelect:D=>D.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:D=>{h("allowScroll",D)},onSelect:D=>D.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 Pt(){const t=s.useEditorStore(o=>o.card);s.useEditorStore(o=>o.isShowingVisual);const n=s.useEditorStore(o=>{var c,i;return(i=(c=o.card)==null?void 0:c.preferences)==null?void 0:i.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function l(){const o=["xy","none","x","y"],i=(o.indexOf(a)+1)%o.length;r(o[i])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(gr,{})}),!["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(ms,{className:"size-4"}),a==="x"&&e.jsx(ja,{className:"size-4"}),a==="y"&&e.jsx(_a,{className:"size-4"}),a==="none"&&e.jsx($a,{className:"size-4"})]}),e.jsx(jr,{})]})}function br(){const t=s.useEditorStore(b=>b.frame),n=s.useEditorStore(b=>b.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(b,p)=>{b.dataTransfer.setData("tabIndex",p.toString())},i=b=>{b.preventDefault()},d=(b,p)=>{const j=b.dataTransfer.getData("tabIndex");if(j===p.toString())return;const f=Array.from(t.cards),[y]=f.splice(parseInt(j),1);f.splice(p,0,y),a({...t,cards:f})};function u(b){const p=t.cards.filter(y=>y.id!==b),j=p[0],f={...t,cards:p,activeCardId:j.id};a(f),r(j.id),l(j)}function m(b,p){const j={...t,cards:[...t.cards,p],activeCardId:b.id};a(j),r(p.id)}function h(){const b={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};m(n,b)}function x(b){const p={dataSource:b.dataSource,connectionId:b.connectionId,lastSelectedDatabase:b.lastSelectedDatabase,lastSelectedSchema:b.lastSelectedSchema,lastSelectedTable:b.lastSelectedTable,lastSelectedDatamodelId:b.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(b,p)}function g(b,p){return b.cards.length===1&&(p.displayTab===!0||p.displayTab===void 0)||b.activeCardId!==p.id&&(p.displayTab===!0||p.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const j=p.displayTab===void 0?!1:!p.displayTab;l({...p,displayTab:j}),o({...p,displayTab:j})},children:p.displayTab===!0||p.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(ya,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((b,p)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:j=>c(j,p),onDragOver:i,onDrop:j=>d(j,p),className:"",value:b.id,children:[g(t,b),e.jsx(s.Editable,{enabled:t.activeCardId===b.id,text:b.tabTitle||b.title,onSave:j=>{l({...n,tabTitle:j}),o({...n,tabTitle:j})},children:b.tabTitle||b.title},b.id),t.activeCardId===b.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(b.id)})]},b.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>x(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(s.CopyPlus,{className:"h-4 w-4"})})]})})}function zt(){const t=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.isSqlRunning),r=s.useEditorStore(p=>p.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h}=s.useDashboardCardQuery(n);function x(p){const j=t.cards.find(f=>f.id===p);if(j!=null&&j.sql){r||i(!0),o(p);return}if(j!=null&&j.queryConfig){r&&i(!1),g(p),o(p);return}r||g(p),o(p)}function g(p){const j={...t,cards:t.cards.map(y=>y.id===n.id?n:y),activeCardId:p};l(j);const f=j.cards.find(y=>y.id===p);f.sql&&d(!0),c(f)}function b(){return n.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:u==null?void 0:u.records,isPending:m||h})})}):n.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Lt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:x,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(p=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:p.id,children:b()},p.id)),e.jsx(br,{})]})}function as({children:t}){var D,C;s.useEditorStore(S=>S.frame);const n=s.useEditorStore(S=>S.card),a=s.useEditorStore(S=>S.isDevMode),r=s.useEditorStore(S=>S.isShowingVisual),l=s.useDashboardStore(S=>S.isVisualEditing),o=s.useEditorStore(S=>S.pythonStdOut);s.useEditorStore(S=>S.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:x,isLoading:g,isFetching:b,errorMessage:p,refetch:j}=s.useDashboardCardQuery(n);function f(){const S=JSON.stringify(x==null?void 0:x.records,null,2),v=new Blob([S],{type:"application/json"}),k=URL.createObjectURL(v),N=document.createElement("a");N.href=k,N.download=`${n.title}.json`,N.click()}function y(){const v=[Object.keys(x==null?void 0:x.records.reduce((T,B)=>({...T,...B}),{})).join(","),...((x==null?void 0:x.records)||[]).map(T=>Object.values(T).join(","))].join(`
328
- `),k=new Blob([v],{type:"text/csv"}),N=URL.createObjectURL(k),F=document.createElement("a");F.href=N,F.download=`${n.title}.csv`,F.click()}function E(){const S=`Can you get the documentation for ${n.type} chart?`;u(S)}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:E,children:e.jsx(ha,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(mr,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:y,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:f,children:e.jsx(Ca,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(x==null?void 0:x.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(Pt,{})]}),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:((C=(D=n.preferences)==null?void 0:D.tablePrefs)==null?void 0:C.enableDevModePagination)??!1,onCheckedChange:S=>{var v;h({...n.preferences,tablePrefs:{...(v=n.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:S}}),j()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(yr,{})]}),r?e.jsx(zt,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:o&&e.jsx(vr,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":o}),children:[(x==null?void 0:x.records)&&(x==null?void 0:x.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(x==null?void 0:x.records)||[]}),p&&e.jsx(fr,{error:p})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function vr(){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 yr(){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 Te({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function Nr(){var p,j;const t=s.useEditorStore(f=>f.card.customCardPreferences),{data:n}=Rt(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(f=>f.card),l=s.useEditorStore(f=>f.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(p=d==null?void 0:d.visuals)==null?void 0:p.find(f=>f.name===(t==null?void 0:t.componentName));function m(f,y){if(!t)return;const D={...(t==null?void 0:t.dataInputCardIds)||{},[f]:{cardId:y,hookRef:null}};c({...t,dataInputCardIds:D})}function h(f){var E,D;const y=(E=l==null?void 0:l.cards)==null?void 0:E.filter(C=>{var S;return((S=C==null?void 0:C.customCardPreferences)==null?void 0:S.visualType)!=="multiple"}).map(C=>({value:C.id,label:C.tabTitle||C.title}));return e.jsx("div",{className:"space-y-2",children:(D=f==null?void 0:f.dataInputs)==null?void 0:D.map((C,S)=>{var v,k;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:C}),e.jsx(Te,{className:"col-span-6 h-8 w-full justify-between",label:"",options:y||[],value:((k=(v=t==null?void 0:t.dataInputCardIds)==null?void 0:v[S])==null?void 0:k.cardId)||"",onValueChange:N=>m(S,N)})]},S+Math.random())})})}function x(f,y,E=[],D=""){var C,S;return t?f==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((C=t==null?void 0:t.settings)==null?void 0:C[y])||D,onChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[y]:v.target.value}})}},y):f==="select"?e.jsx(Te,{className:"h-8 w-full",label:"",options:E,value:((S=t==null?void 0:t.settings)==null?void 0:S[y])||D,onValueChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[y]:v}})}}):null:null}function g(f){const y=Object.entries((f==null?void 0:f.settings)||{});return e.jsx("div",{className:"space-y-3",children:y.map(([E,D])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:D.title}),x(D.ui,E,D.options,D.defaultValue)]},E))})}function b(f){t&&c({...t,visualType:f,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Te,{icon:e.jsx(ma,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:f=>c({...t||{url:"",componentName:""},url:f})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:b,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(Te,{icon:e.jsx(ba,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(f=>f.type===o).map(f=>({value:f.name,label:f.name})))||[],value:t.componentName,onValueChange:f=>{console.log("changing value",f),c({...t,componentName:f})}})})]})})]}),((j=r==null?void 0:r.customCardPreferences)==null?void 0:j.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(u)})})]})]})]})}function _e(){const[t,n]=A.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),o=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),A.useEffect(()=>{o&&n(new Array(o.length).fill(!1))},[o]);function c(u,m){var h,x;m?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):l({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...a,onClickFilter:(x=a==null?void 0:a.onClickFilter)==null?void 0:x.filter(g=>g.columnIndex!==u)}),n(g=>{const b=[...g];return b[u]=!1,b}))}function i(u,m){var x;const h=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.map(g=>g.columnIndex===u?{...g,expression:m.target.value}:g);l({...a,onClickFilter:h})}function d(u){var m,h,x,g;if(t!=null&&t[u]||(h=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(b=>b.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(b=>b.columnIndex===u))==null?void 0:g.expression,onChange:b=>i(u,b),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:o==null?void 0:o.map((u,m)=>{var h,x;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(g=>g.columnIndex===m)),onCheckedChange:g=>c(m,g)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(g=>g.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{n(g=>{const b=[...g];return b[m]=!g[m],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function Cr({idx:t}){var i;const n=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),a=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=n==null?void 0:n.chartOptions)==null?void 0:i.indexAxis,o=a==null?void 0:a.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:m}]});else{const h={...o};h.datalabels=m;const x=a==null?void 0:a.map(g=>g.idx===u?h:g);r({...n,datasetOptions:x})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(it,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ia,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ma,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Aa,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function Sr(){const t=s.useEditorStore(o=>o.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function fs({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 Vt(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=Sr();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:o.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:_t(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(Ut,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function _t(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Ut({col:t,idx:n,className:a,iconClassName:r,children:l}){const o=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,x;return(x=(h=m.card)==null?void 0:h.preferences)==null?void 0:x.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===n),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...o,datasetOptions:[...c||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const x=c==null?void 0:c.map(g=>g.idx===n?h:g);d({...o,datasetOptions:x})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(fs,{className:"max-w-[100px]",title:t,children:_t(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(Cr,{idx:n})]})]})}function Ls(){const t=s.useEditorStore(g=>g.selectedConnectionId),n=s.useEditorStore(g=>g.selectedDatamodelId),a=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),l=s.useEditorStore(g=>g.selectedTableName),o=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:h}=s.useEditorAside();function x(g,b="dashboard",p){var k;const j=s.fmt(g.column_name),f=s.fmt(a||""),y=s.fmt(r||""),E=s.fmt(m);let D=s.getQualifiedTableName({schemaName:y,tableName:E,connectionType:h,databaseName:f}),C=`${D}.${j}`;const S=(k=u==null?void 0:u.find(N=>N.id===n))==null?void 0:k.name;n&&n!=="none"&&(C=`${s.DATAMODEL_NAMESPCACE}.${S}.${j}`,D=`${s.DATAMODEL_NAMESPCACE}.${S}`),p!=null&&p.qualifiedFieldName&&(C=p.qualifiedFieldName),p!=null&&p.entityName&&(D=p.entityName);const v=o==null?void 0:o.find(N=>N.column===C&&N.table===E&&(N.database===f||N.database===a));if(v)d(v.id),i(v.id);else{const N=s.v4();return m==="api"&&t?(c({location:b,id:N,column:C,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,D,j)}),N):(c({id:N,location:b,column:C,title:g.column_name,dataType:g.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,D,j)}),N)}}return{assignFilter:x}}function Ke(){const t=s.useDashboardStore(i=>i.dashboard.filters),n=s.useEditorStore(i=>i.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=Ls();function o(i){const d=l(i,"frame");a({...n,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(wr,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function wr({columns:t,onSelect:n}){var c;const[a,r]=Re.useState(!1),[l,o]=Re.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const u=d===l?"":d;o(u),r(!1),u&&n(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function Dr({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(Vt,{})})]}),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(_e,{}),e.jsx(Ke,{})]})]})]})})}function Tr({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(_e,{}),e.jsx(Ke,{})]})]})]})})}function Gt(){const t=s.useEditorStore(i=>i.card.type),n=s.useEditorStore(i=>i.isDevMode),a=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(m=a==null?void 0:a.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function o(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?o():c()})}const kr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Er={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Ir(){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:Ar(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Gt,{}),e.jsx(_e,{}),e.jsx(Ke,{})]})]})}function Ar(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(kr,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(Er,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(c,i,d){const u=[...t];u[c]={...u[c],[i]:d},n(u)}function l(c){const i=[...t];i.splice(c,1),n(i)}function o(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:o,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(i,"start",d.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:d=>r(i,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(i,"color",d.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function Lr(){var m,h,x,g,b;const t=s.useEditorStore(p=>p.card.preferences),n=s.useEditorStore(p=>p.actions.setCardPreferences),a=s.useEditorStore(p=>p.card),r=s.isExplorerCard(a),l=s.useEditorStore(p=>p.actions.setNumberFormat);s.useEditorStore(p=>{var j,f;return(f=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.decimalPlaces});const o=s.useEditorStore(p=>{var j,f;return(f=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.locale}),c=s.useEditorStore(p=>{var j,f;return(f=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.currency});s.useEditorStore(p=>p.actions.setFilterOnClickField);const i=s.useEditorStore(p=>{var j,f;return(f=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.colorRanges})||[],d=s.useEditorStore(p=>p.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(p=>p.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:p=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:p}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:p=>{var j,f,y;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",p,((y=t==null?void 0:t.formatNumber)==null?void 0:y.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(p=>e.jsx(s.SelectItem,{value:p.locale,children:p.locale},p.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:p=>{var j,f,y;console.log("currency",p),l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,p==="none"?"":p,((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((g=(x=t==null?void 0:t.formatNumber)==null?void 0:x.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:p=>{var j,f,y;return l(Number(p),((j=t==null?void 0:t.formatNumber)==null?void 0:j.currency)||"",((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:p=>{var j,f,y;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.locale)||"",p.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(Mr,{colorRanges:i,setColorRanges:d})]})]})}function Rr(){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(Lr,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function Cs({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 Or=[{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"],Br=Fr.map(t=>({label:t,value:t}));function Pr(){var d,u,m,h,x,g,b,p,j,f,y,E,D,C,S,v,k,N;const t=s.useEditorStore(F=>F.card),n=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=A.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(F=>({label:F,value:F}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(Cs,{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(Cs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Te,{className:"h-9",options:i,onValueChange:F=>{console.log("value",F),l({...t.preferences,mapVisualOptions:{topoJsonUrl:F}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:F=>{r(F.target.value)},onBlur:()=>{var F;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(F=t.preferences)==null?void 0:F.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(Te,{className:"h-9",options:c,value:((g=(x=t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:F=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,objectKey:F}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(Te,{className:"h-9",options:Or,value:((p=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:p.projection)||"",label:"Projection",onValueChange:F=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projection:F}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(Te,{className:"h-9",options:Br,value:((f=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:f.colorScale)||"",label:"Select Color Scale",onValueChange:F=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,colorScale:F}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Cs,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((E=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:E.projectionScale)||1,onChange:F=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionScale:Number(F.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(C=(D=t.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:C.projectionOffset)==null?void 0:S[0])||0,onChange:F=>{var T,B,I,w;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[Number(F.target.value),((w=(I=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:w[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((N=(k=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:N[1])||0,onChange:F=>{var T,B,I,w;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[((w=(I=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:w[0])||0,Number(F.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(_e,{})]})}function zr(){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 ns({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(zr,{})})]}),!["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(_e,{}),e.jsx(Ke,{})]})]})]})})}function Vr(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(Te,{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(Vt,{})]})]}),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(_e,{}),e.jsx(Ke,{})]})]})]})})}function _r({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(_e,{}),e.jsx(Ke,{})]})]})}),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 Yt({color:t,onColorChange:n,onClose:a}){const[r,l]=A.useState(0),[o,c]=A.useState(100),[i,d]=A.useState(50),[u,m]=A.useState(t);A.useEffect(()=>{const j=Ks(t);if(j){const f=Qs(j.r,j.g,j.b);l(f.h),c(f.s),d(f.l),m(t)}},[t]);const h=j=>{l(j),g(j,o,i)},x=j=>{const f=j.currentTarget.getBoundingClientRect(),y=Math.max(0,Math.min(1,(j.clientX-f.left)/f.width)),E=Math.max(0,Math.min(1,(j.clientY-f.top)/f.height)),D=y*100,C=(1-E)*100;c(D),d(C),g(r,D,C)},g=(j,f,y)=>{const E=Gr(j,f,y),D=Ur(E.r,E.g,E.b);m(D)},b=j=>{if(m(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const f=Ks(j);if(f){const y=Qs(f.r,f.g,f.b);l(y.h),c(y.s),d(y.l)}}},p=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(n(u),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:x,onMouseMove:j=>{j.buttons===1&&x(j)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>h(Number(j.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:u,onChange:j=>b(j.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:p,children:"OK"})]})]})}function Ks(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 Ur(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function Qs(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let o=0,c=0;const i=(r+l)/2;if(r!==l){const d=r-l;switch(c=i>.5?d/(2-r-l):d/(r+l),r){case t:o=((n-a)/d+(n<a?6:0))/6;break;case n:o=((a-t)/d+2)/6;break;case a:o=((t-n)/d+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function Gr(t,n,a){t/=360,n/=100,a/=100;let r,l,o;if(n===0)r=l=o=a;else{const c=(u,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(m-u)*6*h:h<.5?m:h<.6666666666666666?u+(m-u)*(.6666666666666666-h)*6:u),i=a<.5?a*(1+n):a+n-a*n,d=2*a-i;r=c(d,i,t+1/3),l=c(d,i,t),o=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const Yr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function $t(){var E,D,C,S,v,k,N,F,T,B;const t=s.useEditorStore(I=>I.card),n=s.useEditorStore(I=>{var w;return(w=I.card)==null?void 0:w.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=A.useState({}),[i,d]=A.useState(null),[u,m]=A.useState(null),h=A.useMemo(()=>{var L,O,R,z,G,Q,_;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",w=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",M=((L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns)&&t.config.pivotByColumns.length>0;if((I||w)&&M){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const W=new Set;return l.pivotSchema.forEach($=>{$.alias&&W.add($.alias)}),Array.from(W)}if(l.records.length>0){const W=l.records[0],$=Object.keys(W),X=new Set;(O=t==null?void 0:t.config)!=null&&O.groupByColumns&&t.config.groupByColumns.forEach(U=>{X.add(U.label||U.name),X.add(U.alias||U.name)});const Y=new Set;return(R=t==null?void 0:t.config)!=null&&R.metricColumns&&t.config.metricColumns.forEach(U=>{const ee=U.alias||U.name;Y.add(ee),Y.add(`${ee}_count`),Y.add(`${ee}_sum`),Y.add(`${ee}_avg`),Y.add(`${ee}_min`),Y.add(`${ee}_max`);const ne=U.entityName||U.qualifiedEntityName;ne&&(Y.add(`${ne}_${ee}`),Y.add(`${ne}_${ee}_count`))}),$.filter(U=>!X.has(U)&&!Y.has(U))}}if((w||I)&&!M&&((G=(z=t==null?void 0:t.config)==null?void 0:z.metricColumns)!=null&&G.length))return t.config.metricColumns.map(W=>W.alias||W.label||W.name);if((_=(Q=t==null?void 0:t.config)==null?void 0:Q.groupByColumns)!=null&&_.length){const W=t.config.groupByColumns[0],$=W.label||W.name,X=new Set;return l.records.forEach(Y=>{const K=Y[$];K!=null&&X.add(String(K))}),Array.from(X)}return[]},[l,(E=t==null?void 0:t.config)==null?void 0:E.groupByColumns,(D=t==null?void 0:t.config)==null?void 0:D.pivotByColumns,(C=t==null?void 0:t.config)==null?void 0:C.metricColumns,t==null?void 0:t.type]),x=A.useMemo(()=>s.getDefaultChartColors(),[]);A.useEffect(()=>{const I={};h.forEach((w,M)=>{I[w]=s.getColorForValue(w,M,n==null?void 0:n.colorConfig)}),c(I)},[h,n==null?void 0:n.colorConfig,x]);const g=(I,w)=>{const M={...o,[I]:w};c(M);const L={...n||{},colorConfig:{segments:M}};a(L);const O={...t,preferences:L};r(O)},b=(I,w)=>{var G;const M=x[w%x.length],{[I]:L,...O}=((G=n==null?void 0:n.colorConfig)==null?void 0:G.segments)||{},R={...n||{},colorConfig:{segments:O}};a(R);const z={...t,preferences:R};r(z),c(Q=>({...Q,[I]:M}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((v=(S=t==null?void 0:t.config)==null?void 0:S.groupByColumns)==null?void 0:v.length)||((N=(k=t==null?void 0:t.config)==null?void 0:k.pivotByColumns)==null?void 0:N.length):(T=(F=t==null?void 0:t.config)==null?void 0:F.groupByColumns)==null?void 0:T.length)||["table","kpi","text","custom"].includes(t.type))return null;const f=()=>{const I={...n||{},colorConfig:{segments:{}}};a(I);const w={...t,preferences:I};r(w);const M={};h.forEach((L,O)=>{M[L]=s.getColorForValue(L,O,void 0)}),c(M)},y=Object.keys(((B=n==null?void 0:n.colorConfig)==null?void 0:B.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:y&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:f,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((I,w)=>{const M=s.isDefaultColor(o[I],w),L=!M;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===I,onOpenChange:O=>d(O?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:o[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:x.slice(0,10).map((O,R)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[I]===O?"border-gray-900":"border-transparent"),style:{backgroundColor:O},onClick:()=>{g(I,O),d(null)},children:[R===w%x.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:O})]},`default-${R}`))})]}),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:Yr.map((O,R)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[I]===O?"border-2 border-gray-900":O==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:O},onClick:()=>{g(I,O),d(null)},children:e.jsx("span",{className:"sr-only",children:O})},`preset-${R}`))})]}),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:o[I]}),d(null)},children:"Custom color"}),!M&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(I,w),d(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:I}),L&&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(Yt,{color:u.color,onColorChange:I=>{g(u.value,I),m(null)},onClose:()=>m(null)})})]})]})})]})}function Ee({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[o,c]=A.useState(t??""),[i,d]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const u=()=>{n(o),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?u():h.key==="Escape"&&m()},"aria-label":a||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const $r=["auto","number","currency","percent","scientific","date"],qr=[{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"}],Hr=[{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"}],Wr=t=>t.charAt(0).toUpperCase()+t.slice(1);function Rs({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,d)=>{n({...t,[i]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:$r.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":Wr(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:qr.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Hr.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function Js({axis:t,label:n,type:a,config:r,onChange:l}){var h,x,g,b,p,j,f,y,E,D,C,S;const o=(v,k)=>{l({...r,[v]:k})},c=(v,k)=>{var N,F;l({...r,name:{enabled:v==="enabled"?k:((N=r==null?void 0:r.name)==null?void 0:N.enabled)??!1,text:v==="text"?k:(F=r==null?void 0:r.name)==null?void 0:F.text}})},i=(v,k)=>{var N,F;l({...r,labels:{enabled:v==="enabled"?k:((N=r==null?void 0:r.labels)==null?void 0:N.enabled)??!0,rotation:v==="rotation"?k:(F=r==null?void 0:r.labels)==null?void 0:F.rotation}})},d=(v,k)=>{l({...r,scale:{...r==null?void 0:r.scale,[v]:k===""?"auto":Number(k)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:v=>o("enabled",v),onClick:v=>v.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:v=>c("enabled",v)})]}),((x=r==null?void 0:r.name)==null?void 0:x.enabled)&&e.jsx(Ee,{placeholder:`${n} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:v=>c("text",v),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:v=>o("position",v),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":s.titleCase(v)},v))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((b=r==null?void 0:r.labels)==null?void 0:b.enabled)!==!1,onCheckedChange:v=>i("enabled",v)})]}),((p=r==null?void 0:r.labels)==null?void 0:p.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((j=r==null?void 0:r.labels)==null?void 0:j.rotation)||"auto"),onValueChange:v=>i("rotation",v==="auto"?"auto":Number(v)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":`${v}°`},v))})]})]})]}),a==="value"&&e.jsx(Rs,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:v=>l({...r,formatOptions:v}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ee,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.min)==="auto"||((y=r==null?void 0:r.scale)==null?void 0:y.min)===void 0?"":String(r.scale.min),onSave:v=>d("min",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ee,{type:"number",placeholder:"auto",value:((E=r==null?void 0:r.scale)==null?void 0:E.max)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.max)===void 0?"":String(r.scale.max),onSave:v=>d("max",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ee,{type:"number",placeholder:"auto",value:((C=r==null?void 0:r.scale)==null?void 0:C.stepSize)==="auto"||((S=r==null?void 0:r.scale)==null?void 0:S.stepSize)===void 0?"":String(r.scale.stepSize),onSave:v=>d("stepSize",v),className:""})})]})]})]})]})]})}function qt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const u={...n||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};a(u);const m={...t,preferences:u};r(m)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{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(Js,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(Js,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function Ht(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var m,h,x,g;return(g=(x=(h=(m=u.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:x.plugins)==null?void 0:g.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(u,m)=>{const h={...n,[u]:m};a(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ea,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??o,onCheckedChange:u=>c("display",u)})]}),((n==null?void 0:n.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||r,onValueChange:u=>c("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||l,onValueChange:u=>c("align",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]})]})]})})]})}function Wt(){var k,N,F,T,B,I,w,M,L;const t=s.useEditorStore(O=>O.card),n=s.useEditorStore(O=>{var R,z;return(z=(R=O.card)==null?void 0:R.preferences)==null?void 0:z.dataLabelsConfig}),a=s.useEditorStore(O=>{var R;return(R=O.card)==null?void 0:R.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((k=a==null?void 0:a.chartOptions)==null?void 0:k.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!i,u=(F=(N=a==null?void 0:a.chartOptions)==null?void 0:N.plugins)==null?void 0:F.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),h=(n==null?void 0:n.enabled)!==void 0?n.enabled:m,x=(O,R)=>{const z={...n,[O]:R},G={...t.preferences||{},dataLabelsConfig:z};r(G);const Q={...t,preferences:G};l(Q)},g=(O,R)=>{const z={...n,font:{...n==null?void 0:n.font,[O]:R}},G={...t.preferences||{},dataLabelsConfig:z};r(G);const Q={...t,preferences:G};l(Q)},b=(O,R)=>{const z={...n,formatOptions:{...n==null?void 0:n.formatOptions,[O]:R}},G={...t.preferences||{},dataLabelsConfig:z};r(G);const Q={...t,preferences:G};l(Q)},j=(()=>{const O=t.type;return O==="stackedBar"||O==="stackedLine"||O==="pie"||O==="doughnut"?"center":o?"right":"top"})();let f=[];c||i?f=["center"]:f=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(R=>R!==j),"custom"];const y=()=>s.titleCase(j),E=["center","start","end"],D=["center","start","end","top","bottom"],C=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],S=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],v=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:O=>x("enabled",O)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:O=>x("position",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"?y():O==="custom"?"Custom (Advanced)":s.titleCase(O)},O))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:O=>x("showTotal",O)})]}),(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:O=>x("anchor",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:E.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]}),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:O=>x("align",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:D.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(d?"auto":"none"),onValueChange:O=>x("format",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:C.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"&&d?"Auto (Use Axis)":O==="none"?"None (Raw Value)":s.titleCase(O)},O))})]})]}),(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(Ee,{type:"number",placeholder:"0",value:String(((T=n==null?void 0:n.formatOptions)==null?void 0:T.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:O=>b("decimalPlaces",Number(O)),className:""})})]}),n.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((B=n==null?void 0:n.formatOptions)==null?void 0:B.currency)||"USD",onValueChange:O=>b("currency",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:S.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.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:O=>b("useSuffix",O)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((w=n==null?void 0:n.formatOptions)==null?void 0:w.locale)||"en-US",onValueChange:O=>b("locale",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.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(Ee,{type:"number",placeholder:"12",value:String(((M=n==null?void 0:n.font)==null?void 0:M.size)||12),onSave:O=>g("size",Number(O)),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:((L=n==null?void 0:n.font)==null?void 0:L.weight)||"normal",onValueChange:O=>g("weight",O),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:O=>{O==="auto"&&x("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ee,{type:"number",placeholder:"0",value:String((n==null?void 0:n.rotation)||0),onSave:O=>x("rotation",Number(O)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Kr(){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($t,{}),e.jsx(qt,{}),e.jsx(Ht,{}),e.jsx(Wt,{})]})]})}const Qr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT 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."]})]}),Jr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT 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."]})]}),Xr=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 Zr(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=o=>r.includes(a)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(Kr,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(Vr,{}));case"tornado":case"pyramid":return l(e.jsx(ns,{docContent:Qr,cardType:a}));case"kpi":return e.jsx(Rr,{});case"line":case"bar":return l(e.jsx(Dr,{cardType:a}));case"range":return l(e.jsx(ns,{docContent:Jr,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(ns,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(Tr,{cardType:a}));case"table":return e.jsx(_r,{cardType:a});case"text":return e.jsx(ns,{docContent:Xr,cardType:a,suffix:"Visual"});case"map":return e.jsx(Pr,{});case"custom":return e.jsx(Nr,{});default:return l(e.jsx(Ir,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Kt({label:t,column:n,functions:a,onFunctionChange:r}){let l=a[0];"aggregate"in n?l=a.find(c=>c.value===n.aggregate)||a[0]:"granularity"in n&&(l=a.find(c=>c.value===n.granularity)||a[0]);function o(c){r(c)}return e.jsx(Te,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:a,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const el=[{label:"Sum",value:"SUM",logo:e.jsx(lt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Ie,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(Sa,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(ca,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function sl({column:t}){const{updateMetricColumnOld:n}=s.useEditorActions();let a=el;s.isTextDataType(t.type)&&(a=a.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(a=a.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:es(t.name,l)};n(t.id,o)}return e.jsx(Kt,{column:t,functions:a,onFunctionChange:l=>r(l),label:"Aggregation"})}const tl=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function al({column:t}){const{updateGroupByColumnOld:n}=s.useEditorActions();function a(r){const l={...t,granularity:r,label:We(t.name,r)};n(t.id,l)}return e.jsx(Kt,{column:t,functions:tl,onFunctionChange:r=>a(r),label:"Granularity"})}function nl({col:t,onChange:n,droppableId:a}){const{columns:r}=s.useDataColumns(),l=A.useMemo(()=>{let i=[];(a===Oe||a===Fe||a===Be)&&(i=r);const d=i==null?void 0:i.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,a,t.name]),o=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(u=>{var m;return u.column_name===((m=i[0])==null?void 0:m.id)});d&&n(d)}return l!=null&&l.length?e.jsx(s.ComboBox2,{multiple:!1,options:l,selectedOptions:o,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function Qt({column:t}){const n=s.useEditorStore(d=>d.card.type),a=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(a==null?void 0:a.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Ut,{idx:o,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Gt,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&i()]})}function rl({column:t,type:n,onRemoveColumn:a,droppableId:r}){const[l,o]=A.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:m,setNodeRef:h,transform:x,transition:g,isDragging:b}=s.useSortable({id:t.id,data:{type:n}}),p=x?{opacity:b?.5:void 0,transform:s.CSS.Translate.toString(x),transition:g}:void 0,j=s.isTextDataType(t.type);function f(S){const v=s.isNumberDataType(S.data_type),k=s.isTextDataType(S.data_type),N=s.isDateDataType(S.data_type),F=v?"number":k?"string":N?"date":"string";if(r===Oe){if(k){const T={id:t.id,name:S.column_name,type:F,role:"groupby"};c(t.id,T)}if(N){const T={id:t.id,name:S.column_name,type:F,role:"groupby",label:We(S.column_name,"month"),granularity:"month"};c(t.id,T)}}if(r===Be){if(k){const T={id:t.id,name:S.column_name,type:F,role:"groupby"};d(t.id,T)}if(N){const T={id:t.id,name:S.column_name,type:F,label:We(S.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,T)}}if(r===Fe){const T={id:t.id,name:S.column_name,type:F,role:"metric",label:es(S.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};i(t.id,T)}}function y(){if(r===Fe)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(Qt,{column:t})})}function E(){const S=s.isDateDataType(t.type);if(r===Fe)return e.jsx(sl,{column:t});if((r===Oe||r===Be)&&S)return e.jsx(al,{column:t})}function D(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Oe||r===Be)&&j}),children:e.jsx(nl,{col:t,onChange:f,droppableId:r})})}function C(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>o(!l),children:l?e.jsx(Ya,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(nt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...u,ref:h,style:p,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[C(),E(),D()]}),l&&y()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>a(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function Ss({id:t,label:n,columns:a,previewColumns:r,sortableType:l,onRemoveColumn:o}){var p,j;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),u=s.useDndStore(f=>f.activeId),m=s.useEditorStore(f=>{var y;return(y=f.card)==null?void 0:y.type}),h=i||((j=(p=d==null?void 0:d.data)==null?void 0:p.current)==null?void 0:j.type)===l,x=u?r:a,g=l===ds?"Rows":l===us?"Pivot Columns":"Columns";function b(){if(!x||x.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(f=>f.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:n}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),b(),e.jsx("div",{className:"space-y-2",children:x==null?void 0:x.map(f=>f.id===Tt.id?e.jsx(ll,{},f.id):e.jsx(rl,{droppableId:t,type:l,column:f,onRemoveColumn:o},f.id))})]})})}function ll(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function Jt({children:t,id:n,type:a}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:d}=s.useSortable({id:n,data:{type:a}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...l,...r,ref:o,style:u,children:t})}function ol(){const t=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.orderBy})||[],n=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.groupByColumns})||[],a=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...n,...a];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(ua,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(ia,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(da,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(oa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(f=>!t.some(y=>y.columnId===f.id)).map(f=>({id:f.id,value:f.label||f.name}));function x(f,y){const E=g(f);return E?E.role==="metric"?y==="asc"?u:m:y==="asc"?i:d:null}function g(f){return c.find(y=>y.id===f)}function b(f){const y=t.find(E=>E.columnId===f);if(y){const E={...y,direction:y.direction==="asc"?"desc":"asc"};o(E)}}const p=f=>{r({columnId:f.id,direction:"asc"})};function j(f){const y=t.find(E=>E.columnId===f);y&&l(y)}return e.jsx(s.SortableContext,{items:t.map(f=>Je(f.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:f=>p(f[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(f=>{var y,E;return e.jsx(Jt,{id:Je(f.columnId),type:Ms,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(nt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(fs,{className:"w-[175px] text-sm",children:((y=g(f.columnId))==null?void 0:y.label)||((E=g(f.columnId))==null?void 0:E.name)})]}),e.jsx("button",{title:f.direction==="asc"?"Ascending":"Descending",onClick:()=>b(f.columnId),className:"rounded-sm p-0",children:x(f.columnId,f.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>j(f.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},f.columnId)},Je(f.columnId))})]})})}function il(){const t=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.groupByColumns)||[]}),n=s.useEditorStore(j=>j.card.type),a=s.useDndStore(j=>j.previewGroupByColumns),r=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.metricColumns)||[]}),l=s.useDndStore(j=>j.previewMetricColumns),o=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.pivotColumns)||[]}),c=s.useDndStore(j=>j.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function m(j){i(j)}function h(j){d(j)}function x(j){u(j)}let g="Group By",b="Metrics",p="Stack By";return n==="table"&&(g="Rows",b="Metrics",p="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(Ft,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(Ss,{onRemoveColumn:m,sortableType:ds,id:Oe,label:g,columns:t,previewColumns:a}),e.jsx(Ss,{onRemoveColumn:x,sortableType:us,id:Be,label:p,columns:o,previewColumns:c}),e.jsx(Ss,{onRemoveColumn:h,sortableType:Ts,id:Fe,label:b,columns:r,previewColumns:l}),e.jsx(ol,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Os({children:t,column:n,id:a,sortableType:r,className:l}){const[o,c]=A.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(h=>{var x,g;return(g=(x=h.card.queryConfig)==null?void 0:x.filters)==null?void 0:g.some(b=>b.filterColumnName===n.name)});function m(h){i(h)}return e.jsx(Jt,{id:a,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":o}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:n.name}),u&&e.jsx("button",{onClick:()=>d(n),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>m(n),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!o&&"rounded-b-md",o&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",l),children:t})]})]})})}function cl({column:t,sortableType:n}){const a=s.useDashboardStore(E=>E.themeStyle),r=s.useEditorStore(E=>{var D,C;return(C=(D=E.card)==null?void 0:D.queryConfig)==null?void 0:C.filters}),l=s.useEditorStore(E=>{var D,C;return(C=(D=E.card.queryConfig)==null?void 0:D.filterColumns)==null?void 0:C.find(S=>S.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=A.useMemo(()=>{var E;return(E=r==null?void 0:r.find(D=>D.filterColumnName===t.name))==null?void 0:E.filterValue},[r,t.name]),u=A.useMemo(()=>Array.isArray(d)?d.map(E=>({id:E,value:E})):[],[d]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:x,isLoading:g,isFetching:b,isError:p}=s.useFilterQuery(h),j=A.useMemo(()=>{var D;return h.column?(D=x==null?void 0:x.records)==null?void 0:D.map(C=>{let S=h.column.split(".").slice(-1)[0].replace(/"/g,"");return C[S]===void 0&&(S=S.toLowerCase()),{id:C[S],value:C[S]}}):[]},[x,h.column]);function f(E){const D=E.map(C=>C.id);m(t.name,D)}function y(){return g||b?e.jsx(s.Skeleton,{style:{borderRadius:a==null?void 0:a.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):p?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(dl,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:j,onChange:f,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Os,{className:"w-60",id:t.id,sortableType:n,column:t,children:y()})}function dl({columnName:t}){const{setEditorFilterMode:n}=s.useEditorActions(),a=s.useEditorStore(l=>{var o,c;return(c=(o=l.card.queryConfig)==null?void 0:o.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(a==null?void 0:a.mode)==="exclude"?n(t,"include"):n(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((a==null?void 0:a.mode)==="exclude"?"exclude":"include")})}function ul({open:t,setOpen:n,dateRange:a,setDateRange:r,containerClassName:l,inputClassName:o,title:c,onApply:i,onClear:d}){const u=s.useDashboardStore(m=>m.themeStyle);return e.jsx("div",{className:s.cn("grid gap-2",l),children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{style:{borderRadius:u==null?void 0:u.controlInputRadius},asChild:!0,children:e.jsxs(s.Button,{size:"sm",id:"date",variant:"outline",className:s.cn("h-9 w-full justify-start rounded-sm text-left font-normal",!a&&"text-muted-foreground",o),children:[e.jsx(s.Calendar,{className:"mr-2 h-4 w-4"}),a!=null&&a.from?a.to?e.jsxs(e.Fragment,{children:[s.format(a.from,"LLL dd, y")," -"," ",s.format(a.to,"LLL dd, y")]}):s.format(a.from,"LLL dd, y"):e.jsx("span",{children:"Pick a date"})]})}),e.jsxs(s.PopoverContent,{style:{borderRadius:u==null?void 0:u.controlInputRadius},className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsx(s.Label,{children:c})}),e.jsx(s.Calendar$1,{initialFocus:!0,mode:"range",defaultMonth:a==null?void 0:a.from,selected:a,onSelect:r,numberOfMonths:2}),e.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3",children:[e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:m=>{m.stopPropagation(),i(a),n(!1)},children:"Apply"}),e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:d,children:"Clear"})]})]})]})})}function ml({column:t,sortableType:n}){const[a,r]=A.useState(!1),{selectedConnectionId:l,selectedDatabaseName:o,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:l,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:m,data:h}=s.useFilterQuery(i),x=h==null?void 0:h.records,{dateRange:g,setDateRange:b,initialDateRange:p}=s.useDateRangeFromRecords(x),{updateEditorFilterValue:j}=s.useEditorActions();function f(D){var S,v;const C={gte:(S=D==null?void 0:D.from)==null?void 0:S.toISOString(),lte:(v=D==null?void 0:D.to)==null?void 0:v.toISOString()};j(t.name,C)}function y(){j(t.name,null,!0),b(p)}function E(){return d||u?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):m?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):x?e.jsx(ul,{title:i.title,open:a,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:b,onApply:f,onClear:y}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Os,{className:"w-72",id:t.id,sortableType:n,column:t,children:E()})}function hl({id:t,label:n,columns:a,previewColumns:r,sortableType:l}){var b,p;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(j=>j.activeId),u={},m=c||((p=(b=i==null?void 0:i.data)==null?void 0:b.current)==null?void 0:p.type)===l;function h(){if(!g||g.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function x(j){const f=s.isDateDataType(j.type);return j.id===Tt.id?e.jsx(Os,{id:j.id,sortableType:l,column:j,children:e.jsx(xl,{})},j.id):f?e.jsx(ml,{droppableId:t,sortableType:l,column:j},j.id):e.jsx(cl,{droppableId:t,sortableType:l,column:j},j.id)}const g=d?r:a;return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(j=>j.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",m&&"border border-muted-foreground/20"),ref:o,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:n}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(j=>x(j))})]})})}function xl(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function pl(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),n=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:a}=s.useEditorActions();function r(l){a(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(hl,{onRemoveColumn:r,sortableType:Es,id:ks,label:"Filters",columns:t,previewColumns:n})})}function fl(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.showAIDialog),{setShowAIDialog:a}=s.useEditorActions(),{data:r,errorMessage:l,errorSql:o}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xs,{}),!n&&e.jsxs(s.Button,{onClick:()=>a(!0),variant:"secondary",size:"sm",children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(At,{sql:r==null?void 0:r.sql,error:l,errorSql:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(St,{}),e.jsx(Ct,{variant:"default"})]})]})}function gl(){const t=A.useRef(null),n=A.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);A.useEffect(()=>{var i,d,u,m;r?((i=t.current)==null||i.resize(0),(d=n.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(m=n.current)==null||m.resize(25))},[r]);function o(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(rr,{})}),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(Zr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(as,{})})]}):e.jsx(as,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:a?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:n,defaultSize:25,maxSize:30,children:e.jsx(il,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(fl,{}),e.jsx(pl,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(as,{})})]})})]}):e.jsx(as,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function jl(t){s.useAIInteractionStore(V=>V.currentAIContext);const[n,a]=A.useState(""),[r,l]=A.useState(null),{authToken:o,tokenProps:c}=s.useSemaphorContext(),i=s.useEditorStore(V=>{var Z;return(Z=V==null?void 0:V.card)==null?void 0:Z.sql}),d=s.useEditorStore(V=>V.isDevMode),u=s.useEditorStore(V=>{var Z;return(Z=V==null?void 0:V.card)==null?void 0:Z.python}),{setCardPython:m,setCardSql:h,setRunSql:x,switchCardType:g,setQueryConfig:b}=s.useEditorActions(),p=s.useEditorStore(V=>V.currentAssitantScope)||[],j=s.useEditorStore(V=>V.userInputForAI),f=s.useEditorStore(V=>V.triggerAIRun),y=s.useEditorStore(V=>V.card),E=s.useEditorStore(V=>V.selectedDatabaseName),D=s.useEditorStore(V=>V.selectedTableName),C=s.useEditorStore(V=>V.selectedConnectionId),S=s.useEditorStore(V=>V.selectedSchemaName),v=s.useDashboardStore(V=>V.dashboard.aiScopeTables),{errorMessage:k,refetch:N,data:F}=s.useDashboardCardQuery(y),{setTriggerAIRun:T,setCurrentAssitantScope:B,setCardConfig:I}=s.useEditorActions(),{selectedDatamodelName:w,connectionType:M,selectedDatamodelId:L}=s.useEditorAside(),{messages:O,setMessages:R,regenerate:z,error:G,sendMessage:Q,status:_,addToolResult:W,stop:$,clearError:X}=s.useChat({transport:new s.DefaultChatTransport({api:`${c.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const V=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:V.currentAIContext,reasoningEffort:V.reasoningEffort,showReasoning:V.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:V,body:Z})=>({body:{...Z,messages:s.cleanupIncompleteMessages(V)}})}),onError:V=>{var Z;if(V.name==="AbortError"||(Z=V.message)!=null&&Z.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",V)},onToolCall:Y,onFinish({isAbort:V,isDisconnect:Z,isError:te}){a(""),console.log(V?"[Editor Assistant] Stream aborted by user":Z?"[Editor Assistant] Stream disconnected (network error)":te?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});A.useEffect(()=>{f&&j&&(Q({role:"user",parts:[{type:"text",text:j}]}),T(!1))},[f,j,Q,T]);async function Y({toolCall:V}){var Z,te,re,ie,de,xe,H,P,J,se,oe,le,ue,ce,be,Ue;if(["createChartFromSql","createForecast"].includes(V.toolName)){const Me=((Z=V.input)==null?void 0:Z.sql)??((te=V.args)==null?void 0:te.sql),Ne=((re=V.input)==null?void 0:re.python)??((ie=V.args)==null?void 0:ie.python),me=((de=V.input)==null?void 0:de.chartType)??((xe=V.args)==null?void 0:xe.chartType);g(me),h(Me),m(Ne),x(!0),W({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(V.toolName==="getUserSql"){if(!i){W({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"error",message:"No SQL found"}});return}W({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"success",sql:i,python:u||""}})}else if(V.toolName==="generateQueryConfig"){a("Generating query config...");const Me=((H=V.input)==null?void 0:H.chartType)??((P=V.args)==null?void 0:P.chartType),Ne=((J=V.input)==null?void 0:J.queryConfig)??((se=V.args)==null?void 0:se.queryConfig);((oe=V.input)==null?void 0:oe.cardConfig)??((le=V.args)==null||le.cardConfig),g(Me),I(Ne),h(void 0),m(void 0);const me=await N();if((ue=me==null?void 0:me.data)!=null&&ue.error){W({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"error",queryConfig:Ne,message:(ce=me==null?void 0:me.data)==null?void 0:ce.error.message}});return}if((be=me==null?void 0:me.data)!=null&&be.records){W({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"success",queryConfig:Ne,message:"The data has been visualized"}});return}W({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"success",queryConfig:Ne,message:"The data has been visualized",records:(Ue=me==null?void 0:me.data)==null?void 0:Ue.records}})}else a("Analyzing...")}function K(V){const Z=s.removeFromScopeArray(p,V);U(Z)}function U(V){const Z=s.sanitizeAIScope(V);B(Z),R(te=>[...te,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Z)}`}]}])}function ee(){const V={databaseName:E||"",schemaName:S||"",tableName:D||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(w),connectionId:C||"",connectionType:M||""},Z=s.dedup([...p,V]);U(Z)}function ne(){const V={databaseName:E||"",schemaName:S||"",tableName:D||"",datamodelName:s.resolveDatamodelName(w),connectionId:C||"",connectionType:M||"",datamodelId:L||""};if(!s.isInAiScopeArray([...v||[],...p],V)||p.length===0){const te=s.dedup([...v||[],...p,V]).filter(re=>re.connectionId===V.connectionId);U(te)}}const he=!["ready","error"].includes(_),ge=s.getErrorMessage(G);return{messages:O,setMessages:R,sendMessage:Q,regenerate:z,isLoading:he,handleSetAIScope:ne,handleAddCurrentTableToScope:ee,removeFromCurrentSelections:K,currentAssitantScope:p,setCurrentAssitantScope:B,stop:$,status:_,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:ge,clearError:X}}const bl=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Xs({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=A.useRef(null),[l,o]=A.useState(!1),[c,i]=A.useState(s.isDevEnv),[d,u]=A.useState(!1),[m,h]=A.useState(!1),[x,g]=A.useState(!1),b=t??x,p=s.useCurrentAIContext(),{setCurrentAIContext:j}=s.useAIActions(),{clearQueue:f}=s.useQueueActions(),{clearFileAttachments:y}=s.useFileActions(),E=s.useFileAttachments("editor"),D=s.useDashboardStore(ae=>ae.dashboard.aiContext),C=s.useEditorStore(ae=>ae.card.dataSource),S=s.useEditorStore(ae=>ae.actions.setCardSql),v=s.useEditorStore(ae=>ae.actions.setRunSql),k=s.useEditorStore(ae=>ae.showAIDialog),N=s.useDashboardStore(ae=>ae.handleOpenAssistantProfile),{setShowAIDialog:F,setCardPython:T}=s.useEditorActions(),{setDataSource:B}=s.useEditorActions(),{assistantProfile:I}=s.useAssistantProfile(),{messages:w,setMessages:M,sendMessage:L,isLoading:O,stop:R,status:z,llmUsage:G,errorMessage:Q,clearError:_}=jl(),[W,$]=A.useState(""),X=ae=>{$(ae.target.value)},Y=ae=>{ae.preventDefault();const je=W.trim();if(!je&&E.length===0)return;const Qe=[];je&&Qe.push({type:"text",text:je}),E.forEach(Le=>{Le.data&&Qe.push({type:"file",mediaType:Le.type,filename:Le.name,url:`data:${Le.type};base64,${Le.data}`})}),L({role:"user",parts:Qe}),$(""),y("editor"),re({force:!0})},{visibleMessages:K,hasMoreMessages:U,totalMessageCount:ee,loadMoreMessages:ne,resetMessageWindow:he}=s.useMessageWindow(w,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ge,isAtBottom:V,hasNewMessages:Z,newMessageCount:te,scrollToBottom:re,handleScroll:ie,resetNewMessageCount:de}=s.useAutoScroll(K,{threshold:50,delay:0,dependencies:[z,w.length]});A.useEffect(()=>{var ae;k&&((ae=r.current)==null||ae.focus(),j({selectedEntities:(C==null?void 0:C.selectedEntities)||[]}))},[k,C,j]),s.useAutoSubmitQueue({assistantType:"editor",status:z,isLoading:O,sendMessage:L});const{hasActiveTools:xe}=s.useActiveToolStatus(w),H=A.useCallback(ae=>{n==null||n(ae),t===void 0&&g(ae)},[t,n]);A.useEffect(()=>{if(!b)return;function ae(je){je.key==="Escape"&&H(!1)}return window.addEventListener("keydown",ae),()=>{window.removeEventListener("keydown",ae)}},[b,H]);const P=A.useCallback(ae=>{L({role:"user",parts:[{type:"text",text:ae}]}),re({force:!0})},[L,re]),J=A.useCallback(async()=>{const ae=JSON.stringify(w??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ae),s.ue.success("Conversation copied")}catch(je){console.error("Failed to copy conversation",je),s.ue.error("Unable to copy conversation")}},[w]),se=A.useCallback(()=>{H(!b)},[b,H]);function oe(ae,je){je==="sql"?(S(ae),v(!0)):je==="python"&&(T(ae),v(!0))}function le(){var ae;(ae=D==null?void 0:D.selectedEntities)==null||ae[0],h(!0)}function ue(){p.selectedEntities.length===0&&j({selectedEntities:(D==null?void 0:D.selectedEntities)||[]})}function ce(ae){ue();const je={role:"user",parts:[{type:"text",text:ae.title+" "+ae.subtitle}]};L(je)}function be(ae){ue(),L({role:"user",parts:[{type:"text",text:ae}]})}function Ue(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:o,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:u,children:"System Message"})]})]})}function Me(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Ne=(W==null?void 0:W.length)===0&&(w==null?void 0:w.filter(ae=>ae.role==="user").length)===0,me=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:[Me(),N&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:N,children:(I==null?void 0:I.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Ue(),c&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground/70 hover:text-foreground",onClick:J,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:b?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:se,children:b?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:le,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:"New Chat",onClick:()=>{M([]),f("editor"),_(),he()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",onClick:()=>{F(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:ge,className:"mt-2 flex w-full grow basis-0",onScroll:ie,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[U&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:ne,className:"text-xs",children:["Load ",Math.min(5,ee-K.length)," ","more messages (",ee-K.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:K,showTools:c,handleRun:oe,showSystemMessage:d,onQuickReply:P,disableQuickReplies:O}),!xe&&e.jsx(s.AssistantStatus,{status:z,errorMessage:Q})]})}),!V&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{re({force:!0}),de()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),Z&&te>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:te>9?"9+":te})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Ne&&!I&&e.jsx(s.Placeholders,{onClick:ce,placeholders:bl}),e.jsx("div",{children:Ne&&I&&e.jsx(s.SeedQuestions,{seedQuestions:I.seedQuestions||[],handleSeedQuestionClick:be})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:$,stop:R,input:W,handleInputChange:X,handleSubmit:ae=>{ue(),Y(ae),re({force:!0})},isLoading:O,status:z,assistantType:"editor",onFocus:()=>{}})]}),G&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",G.inputTokens," prompt tokens, ",G.outputTokens," ","completion tokens, ",G.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(C==null?void 0:C.selectedEntities)||[],open:m,onOpenChange:h,dataSource:C||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return b&&a?ra.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:me})}),a):me}const Fs=t=>{var T;const{updateCardConfig:n,updateGroupByColumn:a,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(B=>B.card.type),h=t==null?void 0:t.id,x=A.useCallback(B=>{if(!(t!=null&&t.config))return[];switch(B){case"groupBy":return(t.config.groupByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,dateFormat:I.dateFormat,customFormat:I.customFormat,granularity:I.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,direction:I.direction}));case"source":return[];default:return[]}},[t]),g=A.useCallback((B,I)=>{if(h)switch(B){case"groupBy":{n(h,{groupByColumns:I});break}case"metrics":{n(h,{metricColumns:I});break}case"pivotBy":{n(h,{pivotByColumns:I});break}case"sortBy":{n(h,{sortByColumns:I});break}}},[h,n]),b=A.useCallback((B,I,w)=>{if(!h)return;const L=x(B)[I];if(L)switch(B){case"groupBy":a(h,L.id,{label:w});break;case"metrics":r(h,L.id,{label:w});break;case"pivotBy":l(h,L.id,{label:w});break;case"sortBy":o(h,L.id,{label:w});break}},[h,x,a,r,l,o]),p=A.useCallback((B,I)=>{if(!h)return;const M=x("metrics")[B];M&&r(h,M.id,{aggregate:I,label:s.getAggregationLabel(M.name,I)})},[h,x,r]),j=A.useCallback((B,I,w)=>{if(!h)return;const L=x("groupBy")[B];if(!L)return;const O={dateFormat:I};I==="custom"&&w?O.customFormat=w:O.customFormat=void 0,a(h,L.id,O)},[h,x,a]),f=A.useCallback((B,I)=>{if(!h)return;const M=x("groupBy")[B];M&&a(h,M.id,{granularity:I})},[h,x,a]),y=A.useCallback((B,I)=>{if(!h)return;const M=x("metrics")[B];M&&r(h,M.id,{aliasTemplate:I})},[h,x,r]),E=A.useCallback((B,I)=>{if(console.log("handleValueAliasesChange",B,I),!h)return;console.log("handleValueAliasesChange",B,I);const M=x("metrics")[B];M&&(console.log("handleValueAliasesChange",I),r(h,M.id,{valueAliases:I}))},[h,x,r]),D=A.useCallback(B=>{h&&n(h,{comparisonType:B})},[h,n]),C=A.useCallback(B=>{h&&n(h,{showTrendline:B})},[h,n]),S=A.useCallback(B=>{h&&n(h,{trendlineWindow:B})},[h,n]),v=A.useCallback(B=>{h&&n(h,{trendlineGranularity:B})},[h,n]),k=A.useCallback(B=>{h&&n(h,{targetValue:B})},[h,n]),N=A.useCallback(B=>{var z;if(!h)return;const I=[...x("groupBy"),...x("pivotBy"),...x("metrics"),...x("sortBy")],w=(z=t==null?void 0:t.config)==null?void 0:z.joinPlan,M=s.validateEntityConsistency(B,I,w);if(!M.isValid){M.showError&&s.showJoinRequiredNotification();return}const L=s.getSmartContainerForField(B,I),O=x(L);if(s.fieldAlreadyExists(B,O))return;const R=s.getNewField(B,L,O);R&&g(L,[...O,R])},[h,(T=t==null?void 0:t.config)==null?void 0:T.joinPlan,x,g]),F=A.useCallback((B,I)=>{if(!h)return;const M=x(B)[I];if(M){if(B!=="sortBy"){const L=x("sortBy"),O=L.filter(R=>!(R.name===M.name&&R.qualifiedEntityName===M.qualifiedEntityName));O.length!==L.length&&n(h,{sortByColumns:O})}switch(B){case"groupBy":c(h,M.id);break;case"metrics":i(h,M.id);break;case"pivotBy":d(h,M.id);break;case"sortBy":u(h,M.id);break}}},[h,x,c,i,d,u,n]);return{getFieldsForContainer:x,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:p,handleDateFormatChange:j,handleGranularityChange:f,handleAliasTemplateChange:y,handleValueAliasesChange:E,removeField:F,handleFieldClick:N,handleKpiComparisonTypeChange:D,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:S,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:k,cardType:m}};function vl({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function yl({field:t}){const{attributes:n,listeners:a,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,d]=A.useState(!1),u=s.useEditorStore(b=>b.card),{handleFieldClick:m}=Fs(u),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const x=b=>{const p=(b||"").toLowerCase();switch(s.getDataType(p)){case"number":return Ie;case"date":return s.Calendar;case"boolean":return Pe;case"json":return $e;case"geo":return Xe;default:return Se}},g=b=>{const p=(b||"").toLowerCase(),j=s.getDataType(p);return j==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Se,{className:"h-3 w-3"})}):j==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ie,{className:"h-3 w-3"})}):j==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):j==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Pe,{className:"h-3 w-3"})}):j==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx($e,{className:"h-3 w-3"})}):j==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Xe,{className:"h-3 w-3"})}):j==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ss,{className:"h-3 w-3"})}):null};return x(t.dataType),e.jsxs("div",{ref:r,style:h,...n,...a,className:`group/container max-w-[265px] overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>m(t),children:[g(t.dataType),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(vl,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{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(Wa,{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 Nl(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useEditorStore(E=>E.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),u=o.filter(E=>E.name.toLowerCase().includes(t.toLowerCase())||E.dataType.toLowerCase().includes(t.toLowerCase())||E.qualifiedEntityName&&E.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=E=>{if(E.dataType==="number"||E.dataType==="integer"||E.dataType==="float"||E.dataType==="decimal"||E.dataType==="currency")return"metrics";const D=s.getDataType(E.dataType);return["date","string","boolean"].includes(D)?"dimensions":D==="number"?"metrics":"dimensions"},x=(a==="all"?u:u.filter(E=>m(E)===a)).reduce((E,D)=>{const C=D.qualifiedEntityName||"Other Fields";return E[C]||(E[C]={label:s.toLabel(D.entityName),fields:[]}),E[C].fields.push(D),E},{}),b=Object.keys(x),p=u.filter(E=>m(E)==="dimensions").length,j=u.filter(E=>m(E)==="metrics").length,f=u.filter(E=>m(E)==="calculated").length,y=u.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[o.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:t,onChange:E=>n(E.target.value)}),t&&e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:e.jsx(s.X,{className:"size-3.5"})})]}),y&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:E=>r(E),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:u.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(ss,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:b,className:"space-y-2",children:Object.entries(x).map(([E,D])=>{const C=c.find(S=>S.entityName===E)||{entityName:E,label:D.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:C.label||C.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:C.label||C.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:D.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:D.fields.map(S=>e.jsx(yl,{field:S},S.id))})})]},E)})}),Object.keys(x).length===0&&o.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(x).length===0&&o.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function Cl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(Nl,{})," "]})}function Sl({initialJoinPlan:t,availableDataSources:n}){const[a,r]=A.useState(t),[l,o]=A.useState(new Set),c=()=>{const S=a.joins.length>0?Math.max(...a.joins.map(k=>k.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:S,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,v]}),o(new Set([...l,v.id]))},i=S=>{r({...a,joins:a.joins.filter(v=>v.id!==S)}),o(new Set([...l].filter(v=>v!==S)))},d=(S,v)=>{var T,B;const k=a.joins.find(I=>I.id===S);if(!k)return;const N={...k,...v},F=a.joins.map(I=>I.id===S?N:I);if((T=N.source)!=null&&T.name&&((B=N.target)!=null&&B.name)&&N.joinKeyGroups[0].keys.length===0){const I=n.find(O=>{var R;return O.name===((R=N.source)==null?void 0:R.name)}),w=n.find(O=>{var R;return O.name===((R=N.target)==null?void 0:R.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:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},operator:"="},L=[...N.joinKeyGroups];L[0]={...L[0],keys:[M]},N.joinKeyGroups=L,F[F.findIndex(O=>O.id===S)]=N}r({...a,joins:F})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:S=>{const v=a.joins.findIndex(k=>k.id===S);if(v>0){const k=[...a.joins],N={...k[v]},F={...k[v-1]};k[v]=F,k[v-1]=N,k.forEach((B,I)=>{B.sequence=I+1});const T={...a,joins:k};r(T)}},moveJoinDown:S=>{const v=a.joins.findIndex(k=>k.id===S);if(v<a.joins.length-1){const k=[...a.joins],N={...k[v]},F={...k[v+1]};k[v]=F,k[v+1]=N,k.forEach((B,I)=>{B.sequence=I+1});const T={...a,joins:k};r(T)}},toggleJoinExpansion:S=>{const v=new Set(l);v.has(S)?v.delete(S):v.add(S),o(v)},getAvailableSourceEntities:S=>{if(a.joins.length===0)return n;const v=a.joins.findIndex(N=>N.id===S);if(v===0)return n;const k=new Set;return a.baseEntity.name&&k.add(a.baseEntity.name),a.joins.slice(0,v).forEach(N=>{k.add(N.source.name),k.add(N.target.name)}),n.filter(N=>k.has(N.name))},getAvailableTargetEntities:S=>n.filter(v=>v.name!==S),addJoinKeyGroup:S=>{const v=a.joins.find(N=>N.id===S);if(!v)return;const k=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(S,{joinKeyGroups:k})},updateGroupOperator:(S,v,k)=>{const N=a.joins.find(T=>T.id===S);if(!N)return;const F=[...N.joinKeyGroups];F[v]={...F[v],operator:k},d(S,{joinKeyGroups:F})},removeJoinKeyGroup:(S,v)=>{const k=a.joins.find(F=>F.id===S);if(!k)return;const N=[...k.joinKeyGroups];N.splice(v,1),d(S,{joinKeyGroups:N})},addJoinKey:(S,v)=>{const k=a.joins.find(I=>I.id===S);if(!k)return;const N=n.find(I=>I.name===k.source.name),F=n.find(I=>I.name===k.target.name),T=[...k.joinKeyGroups],B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(N==null?void 0:N.name)||"",entityName:(N==null?void 0:N.name)||"",entityType:(N==null?void 0:N.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(F==null?void 0:F.name)||"",entityName:(F==null?void 0:F.name)||"",entityType:(F==null?void 0:F.type)||"table"},operator:"="};T[v]={...T[v],keys:[...T[v].keys,B]},d(S,{joinKeyGroups:T})},updateJoinKey:(S,v,k,N,F)=>{const T=a.joins.find(L=>L.id===S);if(!T)return;const B=n.find(L=>L.name===T.source.name),I=n.find(L=>L.name===T.target.name),w=[...T.joinKeyGroups],M=w[v].keys[k];N==="sourceColumnName"&&B?w[v].keys[k]={...M,source:{...M.source,name:F}}:N==="targetColumnName"&&I?w[v].keys[k]={...M,target:{...M.target,name:F}}:N==="operator"&&(w[v].keys[k]={...M,operator:F}),d(S,{joinKeyGroups:w})},removeJoinKey:(S,v,k)=>{const N=a.joins.find(T=>T.id===S);if(!N)return;const F=[...N.joinKeyGroups];F[v].keys.splice(k,1),d(S,{joinKeyGroups:F})},generateSQLPreview:()=>{const S=[...a.joins].sort((N,F)=>N.sequence-F.sequence),v=a.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let k=`SELECT *
329
- FROM ${v.name}`;return S.forEach(N=>{const F=n.find(I=>I.name===N.target.name);if(!F)return;const T=N.joinKeyGroups.filter(I=>I.keys&&I.keys.length>0).map(I=>{const w=I.keys.filter(M=>{var L,O,R,z;return((L=M.source)==null?void 0:L.name)&&((O=M.target)==null?void 0:O.name)&&((R=M.source)==null?void 0:R.entityName)&&((z=M.target)==null?void 0:z.entityName)}).map(M=>`${M.source.entityName}.${M.source.name} ${M.operator} ${M.target.entityName}.${M.target.name}`);return w.length>1?`(${w.join(` ${I.operator} `)})`:w[0]}).filter(Boolean),B=T.length>1?T.join(" OR "):T[0]||"condition_here";k+=`
330
- ${N.joinType} JOIN ${F.name}
331
- ON ${B}`}),k},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(N=>!N.source.name||!N.target.name)||a.joins.some(N=>N.joinKeyGroups.some(F=>F.keys.length===0))||a.joins.some(N=>N.joinKeyGroups.some(F=>F.keys.some(T=>!T.source.name||!T.target.name||!T.operator))))}}function wl({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(T=>T.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:x,moveJoinUp:g,moveJoinDown:b,toggleJoinExpansion:p,getAvailableSourceEntities:j,getAvailableTargetEntities:f,addJoinKeyGroup:y,updateGroupOperator:E,removeJoinKeyGroup:D,addJoinKey:C,updateJoinKey:S,removeJoinKey:v,generateSQLPreview:k,isValidConfiguration:N}=Sl({initialJoinPlan:t,availableDataSources:n}),F=T=>{const B=c.find(I=>I.entityName===T);return(B==null?void 0:B.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:T=>{const B=n.find(I=>I.name===T);u({...i,baseEntity:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:T,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(T=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:T.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:T.type}),T.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},T.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:k()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(T=>{const B=n.find(M=>M.name===T.source.name),I=n.find(M=>M.name===T.target.name),w=d.has(T.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:T.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",T.sequence,B&&I&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",B.name," → ",I.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(T.id),disabled:T.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(T.id),disabled:T.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(T.id),children:w?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(T.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),w&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:T.source.name,onValueChange:M=>{const L=n.find(O=>O.name===M);x(T.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:M,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:j(T.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:T.joinType,onValueChange:M=>x(T.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:T.target.name,onValueChange:M=>{const L=n.find(O=>O.name===M);x(T.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:M,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},disabled:!T.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:T.source.name?f(T.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===T.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},M.name)):[]})]})]})]}),T.source.name&&T.target.name&&B&&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:()=>y(T.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),T.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:T.joinKeyGroups.map((M,L)=>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 ",L+1]}),L>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:O=>E(T.id,L,O),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:()=>D(T.id,L),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((O,R)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[R>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:O.source.name,onValueChange:z=>S(T.id,L,R,"sourceColumnName",z),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:F(T.source.name).map(z=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:z.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:O.operator,onValueChange:z=>S(T.id,L,R,"operator",z),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:O.target.name,onValueChange:z=>S(T.id,L,R,"targetColumnName",z),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:F(T.target.name).map(z=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:z.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>v(T.id,L,R),children:e.jsx(s.X,{className:"size-3.5"})})]},O.id||R))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>C(T.id,L),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},M.id))})]})]})]},T.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(i),disabled:!N(),children:"Save"})]})]})}function Zs({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(wl,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function Dl({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=a.find(c=>c.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=a.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=a.find(d=>d.name===l.source.name),i=a.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function Tl(){var m,h;const t=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>x.actions.updateCardConfig),a=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=A.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=x=>{n(t.id,{...t==null?void 0:t.config,joinPlan:x}),l(!1)},i=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},u=()=>{const x=[...a.joins].sort((p,j)=>p.sequence-j.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let b=`SELECT *
332
- FROM ${g.name}`;return x.forEach(p=>{const j=o.find(E=>E.name===p.target.name);if(!j)return;const f=p.joinKeyGroups.filter(E=>E.keys&&E.keys.length>0).map(E=>{const D=E.keys.filter(C=>{var S,v,k,N;return((S=C.source)==null?void 0:S.name)&&((v=C.target)==null?void 0:v.name)&&((k=C.source)==null?void 0:k.entityName)&&((N=C.target)==null?void 0:N.entityName)}).map(C=>`${C.source.entityName}.${C.source.name} ${C.operator} ${C.target.entityName}.${C.target.name}`);return D.length>1?`(${D.join(` ${E.operator} `)})`:D[0]}).filter(Boolean),y=f.length>1?f.join(" OR "):f[0]||"condition_here";b+=`
327
+ `;I(V)}function P(){return e.jsxs(e.Fragment,{children:[l&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(nr,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>o(!l),className:"absolute bottom-0 right-6 size-7 p-1",children:l?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function G(){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(tr,{})}),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(ar,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function J(){return e.jsx("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:C||F,onClick:()=>{L()},className:"h-8 shrink-0",size:"sm",children:[C||F?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(At,{errorSql:w,sql:k==null?void 0:k.sql,error:O,onDebugWithAssistant:R}),e.jsx(xs,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:V=>r(V),className:"h-8",size:"sm",variant:"outline",children:e.jsx(sr,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:i,onClick:()=>{D(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:i?"":"Type your question..."})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[G(),P()]}),J()]})}const lr=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:ms}];function or({className:t}){const n=s.useEditorStore(d=>d.card),{setCardType:a,setCard:r,updateCardInFrame:l}=s.useEditorActions(),o=["table","aggregateTable","pivotTable"].includes(n.type),c=s.hasValidCardConfig(n.config);if(!o||!c)return null;const i=d=>{var m;const u=d;if(u==="aggregateTable"&&((m=n.config)!=null&&m.pivotByColumns)&&n.config.pivotByColumns.length>0){const h={...n,type:u,config:{...n.config,pivotByColumns:[]}};r(h),l(h)}else{a(u);const h={...n,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:i,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:lr.map(d=>{const u=d.icon,m=n.type===d.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:d.value,id:`table-type-${d.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${d.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",m?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),d.label]})]},d.value)})})})}function ir({card:t}){var I,D,N,S,v,k,C,F,T,B,E;const[n,a]=A.useState(!1),[r,l]=A.useState([]),{authToken:o}=s.useSemaphorContext(),{theme:c}=s.useTheme(),i=s.getTokenParams(o==null?void 0:o.accessToken),d=s.useDashboardStore(w=>w.themeStyle),u={mode:c||"system",colors:((D=(I=d==null?void 0:d.chart)==null?void 0:I.dataset)==null?void 0:D.backgroundColor)||[]};(N=t.customCardPreferences)!=null&&N.inputData;const{getCard:m}=s.useCustomVisual(((S=t.customCardPreferences)==null?void 0:S.url)||""),h=((v=t.customCardPreferences)==null?void 0:v.visualType)||"single",x=s.useEditorStore(w=>w.frame),{setCustomCardPreferences:g}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(t),p=A.useCallback((w,M)=>{l(L=>({...L,[w]:M}))},[]);if(!((k=t.customCardPreferences)!=null&&k.componentName))return null;const j=m((C=t.customCardPreferences)==null?void 0:C.componentName);function f(w){a(w)}const y=Object.keys(((F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)||{}).map(w=>{var O,R,P;const M=(R=(O=t.customCardPreferences)==null?void 0:O.dataInputCardIds)==null?void 0:R[w].cardId,L=(P=x==null?void 0:x.cards)==null?void 0:P.find(G=>G.id===M);return L||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(A.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[j&&h==="single"&&e.jsx(j,{editing:!0,params:i,theme:u,settings:(T=t.customCardPreferences)==null?void 0:T.settings,onDataChange:p,data:(b==null?void 0:b.records)||[]}),j&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((B=t.customCardPreferences)==null?void 0:B.dataInputCardIds)||{}).map(w=>{var O,R,P;const M=(R=(O=t.customCardPreferences)==null?void 0:O.dataInputCardIds)==null?void 0:R[w].cardId,L=(P=x==null?void 0:x.cards)==null?void 0:P.find(G=>G.id===M);if(L)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:f,onDataChange:p,dataInputIndex:w,card:L},L.id+w)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(j,{theme:u,onDataChange:p,settings:y.map(w=>{var M;return(M=w==null?void 0:w.customCardPreferences)==null?void 0:M.settings}),data:y.map(w=>w!=null&&w.id?r==null?void 0:r[w.id]:[])})})]})]},(E=t.customCardPreferences)==null?void 0:E.componentName)})}function Lt({className:t,...n}){var k;const a=s.useEditorStore(C=>C.card),r=s.isExplorerCard(a),l=((k=a.customCardPreferences)==null?void 0:k.showCardHeader)??!0,o=s.useEditorStore(C=>C.frame),c=s.useDashboardStore(C=>C.dashboard.filters),i=s.useEditorStore(C=>C.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),u=c==null?void 0:c.find(C=>C.id===o.filterId),{data:m,isLoading:h,isFetching:x,errorMessage:g,pagination:b}=s.useDashboardCardQuery(a),{setCard:p,updateCardInFrame:j}=s.useEditorActions(),{data:f}=s.useTopoJson(a),y=A.useMemo(()=>{var C;return a.type!=="pivotTable"||!((C=m==null?void 0:m.records)!=null&&C.length)?null:{records:m.records,columnSubtotalMeta:m.columnSubtotalMeta,subtotalColumns:m.subtotalColumns||[],pivotSchema:m.pivotSchema||[],groupByColumns:m.groupByColumns}},[a.type,m==null?void 0:m.records,m==null?void 0:m.columnSubtotalMeta,m==null?void 0:m.subtotalColumns,m==null?void 0:m.pivotSchema,m==null?void 0:m.groupByColumns]),I=s.usePivotTableConfig(a,y),D=(C,F)=>{var B,E;const T={...a,paginationConfig:{page:C+1,pageSize:F}};p(T),j(T),a.sql&&((E=(B=a.preferences)==null?void 0:B.tablePrefs)!=null&&E.enableDevModePagination)&&i(!0)},N=A.useMemo(()=>!a.id||!(m!=null&&m.records)?null:s.createChartConfig({card:a,data:m==null?void 0:m.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:f}),[a.id,m==null?void 0:m.records,a.type,a.queryConfig,a.customCfg,a.preferences,f]);function S(C){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(ir,{card:C})})}function v(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!x)return g?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||x)&&a.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return S(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&N)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:h||x?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:N})});if(a.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:a,data:(m==null?void 0:m.records)||[],paginationMetadata:b,onPaginationChange:D,isLoading:h||x})});if(a.type==="pivotTable"&&I)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:I.data,options:I.options,onAggregationChange:C=>{const F=s.handleAggregationChange(C,a.config),T={...a,config:F};p(T),j(T)},onAggregationLabelChange:C=>{const F=s.handleAggregationLabelChange(C,a.config),T={...a,config:F};p(T),j(T)}})});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:D,onAggregationChange:C=>{const F=s.handleAggregationChange(C,a.config),T={...a,config:F};p(T),j(T)},isLoading:h||x})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-5",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:C=>p({...a,title:C}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(or,{})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:C=>p({...a,description:C}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),u&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:u.title||u.column,onSave:C=>d({...u,title:C}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:u})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:v()})]})}const Ns=({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}),cr=()=>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."})]})]}),dr=({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(Ns,{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(Ns,{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(Ns,{language:"javascript",value:t,onChange:l})})]}),ur=({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 mr(){const[t,n]=A.useState(!1),[a,r]=A.useState(""),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(""),m=s.useEditorStore(N=>N.card),h=s.useEditorStore(N=>N.card.customCfg),x=h?JSON.stringify(h,null,2):"",{data:g}=s.useDashboardCardQuery(m),{data:b}=s.useTopoJson(m),{setCardCustomCfg:p,setCustomVisualCode:j}=s.useEditorActions(),f=N=>{var S,v;return JSON.stringify({...N,data:{...N.data,datasets:(v=(S=N.data)==null?void 0:S.datasets)==null?void 0:v.map(k=>({...k,data:[]}))}},null,2)},y=()=>{var S,v;if(!((S=g==null?void 0:g.records)!=null&&S.length))return;const N=s.createChartConfig({card:m,data:g.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:b});if(N){r(f(N)),i(((v=m.preferences)==null?void 0:v.customVisualCode)||"");const k=s.merge(N,h);o(f(k))}},I=()=>{try{if(c&&j(c),l){const N=JSON.parse(l),S=s.getObjectDiff(JSON.parse(a),N);p(S),u("")}}catch{u("Invalid JSON configuration")}},D=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:y,className:D?"":"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(cr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Lt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(dr,{customCode:c,cardCustomCfgString:x,mergedConfig:l,onConfigChange:N=>o(N??""),onCodeChange:N=>i(N??"")})]}),e.jsx(ur,{error:d,hasCardCustomConfig:!!h,onReset:()=>{o(a),p(null)},onApply:I,onClose:()=>n(!1)})]})]})}function ps(t){const[n,a]=A.useState(null);return n}function Rt(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{data:a,isLoading:r,isFetching:l,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(n.apiServiceUrl,t==null?void 0:t.accessToken)});return{data:a,isLoading:r,isFetching:l,isError:o}}function Ot(){const{data:t,isLoading:n,isError:a}=Rt(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let o=n,c=a;return r.forEach((i,d)=>{var u;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const m=t.plugins[d],h=i.data.visuals.map(x=>({name:x.name,pluginName:m.label,componentType:x.componentType,pluginType:m.type,icon:x.icon,chartType:x.chartType,url:m.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function hr({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=Ot(),d=A.useCallback((u,m)=>{n(null),a({}),r(u),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[n,a,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((u,m)=>e.jsx(xr,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const xr=({text:t,icon:n,onClick:a})=>{const r=ps(),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 Ft({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(m,h){o(null),r({}),a(m),["custom","text","map"].includes(m)&&(l(!0),i(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(s.Table2,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnIncreasing,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(s.ChartLine,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnStacked,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(s.MdStackedLineChart,{className:s.cn("size-5",n),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(s.ChartScatter,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(s.TbChartBubble,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(s.ChartPie,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(s.Donut,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(s.TbChartFunnel,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(s.Radar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(s.PiChartPolar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(s.Tornado,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(s.ChartNoAxesGantt,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(s.TiSortNumerically,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(s.Map,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Ze,{className:s.cn("size-5",n)})})]})}function pr({chartType:t,className:n,customIcon:a,componentName:r}){const l=ps();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(we,{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 o,c;const[n,a]=A.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(pr,{className:"size-4",chartType:l,customIcon:(o=r.customCardPreferences)==null?void 0:o.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"z-[51] w-72 p-1",children:[e.jsx(Ft,{onChartTypeChange:()=>a(!1)}),e.jsx(hr,{onChartTypeChange:()=>a(!1)})]})]})}function fr({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,o]=A.useState(!1),c=A.useRef(null),i=A.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(x){(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d())}function m(){const x=window.getSelection();if(x&&x.toString().trim()!==""){const g=x.toString();navigator.clipboard.writeText(g),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function gr(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx($s,{className:"size-4"}):e.jsx(Ys,{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($s,{className:"size-4"}):e.jsx(Ys,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function jr({className:t}){var x,g,b,p,j,f,y,I;const n=s.useEditorStore(D=>D.card),{setCardPreferences:a,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[o,c]=A.useState(!1),i=((g=(x=n.preferences)==null?void 0:x.displayOptions)==null?void 0:g.showFilterInfo)??!0,d=((p=(b=n.preferences)==null?void 0:b.displayOptions)==null?void 0:p.showCardToolbar)??!0,u=((f=(j=n.preferences)==null?void 0:j.displayOptions)==null?void 0:f.showChrome)??!0,m=((I=(y=n.preferences)==null?void 0:y.displayOptions)==null?void 0:I.allowScroll)??!0,h=(D,N)=>{var k;const S={...n.preferences,displayOptions:{...(k=n.preferences)==null?void 0:k.displayOptions,[D]:N}};a(S);const v={...n,preferences:S};l(v),r(v)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:o,onOpenChange:c,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(ot,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:D=>{h("showFilterInfo",D)},onSelect:D=>D.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:D=>{h("showCardToolbar",D)},onSelect:D=>D.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:D=>{h("showChrome",D)},onSelect:D=>D.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:D=>{h("allowScroll",D)},onSelect:D=>D.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 Pt(){const t=s.useEditorStore(o=>o.card);s.useEditorStore(o=>o.isShowingVisual);const n=s.useEditorStore(o=>{var c,i;return(i=(c=o.card)==null?void 0:c.preferences)==null?void 0:i.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function l(){const o=["xy","none","x","y"],i=(o.indexOf(a)+1)%o.length;r(o[i])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(gr,{})}),!["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(ms,{className:"size-4"}),a==="x"&&e.jsx(ja,{className:"size-4"}),a==="y"&&e.jsx(_a,{className:"size-4"}),a==="none"&&e.jsx($a,{className:"size-4"})]}),e.jsx(jr,{})]})}function br(){const t=s.useEditorStore(b=>b.frame),n=s.useEditorStore(b=>b.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(b,p)=>{b.dataTransfer.setData("tabIndex",p.toString())},i=b=>{b.preventDefault()},d=(b,p)=>{const j=b.dataTransfer.getData("tabIndex");if(j===p.toString())return;const f=Array.from(t.cards),[y]=f.splice(parseInt(j),1);f.splice(p,0,y),a({...t,cards:f})};function u(b){const p=t.cards.filter(y=>y.id!==b),j=p[0],f={...t,cards:p,activeCardId:j.id};a(f),r(j.id),l(j)}function m(b,p){const j={...t,cards:[...t.cards,p],activeCardId:b.id};a(j),r(p.id)}function h(){const b={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};m(n,b)}function x(b){const p={dataSource:b.dataSource,connectionId:b.connectionId,lastSelectedDatabase:b.lastSelectedDatabase,lastSelectedSchema:b.lastSelectedSchema,lastSelectedTable:b.lastSelectedTable,lastSelectedDatamodelId:b.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(b,p)}function g(b,p){return b.cards.length===1&&(p.displayTab===!0||p.displayTab===void 0)||b.activeCardId!==p.id&&(p.displayTab===!0||p.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const j=p.displayTab===void 0?!1:!p.displayTab;l({...p,displayTab:j}),o({...p,displayTab:j})},children:p.displayTab===!0||p.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(ya,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((b,p)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:j=>c(j,p),onDragOver:i,onDrop:j=>d(j,p),className:"",value:b.id,children:[g(t,b),e.jsx(s.Editable,{enabled:t.activeCardId===b.id,text:b.tabTitle||b.title,onSave:j=>{l({...n,tabTitle:j}),o({...n,tabTitle:j})},children:b.tabTitle||b.title},b.id),t.activeCardId===b.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(b.id)})]},b.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>x(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(s.CopyPlus,{className:"h-4 w-4"})})]})})}function zt(){const t=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.isSqlRunning),r=s.useEditorStore(p=>p.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h}=s.useDashboardCardQuery(n);function x(p){const j=t.cards.find(f=>f.id===p);if(j!=null&&j.sql){r||i(!0),o(p);return}if(j!=null&&j.queryConfig){r&&i(!1),g(p),o(p);return}r||g(p),o(p)}function g(p){const j={...t,cards:t.cards.map(y=>y.id===n.id?n:y),activeCardId:p};l(j);const f=j.cards.find(y=>y.id===p);f.sql&&d(!0),c(f)}function b(){return n.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:u==null?void 0:u.records,isPending:m||h})})}):n.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Lt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:x,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(p=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:p.id,children:b()},p.id)),e.jsx(br,{})]})}function as({children:t}){var D,N;s.useEditorStore(S=>S.frame);const n=s.useEditorStore(S=>S.card),a=s.useEditorStore(S=>S.isDevMode),r=s.useEditorStore(S=>S.isShowingVisual),l=s.useDashboardStore(S=>S.isVisualEditing),o=s.useEditorStore(S=>S.pythonStdOut);s.useEditorStore(S=>S.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:x,isLoading:g,isFetching:b,errorMessage:p,refetch:j}=s.useDashboardCardQuery(n);function f(){const S=JSON.stringify(x==null?void 0:x.records,null,2),v=new Blob([S],{type:"application/json"}),k=URL.createObjectURL(v),C=document.createElement("a");C.href=k,C.download=`${n.title}.json`,C.click()}function y(){const v=[Object.keys(x==null?void 0:x.records.reduce((T,B)=>({...T,...B}),{})).join(","),...((x==null?void 0:x.records)||[]).map(T=>Object.values(T).join(","))].join(`
328
+ `),k=new Blob([v],{type:"text/csv"}),C=URL.createObjectURL(k),F=document.createElement("a");F.href=C,F.download=`${n.title}.csv`,F.click()}function I(){const S=`Can you get the documentation for ${n.type} chart?`;u(S)}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:I,children:e.jsx(ha,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(mr,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:y,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:f,children:e.jsx(Ca,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(x==null?void 0:x.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(Pt,{})]}),n.type==="table"&&n.sql&&!s.hasValidCardConfig(n.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((N=(D=n.preferences)==null?void 0:D.tablePrefs)==null?void 0:N.enableDevModePagination)??!1,onCheckedChange:S=>{var v;h({...n.preferences,tablePrefs:{...(v=n.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:S}}),j()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(yr,{})]}),r?e.jsx(zt,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:o&&e.jsx(vr,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":o}),children:[(x==null?void 0:x.records)&&(x==null?void 0:x.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(x==null?void 0:x.records)||[]}),p&&e.jsx(fr,{error:p})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function vr(){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 yr(){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 ke({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function Nr(){var p,j;const t=s.useEditorStore(f=>f.card.customCardPreferences),{data:n}=Rt(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(f=>f.card),l=s.useEditorStore(f=>f.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(p=d==null?void 0:d.visuals)==null?void 0:p.find(f=>f.name===(t==null?void 0:t.componentName));function m(f,y){if(!t)return;const D={...(t==null?void 0:t.dataInputCardIds)||{},[f]:{cardId:y,hookRef:null}};c({...t,dataInputCardIds:D})}function h(f){var I,D;const y=(I=l==null?void 0:l.cards)==null?void 0:I.filter(N=>{var S;return((S=N==null?void 0:N.customCardPreferences)==null?void 0:S.visualType)!=="multiple"}).map(N=>({value:N.id,label:N.tabTitle||N.title}));return e.jsx("div",{className:"space-y-2",children:(D=f==null?void 0:f.dataInputs)==null?void 0:D.map((N,S)=>{var v,k;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:N}),e.jsx(ke,{className:"col-span-6 h-8 w-full justify-between",label:"",options:y||[],value:((k=(v=t==null?void 0:t.dataInputCardIds)==null?void 0:v[S])==null?void 0:k.cardId)||"",onValueChange:C=>m(S,C)})]},S+Math.random())})})}function x(f,y,I=[],D=""){var N,S;return t?f==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((N=t==null?void 0:t.settings)==null?void 0:N[y])||D,onChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[y]:v.target.value}})}},y):f==="select"?e.jsx(ke,{className:"h-8 w-full",label:"",options:I,value:((S=t==null?void 0:t.settings)==null?void 0:S[y])||D,onValueChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[y]:v}})}}):null:null}function g(f){const y=Object.entries((f==null?void 0:f.settings)||{});return e.jsx("div",{className:"space-y-3",children:y.map(([I,D])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:D.title}),x(D.ui,I,D.options,D.defaultValue)]},I))})}function b(f){t&&c({...t,visualType:f,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(ke,{icon:e.jsx(ma,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:f=>c({...t||{url:"",componentName:""},url:f})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:b,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(ke,{icon:e.jsx(ba,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(f=>f.type===o).map(f=>({value:f.name,label:f.name})))||[],value:t.componentName,onValueChange:f=>{console.log("changing value",f),c({...t,componentName:f})}})})]})})]}),((j=r==null?void 0:r.customCardPreferences)==null?void 0:j.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(u)})})]})]})]})}function Ue(){const[t,n]=A.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),o=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),A.useEffect(()=>{o&&n(new Array(o.length).fill(!1))},[o]);function c(u,m){var h,x;m?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):l({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...a,onClickFilter:(x=a==null?void 0:a.onClickFilter)==null?void 0:x.filter(g=>g.columnIndex!==u)}),n(g=>{const b=[...g];return b[u]=!1,b}))}function i(u,m){var x;const h=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.map(g=>g.columnIndex===u?{...g,expression:m.target.value}:g);l({...a,onClickFilter:h})}function d(u){var m,h,x,g;if(t!=null&&t[u]||(h=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(b=>b.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(b=>b.columnIndex===u))==null?void 0:g.expression,onChange:b=>i(u,b),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:o==null?void 0:o.map((u,m)=>{var h,x;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(g=>g.columnIndex===m)),onCheckedChange:g=>c(m,g)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(g=>g.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{n(g=>{const b=[...g];return b[m]=!g[m],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function Cr({idx:t}){var i;const n=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),a=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=n==null?void 0:n.chartOptions)==null?void 0:i.indexAxis,o=a==null?void 0:a.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:m}]});else{const h={...o};h.datalabels=m;const x=a==null?void 0:a.map(g=>g.idx===u?h:g);r({...n,datasetOptions:x})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(it,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ia,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ma,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Aa,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function Sr(){const t=s.useEditorStore(o=>o.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function fs({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 Vt(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=Sr();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:o.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:_t(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(Ut,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function _t(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Ut({col:t,idx:n,className:a,iconClassName:r,children:l}){const o=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,x;return(x=(h=m.card)==null?void 0:h.preferences)==null?void 0:x.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===n),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...o,datasetOptions:[...c||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const x=c==null?void 0:c.map(g=>g.idx===n?h:g);d({...o,datasetOptions:x})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(fs,{className:"max-w-[100px]",title:t,children:_t(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(Cr,{idx:n})]})]})}function Ls(){const t=s.useEditorStore(g=>g.selectedConnectionId),n=s.useEditorStore(g=>g.selectedDatamodelId),a=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),l=s.useEditorStore(g=>g.selectedTableName),o=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:h}=s.useEditorAside();function x(g,b="dashboard",p){var k;const j=s.fmt(g.column_name),f=s.fmt(a||""),y=s.fmt(r||""),I=s.fmt(m);let D=s.getQualifiedTableName({schemaName:y,tableName:I,connectionType:h,databaseName:f}),N=`${D}.${j}`;const S=(k=u==null?void 0:u.find(C=>C.id===n))==null?void 0:k.name;n&&n!=="none"&&(N=`${s.DATAMODEL_NAMESPCACE}.${S}.${j}`,D=`${s.DATAMODEL_NAMESPCACE}.${S}`),p!=null&&p.qualifiedFieldName&&(N=p.qualifiedFieldName),p!=null&&p.entityName&&(D=p.entityName);const v=o==null?void 0:o.find(C=>C.column===N&&C.table===I&&(C.database===f||C.database===a));if(v)d(v.id),i(v.id);else{const C=s.v4();return m==="api"&&t?(c({location:b,id:C,column:N,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,D,j)}),C):(c({id:C,location:b,column:N,title:g.column_name,dataType:g.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,D,j)}),C)}}return{assignFilter:x}}function Ke(){const t=s.useDashboardStore(i=>i.dashboard.filters),n=s.useEditorStore(i=>i.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=Ls();function o(i){const d=l(i,"frame");a({...n,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(wr,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function wr({columns:t,onSelect:n}){var c;const[a,r]=Oe.useState(!1),[l,o]=Oe.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const u=d===l?"":d;o(u),r(!1),u&&n(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function Dr({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(Vt,{})})]}),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(Ue,{}),e.jsx(Ke,{})]})]})]})})}function Tr({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Ue,{}),e.jsx(Ke,{})]})]})]})})}function Gt(){const t=s.useEditorStore(i=>i.card.type),n=s.useEditorStore(i=>i.isDevMode),a=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(m=a==null?void 0:a.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function o(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?o():c()})}const kr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Er={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Ir(){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:Ar(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Gt,{}),e.jsx(Ue,{}),e.jsx(Ke,{})]})]})}function Ar(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(kr,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(Er,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(c,i,d){const u=[...t];u[c]={...u[c],[i]:d},n(u)}function l(c){const i=[...t];i.splice(c,1),n(i)}function o(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:o,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(i,"start",d.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:d=>r(i,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(i,"color",d.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function Lr(){var m,h,x,g,b;const t=s.useEditorStore(p=>p.card.preferences),n=s.useEditorStore(p=>p.actions.setCardPreferences),a=s.useEditorStore(p=>p.card),r=s.isExplorerCard(a),l=s.useEditorStore(p=>p.actions.setNumberFormat);s.useEditorStore(p=>{var j,f;return(f=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.decimalPlaces});const o=s.useEditorStore(p=>{var j,f;return(f=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.locale}),c=s.useEditorStore(p=>{var j,f;return(f=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.currency});s.useEditorStore(p=>p.actions.setFilterOnClickField);const i=s.useEditorStore(p=>{var j,f;return(f=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:f.colorRanges})||[],d=s.useEditorStore(p=>p.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(p=>p.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:p=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:p}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:p=>{var j,f,y;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",p,((y=t==null?void 0:t.formatNumber)==null?void 0:y.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(p=>e.jsx(s.SelectItem,{value:p.locale,children:p.locale},p.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:p=>{var j,f,y;console.log("currency",p),l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,p==="none"?"":p,((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((g=(x=t==null?void 0:t.formatNumber)==null?void 0:x.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:p=>{var j,f,y;return l(Number(p),((j=t==null?void 0:t.formatNumber)==null?void 0:j.currency)||"",((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:p=>{var j,f,y;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",((y=t==null?void 0:t.formatNumber)==null?void 0:y.locale)||"",p.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(Mr,{colorRanges:i,setColorRanges:d})]})]})}function Rr(){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(Lr,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function Cs({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 Or=[{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"],Br=Fr.map(t=>({label:t,value:t}));function Pr(){var d,u,m,h,x,g,b,p,j,f,y,I,D,N,S,v,k,C;const t=s.useEditorStore(F=>F.card),n=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=A.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(F=>({label:F,value:F}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(Cs,{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(Cs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(ke,{className:"h-9",options:i,onValueChange:F=>{console.log("value",F),l({...t.preferences,mapVisualOptions:{topoJsonUrl:F}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:F=>{r(F.target.value)},onBlur:()=>{var F;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(F=t.preferences)==null?void 0:F.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(ke,{className:"h-9",options:c,value:((g=(x=t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:F=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,objectKey:F}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(ke,{className:"h-9",options:Or,value:((p=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:p.projection)||"",label:"Projection",onValueChange:F=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projection:F}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(ke,{className:"h-9",options:Br,value:((f=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:f.colorScale)||"",label:"Select Color Scale",onValueChange:F=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,colorScale:F}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Cs,{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:((I=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:I.projectionScale)||1,onChange:F=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionScale:Number(F.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(N=(D=t.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:N.projectionOffset)==null?void 0:S[0])||0,onChange:F=>{var T,B,E,w;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[Number(F.target.value),((w=(E=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:w[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((C=(k=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:C[1])||0,onChange:F=>{var T,B,E,w;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[((w=(E=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:w[0])||0,Number(F.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ue,{})]})}function zr(){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 ns({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(zr,{})})]}),!["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(Ue,{}),e.jsx(Ke,{})]})]})]})})}function Vr(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(ke,{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(Vt,{})]})]}),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(Ue,{}),e.jsx(Ke,{})]})]})]})})}function _r({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Ue,{}),e.jsx(Ke,{})]})]})}),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 Yt({color:t,onColorChange:n,onClose:a}){const[r,l]=A.useState(0),[o,c]=A.useState(100),[i,d]=A.useState(50),[u,m]=A.useState(t);A.useEffect(()=>{const j=Ks(t);if(j){const f=Qs(j.r,j.g,j.b);l(f.h),c(f.s),d(f.l),m(t)}},[t]);const h=j=>{l(j),g(j,o,i)},x=j=>{const f=j.currentTarget.getBoundingClientRect(),y=Math.max(0,Math.min(1,(j.clientX-f.left)/f.width)),I=Math.max(0,Math.min(1,(j.clientY-f.top)/f.height)),D=y*100,N=(1-I)*100;c(D),d(N),g(r,D,N)},g=(j,f,y)=>{const I=Gr(j,f,y),D=Ur(I.r,I.g,I.b);m(D)},b=j=>{if(m(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const f=Ks(j);if(f){const y=Qs(f.r,f.g,f.b);l(y.h),c(y.s),d(y.l)}}},p=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(n(u),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:x,onMouseMove:j=>{j.buttons===1&&x(j)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>h(Number(j.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:u,onChange:j=>b(j.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:p,children:"OK"})]})]})}function Ks(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 Ur(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function Qs(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let o=0,c=0;const i=(r+l)/2;if(r!==l){const d=r-l;switch(c=i>.5?d/(2-r-l):d/(r+l),r){case t:o=((n-a)/d+(n<a?6:0))/6;break;case n:o=((a-t)/d+2)/6;break;case a:o=((t-n)/d+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function Gr(t,n,a){t/=360,n/=100,a/=100;let r,l,o;if(n===0)r=l=o=a;else{const c=(u,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(m-u)*6*h:h<.5?m:h<.6666666666666666?u+(m-u)*(.6666666666666666-h)*6:u),i=a<.5?a*(1+n):a+n-a*n,d=2*a-i;r=c(d,i,t+1/3),l=c(d,i,t),o=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const Yr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function $t(){var I,D,N,S,v,k,C,F,T,B;const t=s.useEditorStore(E=>E.card),n=s.useEditorStore(E=>{var w;return(w=E.card)==null?void 0:w.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=A.useState({}),[i,d]=A.useState(null),[u,m]=A.useState(null),h=A.useMemo(()=>{var L,O,R,P,G,J,V;if(!(l!=null&&l.records)||l.records.length===0)return[];const E=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",w=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",M=((L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns)&&t.config.pivotByColumns.length>0;if((E||w)&&M){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const K=new Set;return l.pivotSchema.forEach($=>{$.alias&&K.add($.alias)}),Array.from(K)}if(l.records.length>0){const K=l.records[0],$=Object.keys(K),X=new Set;(O=t==null?void 0:t.config)!=null&&O.groupByColumns&&t.config.groupByColumns.forEach(_=>{X.add(_.label||_.name),X.add(_.alias||_.name)});const q=new Set;return(R=t==null?void 0:t.config)!=null&&R.metricColumns&&t.config.metricColumns.forEach(_=>{const te=_.alias||_.name;q.add(te),q.add(`${te}_count`),q.add(`${te}_sum`),q.add(`${te}_avg`),q.add(`${te}_min`),q.add(`${te}_max`);const re=_.entityName||_.qualifiedEntityName;re&&(q.add(`${re}_${te}`),q.add(`${re}_${te}_count`))}),$.filter(_=>!X.has(_)&&!q.has(_))}}if((w||E)&&!M&&((G=(P=t==null?void 0:t.config)==null?void 0:P.metricColumns)!=null&&G.length))return t.config.metricColumns.map(K=>K.alias||K.label||K.name);if((V=(J=t==null?void 0:t.config)==null?void 0:J.groupByColumns)!=null&&V.length){const K=t.config.groupByColumns[0],$=K.label||K.name,X=new Set;return l.records.forEach(q=>{const Q=q[$];Q!=null&&X.add(String(Q))}),Array.from(X)}return[]},[l,(I=t==null?void 0:t.config)==null?void 0:I.groupByColumns,(D=t==null?void 0:t.config)==null?void 0:D.pivotByColumns,(N=t==null?void 0:t.config)==null?void 0:N.metricColumns,t==null?void 0:t.type]),x=A.useMemo(()=>s.getDefaultChartColors(),[]);A.useEffect(()=>{const E={};h.forEach((w,M)=>{E[w]=s.getColorForValue(w,M,n==null?void 0:n.colorConfig)}),c(E)},[h,n==null?void 0:n.colorConfig,x]);const g=(E,w)=>{const M={...o,[E]:w};c(M);const L={...n||{},colorConfig:{segments:M}};a(L);const O={...t,preferences:L};r(O)},b=(E,w)=>{var G;const M=x[w%x.length],{[E]:L,...O}=((G=n==null?void 0:n.colorConfig)==null?void 0:G.segments)||{},R={...n||{},colorConfig:{segments:O}};a(R);const P={...t,preferences:R};r(P),c(J=>({...J,[E]:M}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((v=(S=t==null?void 0:t.config)==null?void 0:S.groupByColumns)==null?void 0:v.length)||((C=(k=t==null?void 0:t.config)==null?void 0:k.pivotByColumns)==null?void 0:C.length):(T=(F=t==null?void 0:t.config)==null?void 0:F.groupByColumns)==null?void 0:T.length)||["table","kpi","text","custom"].includes(t.type))return null;const f=()=>{const E={...n||{},colorConfig:{segments:{}}};a(E);const w={...t,preferences:E};r(w);const M={};h.forEach((L,O)=>{M[L]=s.getColorForValue(L,O,void 0)}),c(M)},y=Object.keys(((B=n==null?void 0:n.colorConfig)==null?void 0:B.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:y&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:f,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((E,w)=>{const M=s.isDefaultColor(o[E],w),L=!M;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===E,onOpenChange:O=>d(O?E:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[E]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:x.slice(0,10).map((O,R)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[E]===O?"border-gray-900":"border-transparent"),style:{backgroundColor:O},onClick:()=>{g(E,O),d(null)},children:[R===w%x.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:O})]},`default-${R}`))})]}),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:Yr.map((O,R)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[E]===O?"border-2 border-gray-900":O==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:O},onClick:()=>{g(E,O),d(null)},children:e.jsx("span",{className:"sr-only",children:O})},`preset-${R}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{m({value:E,color:o[E]}),d(null)},children:"Custom color"}),!M&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(E,w),d(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:E}),L&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},E)})}),u&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Yt,{color:u.color,onColorChange:E=>{g(u.value,E),m(null)},onClose:()=>m(null)})})]})]})})]})}function Ae({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[o,c]=A.useState(t??""),[i,d]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const u=()=>{n(o),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?u():h.key==="Escape"&&m()},"aria-label":a||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const $r=["auto","number","currency","percent","scientific","date"],qr=[{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"}],Hr=[{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"}],Wr=t=>t.charAt(0).toUpperCase()+t.slice(1);function Rs({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,d)=>{n({...t,[i]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:$r.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":Wr(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:qr.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Hr.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function Js({axis:t,label:n,type:a,config:r,onChange:l}){var h,x,g,b,p,j,f,y,I,D,N,S;const o=(v,k)=>{l({...r,[v]:k})},c=(v,k)=>{var C,F;l({...r,name:{enabled:v==="enabled"?k:((C=r==null?void 0:r.name)==null?void 0:C.enabled)??!1,text:v==="text"?k:(F=r==null?void 0:r.name)==null?void 0:F.text}})},i=(v,k)=>{var C,F;l({...r,labels:{enabled:v==="enabled"?k:((C=r==null?void 0:r.labels)==null?void 0:C.enabled)??!0,rotation:v==="rotation"?k:(F=r==null?void 0:r.labels)==null?void 0:F.rotation}})},d=(v,k)=>{l({...r,scale:{...r==null?void 0:r.scale,[v]:k===""?"auto":Number(k)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:v=>o("enabled",v),onClick:v=>v.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:v=>c("enabled",v)})]}),((x=r==null?void 0:r.name)==null?void 0:x.enabled)&&e.jsx(Ae,{placeholder:`${n} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:v=>c("text",v),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:v=>o("position",v),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":s.titleCase(v)},v))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((b=r==null?void 0:r.labels)==null?void 0:b.enabled)!==!1,onCheckedChange:v=>i("enabled",v)})]}),((p=r==null?void 0:r.labels)==null?void 0:p.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((j=r==null?void 0:r.labels)==null?void 0:j.rotation)||"auto"),onValueChange:v=>i("rotation",v==="auto"?"auto":Number(v)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":`${v}°`},v))})]})]})]}),a==="value"&&e.jsx(Rs,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:v=>l({...r,formatOptions:v}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ae,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.min)==="auto"||((y=r==null?void 0:r.scale)==null?void 0:y.min)===void 0?"":String(r.scale.min),onSave:v=>d("min",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ae,{type:"number",placeholder:"auto",value:((I=r==null?void 0:r.scale)==null?void 0:I.max)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.max)===void 0?"":String(r.scale.max),onSave:v=>d("max",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ae,{type:"number",placeholder:"auto",value:((N=r==null?void 0:r.scale)==null?void 0:N.stepSize)==="auto"||((S=r==null?void 0:r.scale)==null?void 0:S.stepSize)===void 0?"":String(r.scale.stepSize),onSave:v=>d("stepSize",v),className:""})})]})]})]})]})]})}function qt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const u={...n||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};a(u);const m={...t,preferences:u};r(m)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{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(Js,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(Js,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function Ht(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var m,h,x,g;return(g=(x=(h=(m=u.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:x.plugins)==null?void 0:g.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(u,m)=>{const h={...n,[u]:m};a(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ea,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??o,onCheckedChange:u=>c("display",u)})]}),((n==null?void 0:n.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||r,onValueChange:u=>c("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||l,onValueChange:u=>c("align",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]})]})]})})]})}function Wt(){var k,C,F,T,B,E,w,M,L;const t=s.useEditorStore(O=>O.card),n=s.useEditorStore(O=>{var R,P;return(P=(R=O.card)==null?void 0:R.preferences)==null?void 0:P.dataLabelsConfig}),a=s.useEditorStore(O=>{var R;return(R=O.card)==null?void 0:R.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((k=a==null?void 0:a.chartOptions)==null?void 0:k.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!i,u=(F=(C=a==null?void 0:a.chartOptions)==null?void 0:C.plugins)==null?void 0:F.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),h=(n==null?void 0:n.enabled)!==void 0?n.enabled:m,x=(O,R)=>{const P={...n,[O]:R},G={...t.preferences||{},dataLabelsConfig:P};r(G);const J={...t,preferences:G};l(J)},g=(O,R)=>{const P={...n,font:{...n==null?void 0:n.font,[O]:R}},G={...t.preferences||{},dataLabelsConfig:P};r(G);const J={...t,preferences:G};l(J)},b=(O,R)=>{const P={...n,formatOptions:{...n==null?void 0:n.formatOptions,[O]:R}},G={...t.preferences||{},dataLabelsConfig:P};r(G);const J={...t,preferences:G};l(J)},j=(()=>{const O=t.type;return O==="stackedBar"||O==="stackedLine"||O==="pie"||O==="doughnut"?"center":o?"right":"top"})();let f=[];c||i?f=["center"]:f=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(R=>R!==j),"custom"];const y=()=>s.titleCase(j),I=["center","start","end"],D=["center","start","end","top","bottom"],N=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],S=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],v=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:O=>x("enabled",O)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:O=>x("position",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"?y():O==="custom"?"Custom (Advanced)":s.titleCase(O)},O))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:O=>x("showTotal",O)})]}),(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:O=>x("anchor",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:I.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]}),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:O=>x("align",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:D.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(d?"auto":"none"),onValueChange:O=>x("format",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"&&d?"Auto (Use Axis)":O==="none"?"None (Raw Value)":s.titleCase(O)},O))})]})]}),(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(Ae,{type:"number",placeholder:"0",value:String(((T=n==null?void 0:n.formatOptions)==null?void 0:T.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:O=>b("decimalPlaces",Number(O)),className:""})})]}),n.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((B=n==null?void 0:n.formatOptions)==null?void 0:B.currency)||"USD",onValueChange:O=>b("currency",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:S.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.value))})]})]}),["number","currency"].includes(n.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((E=n==null?void 0:n.formatOptions)==null?void 0:E.useSuffix)??!1,onCheckedChange:O=>b("useSuffix",O)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((w=n==null?void 0:n.formatOptions)==null?void 0:w.locale)||"en-US",onValueChange:O=>b("locale",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.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(Ae,{type:"number",placeholder:"12",value:String(((M=n==null?void 0:n.font)==null?void 0:M.size)||12),onSave:O=>g("size",Number(O)),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:((L=n==null?void 0:n.font)==null?void 0:L.weight)||"normal",onValueChange:O=>g("weight",O),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:O=>{O==="auto"&&x("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ae,{type:"number",placeholder:"0",value:String((n==null?void 0:n.rotation)||0),onSave:O=>x("rotation",Number(O)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Kr(){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($t,{}),e.jsx(qt,{}),e.jsx(Ht,{}),e.jsx(Wt,{})]})]})}const Qr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT 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."]})]}),Jr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT 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."]})]}),Xr=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 Zr(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=o=>r.includes(a)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(Kr,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(Vr,{}));case"tornado":case"pyramid":return l(e.jsx(ns,{docContent:Qr,cardType:a}));case"kpi":return e.jsx(Rr,{});case"line":case"bar":return l(e.jsx(Dr,{cardType:a}));case"range":return l(e.jsx(ns,{docContent:Jr,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(ns,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(Tr,{cardType:a}));case"table":return e.jsx(_r,{cardType:a});case"text":return e.jsx(ns,{docContent:Xr,cardType:a,suffix:"Visual"});case"map":return e.jsx(Pr,{});case"custom":return e.jsx(Nr,{});default:return l(e.jsx(Ir,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Kt({label:t,column:n,functions:a,onFunctionChange:r}){let l=a[0];"aggregate"in n?l=a.find(c=>c.value===n.aggregate)||a[0]:"granularity"in n&&(l=a.find(c=>c.value===n.granularity)||a[0]);function o(c){r(c)}return e.jsx(ke,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:a,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const el=[{label:"Sum",value:"SUM",logo:e.jsx(lt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Me,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(Sa,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(ca,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function sl({column:t}){const{updateMetricColumnOld:n}=s.useEditorActions();let a=el;s.isTextDataType(t.type)&&(a=a.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(a=a.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:es(t.name,l)};n(t.id,o)}return e.jsx(Kt,{column:t,functions:a,onFunctionChange:l=>r(l),label:"Aggregation"})}const tl=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function al({column:t}){const{updateGroupByColumnOld:n}=s.useEditorActions();function a(r){const l={...t,granularity:r,label:We(t.name,r)};n(t.id,l)}return e.jsx(Kt,{column:t,functions:tl,onFunctionChange:r=>a(r),label:"Granularity"})}function nl({col:t,onChange:n,droppableId:a}){const{columns:r}=s.useDataColumns(),l=A.useMemo(()=>{let i=[];(a===Fe||a===Be||a===Pe)&&(i=r);const d=i==null?void 0:i.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,a,t.name]),o=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(u=>{var m;return u.column_name===((m=i[0])==null?void 0:m.id)});d&&n(d)}return l!=null&&l.length?e.jsx(s.ComboBox2,{multiple:!1,options:l,selectedOptions:o,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function Qt({column:t}){const n=s.useEditorStore(d=>d.card.type),a=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(a==null?void 0:a.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Ut,{idx:o,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Gt,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&i()]})}function rl({column:t,type:n,onRemoveColumn:a,droppableId:r}){const[l,o]=A.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:m,setNodeRef:h,transform:x,transition:g,isDragging:b}=s.useSortable({id:t.id,data:{type:n}}),p=x?{opacity:b?.5:void 0,transform:s.CSS.Translate.toString(x),transition:g}:void 0,j=s.isTextDataType(t.type);function f(S){const v=s.isNumberDataType(S.data_type),k=s.isTextDataType(S.data_type),C=s.isDateDataType(S.data_type),F=v?"number":k?"string":C?"date":"string";if(r===Fe){if(k){const T={id:t.id,name:S.column_name,type:F,role:"groupby"};c(t.id,T)}if(C){const T={id:t.id,name:S.column_name,type:F,role:"groupby",label:We(S.column_name,"month"),granularity:"month"};c(t.id,T)}}if(r===Pe){if(k){const T={id:t.id,name:S.column_name,type:F,role:"groupby"};d(t.id,T)}if(C){const T={id:t.id,name:S.column_name,type:F,label:We(S.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,T)}}if(r===Be){const T={id:t.id,name:S.column_name,type:F,role:"metric",label:es(S.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};i(t.id,T)}}function y(){if(r===Be)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(Qt,{column:t})})}function I(){const S=s.isDateDataType(t.type);if(r===Be)return e.jsx(sl,{column:t});if((r===Fe||r===Pe)&&S)return e.jsx(al,{column:t})}function D(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Fe||r===Pe)&&j}),children:e.jsx(nl,{col:t,onChange:f,droppableId:r})})}function N(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>o(!l),children:l?e.jsx(Ya,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(nt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...u,ref:h,style:p,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[N(),I(),D()]}),l&&y()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>a(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function Ss({id:t,label:n,columns:a,previewColumns:r,sortableType:l,onRemoveColumn:o}){var p,j;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),u=s.useDndStore(f=>f.activeId),m=s.useEditorStore(f=>{var y;return(y=f.card)==null?void 0:y.type}),h=i||((j=(p=d==null?void 0:d.data)==null?void 0:p.current)==null?void 0:j.type)===l,x=u?r:a,g=l===ds?"Rows":l===us?"Pivot Columns":"Columns";function b(){if(!x||x.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(f=>f.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:n}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),b(),e.jsx("div",{className:"space-y-2",children:x==null?void 0:x.map(f=>f.id===Tt.id?e.jsx(ll,{},f.id):e.jsx(rl,{droppableId:t,type:l,column:f,onRemoveColumn:o},f.id))})]})})}function ll(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function Jt({children:t,id:n,type:a}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:d}=s.useSortable({id:n,data:{type:a}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...l,...r,ref:o,style:u,children:t})}function ol(){const t=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.orderBy})||[],n=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.groupByColumns})||[],a=s.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...n,...a];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(ua,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(ia,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(da,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(oa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(f=>!t.some(y=>y.columnId===f.id)).map(f=>({id:f.id,value:f.label||f.name}));function x(f,y){const I=g(f);return I?I.role==="metric"?y==="asc"?u:m:y==="asc"?i:d:null}function g(f){return c.find(y=>y.id===f)}function b(f){const y=t.find(I=>I.columnId===f);if(y){const I={...y,direction:y.direction==="asc"?"desc":"asc"};o(I)}}const p=f=>{r({columnId:f.id,direction:"asc"})};function j(f){const y=t.find(I=>I.columnId===f);y&&l(y)}return e.jsx(s.SortableContext,{items:t.map(f=>Je(f.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:f=>p(f[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(f=>{var y,I;return e.jsx(Jt,{id:Je(f.columnId),type:Ms,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(nt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(fs,{className:"w-[175px] text-sm",children:((y=g(f.columnId))==null?void 0:y.label)||((I=g(f.columnId))==null?void 0:I.name)})]}),e.jsx("button",{title:f.direction==="asc"?"Ascending":"Descending",onClick:()=>b(f.columnId),className:"rounded-sm p-0",children:x(f.columnId,f.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>j(f.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},f.columnId)},Je(f.columnId))})]})})}function il(){const t=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.groupByColumns)||[]}),n=s.useEditorStore(j=>j.card.type),a=s.useDndStore(j=>j.previewGroupByColumns),r=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.metricColumns)||[]}),l=s.useDndStore(j=>j.previewMetricColumns),o=s.useEditorStore(j=>{var f;return((f=j.card.queryConfig)==null?void 0:f.pivotColumns)||[]}),c=s.useDndStore(j=>j.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function m(j){i(j)}function h(j){d(j)}function x(j){u(j)}let g="Group By",b="Metrics",p="Stack By";return n==="table"&&(g="Rows",b="Metrics",p="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(Ft,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(Ss,{onRemoveColumn:m,sortableType:ds,id:Fe,label:g,columns:t,previewColumns:a}),e.jsx(Ss,{onRemoveColumn:x,sortableType:us,id:Pe,label:p,columns:o,previewColumns:c}),e.jsx(Ss,{onRemoveColumn:h,sortableType:Ts,id:Be,label:b,columns:r,previewColumns:l}),e.jsx(ol,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Os({children:t,column:n,id:a,sortableType:r,className:l}){const[o,c]=A.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(h=>{var x,g;return(g=(x=h.card.queryConfig)==null?void 0:x.filters)==null?void 0:g.some(b=>b.filterColumnName===n.name)});function m(h){i(h)}return e.jsx(Jt,{id:a,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":o}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:n.name}),u&&e.jsx("button",{onClick:()=>d(n),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>m(n),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!o&&"rounded-b-md",o&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",l),children:t})]})]})})}function cl({column:t,sortableType:n}){const a=s.useDashboardStore(I=>I.themeStyle),r=s.useEditorStore(I=>{var D,N;return(N=(D=I.card)==null?void 0:D.queryConfig)==null?void 0:N.filters}),l=s.useEditorStore(I=>{var D,N;return(N=(D=I.card.queryConfig)==null?void 0:D.filterColumns)==null?void 0:N.find(S=>S.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=A.useMemo(()=>{var I;return(I=r==null?void 0:r.find(D=>D.filterColumnName===t.name))==null?void 0:I.filterValue},[r,t.name]),u=A.useMemo(()=>Array.isArray(d)?d.map(I=>({id:I,value:I})):[],[d]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:x,isLoading:g,isFetching:b,isError:p}=s.useFilterQuery(h),j=A.useMemo(()=>{var D;return h.column?(D=x==null?void 0:x.records)==null?void 0:D.map(N=>{let S=h.column.split(".").slice(-1)[0].replace(/"/g,"");return N[S]===void 0&&(S=S.toLowerCase()),{id:N[S],value:N[S]}}):[]},[x,h.column]);function f(I){const D=I.map(N=>N.id);m(t.name,D)}function y(){return g||b?e.jsx(s.Skeleton,{style:{borderRadius:a==null?void 0:a.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):p?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(dl,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:j,onChange:f,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Os,{className:"w-60",id:t.id,sortableType:n,column:t,children:y()})}function dl({columnName:t}){const{setEditorFilterMode:n}=s.useEditorActions(),a=s.useEditorStore(l=>{var o,c;return(c=(o=l.card.queryConfig)==null?void 0:o.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(a==null?void 0:a.mode)==="exclude"?n(t,"include"):n(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((a==null?void 0:a.mode)==="exclude"?"exclude":"include")})}function ul({open:t,setOpen:n,dateRange:a,setDateRange:r,containerClassName:l,inputClassName:o,title:c,onApply:i,onClear:d}){const u=s.useDashboardStore(m=>m.themeStyle);return e.jsx("div",{className:s.cn("grid gap-2",l),children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{style:{borderRadius:u==null?void 0:u.controlInputRadius},asChild:!0,children:e.jsxs(s.Button,{size:"sm",id:"date",variant:"outline",className:s.cn("h-9 w-full justify-start rounded-sm text-left font-normal",!a&&"text-muted-foreground",o),children:[e.jsx(s.Calendar,{className:"mr-2 h-4 w-4"}),a!=null&&a.from?a.to?e.jsxs(e.Fragment,{children:[s.format(a.from,"LLL dd, y")," -"," ",s.format(a.to,"LLL dd, y")]}):s.format(a.from,"LLL dd, y"):e.jsx("span",{children:"Pick a date"})]})}),e.jsxs(s.PopoverContent,{style:{borderRadius:u==null?void 0:u.controlInputRadius},className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsx(s.Label,{children:c})}),e.jsx(s.Calendar$1,{initialFocus:!0,mode:"range",defaultMonth:a==null?void 0:a.from,selected:a,onSelect:r,numberOfMonths:2}),e.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3",children:[e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:m=>{m.stopPropagation(),i(a),n(!1)},children:"Apply"}),e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:d,children:"Clear"})]})]})]})})}function ml({column:t,sortableType:n}){const[a,r]=A.useState(!1),{selectedConnectionId:l,selectedDatabaseName:o,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:l,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:m,data:h}=s.useFilterQuery(i),x=h==null?void 0:h.records,{dateRange:g,setDateRange:b,initialDateRange:p}=s.useDateRangeFromRecords(x),{updateEditorFilterValue:j}=s.useEditorActions();function f(D){var S,v;const N={gte:(S=D==null?void 0:D.from)==null?void 0:S.toISOString(),lte:(v=D==null?void 0:D.to)==null?void 0:v.toISOString()};j(t.name,N)}function y(){j(t.name,null,!0),b(p)}function I(){return d||u?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):m?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):x?e.jsx(ul,{title:i.title,open:a,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:b,onApply:f,onClear:y}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Os,{className:"w-72",id:t.id,sortableType:n,column:t,children:I()})}function hl({id:t,label:n,columns:a,previewColumns:r,sortableType:l}){var b,p;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(j=>j.activeId),u={},m=c||((p=(b=i==null?void 0:i.data)==null?void 0:b.current)==null?void 0:p.type)===l;function h(){if(!g||g.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function x(j){const f=s.isDateDataType(j.type);return j.id===Tt.id?e.jsx(Os,{id:j.id,sortableType:l,column:j,children:e.jsx(xl,{})},j.id):f?e.jsx(ml,{droppableId:t,sortableType:l,column:j},j.id):e.jsx(cl,{droppableId:t,sortableType:l,column:j},j.id)}const g=d?r:a;return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(j=>j.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",m&&"border border-muted-foreground/20"),ref:o,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:n}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(j=>x(j))})]})})}function xl(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function pl(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),n=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:a}=s.useEditorActions();function r(l){a(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(hl,{onRemoveColumn:r,sortableType:Es,id:ks,label:"Filters",columns:t,previewColumns:n})})}function fl(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.showAIDialog),{setShowAIDialog:a}=s.useEditorActions(),{data:r,errorMessage:l,errorSql:o}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xs,{}),!n&&e.jsxs(s.Button,{onClick:()=>a(!0),variant:"secondary",size:"sm",children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(At,{sql:r==null?void 0:r.sql,error:l,errorSql:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(St,{}),e.jsx(Ct,{variant:"default"})]})]})}function gl(){const t=A.useRef(null),n=A.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);A.useEffect(()=>{var i,d,u,m;r?((i=t.current)==null||i.resize(0),(d=n.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(m=n.current)==null||m.resize(25))},[r]);function o(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(rr,{})}),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(Zr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(as,{})})]}):e.jsx(as,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:a?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:n,defaultSize:25,maxSize:30,children:e.jsx(il,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(fl,{}),e.jsx(pl,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(as,{})})]})})]}):e.jsx(as,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function jl(t){s.useAIInteractionStore(z=>z.currentAIContext);const[n,a]=A.useState(""),[r,l]=A.useState(null),{authToken:o,tokenProps:c}=s.useSemaphorContext(),i=s.useEditorStore(z=>{var Z;return(Z=z==null?void 0:z.card)==null?void 0:Z.sql}),d=s.useEditorStore(z=>z.isDevMode),u=s.useEditorStore(z=>{var Z;return(Z=z==null?void 0:z.card)==null?void 0:Z.python}),{setCardPython:m,setCardSql:h,setRunSql:x,switchCardType:g,setQueryConfig:b}=s.useEditorActions(),p=s.useEditorStore(z=>z.currentAssitantScope)||[],j=s.useEditorStore(z=>z.userInputForAI),f=s.useEditorStore(z=>z.triggerAIRun),y=s.useEditorStore(z=>z.card),I=s.useEditorStore(z=>z.selectedDatabaseName),D=s.useEditorStore(z=>z.selectedTableName),N=s.useEditorStore(z=>z.selectedConnectionId),S=s.useEditorStore(z=>z.selectedSchemaName),v=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:k,refetch:C,data:F}=s.useDashboardCardQuery(y),{setTriggerAIRun:T,setCurrentAssitantScope:B,setCardConfig:E}=s.useEditorActions(),{selectedDatamodelName:w,connectionType:M,selectedDatamodelId:L}=s.useEditorAside(),{messages:O,setMessages:R,regenerate:P,error:G,sendMessage:J,status:V,addToolResult:K,stop:$,clearError:X}=s.useChat({transport:new s.DefaultChatTransport({api:`${c.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const z=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:z.currentAIContext,reasoningEffort:z.reasoningEffort,showReasoning:z.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:z,body:Z})=>({body:{...Z,messages:s.cleanupIncompleteMessages(z)}})}),onError:z=>{var Z;if(z.name==="AbortError"||(Z=z.message)!=null&&Z.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",z)},onToolCall:q,onFinish({isAbort:z,isDisconnect:Z,isError:ae}){a(""),console.log(z?"[Editor Assistant] Stream aborted by user":Z?"[Editor Assistant] Stream disconnected (network error)":ae?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});A.useEffect(()=>{f&&j&&(J({role:"user",parts:[{type:"text",text:j}]}),T(!1))},[f,j,J,T]);async function q({toolCall:z}){var Z,ae,oe,de,ue,xe,W,U,ee,Y,le,se,ie,ce,je,Ee;if(["createChartFromSql","createForecast"].includes(z.toolName)){const be=((Z=z.input)==null?void 0:Z.sql)??((ae=z.args)==null?void 0:ae.sql),Ce=((oe=z.input)==null?void 0:oe.python)??((de=z.args)==null?void 0:de.python),me=((ue=z.input)==null?void 0:ue.chartType)??((xe=z.args)==null?void 0:xe.chartType);g(me),h(be),m(Ce),x(!0),K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(z.toolName==="getUserSql"){if(!i){K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",message:"No SQL found"}});return}K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",sql:i,python:u||""}})}else if(z.toolName==="generateQueryConfig"){a("Generating query config...");const be=((W=z.input)==null?void 0:W.chartType)??((U=z.args)==null?void 0:U.chartType),Ce=((ee=z.input)==null?void 0:ee.queryConfig)??((Y=z.args)==null?void 0:Y.queryConfig);((le=z.input)==null?void 0:le.cardConfig)??((se=z.args)==null||se.cardConfig),g(be),E(Ce),h(void 0),m(void 0);const me=await C();if((ie=me==null?void 0:me.data)!=null&&ie.error){K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",queryConfig:Ce,message:(ce=me==null?void 0:me.data)==null?void 0:ce.error.message}});return}if((je=me==null?void 0:me.data)!=null&&je.records){K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:Ce,message:"The data has been visualized"}});return}K({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:Ce,message:"The data has been visualized",records:(Ee=me==null?void 0:me.data)==null?void 0:Ee.records}})}else a("Analyzing...")}function Q(z){const Z=s.removeFromScopeArray(p,z);_(Z)}function _(z){const Z=s.sanitizeAIScope(z);B(Z),R(ae=>[...ae,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Z)}`}]}])}function te(){const z={databaseName:I||"",schemaName:S||"",tableName:D||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(w),connectionId:N||"",connectionType:M||""},Z=s.dedup([...p,z]);_(Z)}function re(){const z={databaseName:I||"",schemaName:S||"",tableName:D||"",datamodelName:s.resolveDatamodelName(w),connectionId:N||"",connectionType:M||"",datamodelId:L||""};if(!s.isInAiScopeArray([...v||[],...p],z)||p.length===0){const ae=s.dedup([...v||[],...p,z]).filter(oe=>oe.connectionId===z.connectionId);_(ae)}}const he=!["ready","error"].includes(V),ge=s.getErrorMessage(G);return{messages:O,setMessages:R,sendMessage:J,regenerate:P,isLoading:he,handleSetAIScope:re,handleAddCurrentTableToScope:te,removeFromCurrentSelections:Q,currentAssitantScope:p,setCurrentAssitantScope:B,stop:$,status:V,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:ge,clearError:X}}const bl=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Xs({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=A.useRef(null),[l,o]=A.useState(!1),[c,i]=A.useState(s.isDevEnv),[d,u]=A.useState(!1),[m,h]=A.useState(!1),[x,g]=A.useState(!1),b=t??x,p=s.useCurrentAIContext(),{setCurrentAIContext:j}=s.useAIActions(),{clearQueue:f}=s.useQueueActions(),{clearFileAttachments:y}=s.useFileActions(),I=s.useFileAttachments("editor"),D=s.useDashboardStore(ne=>ne.dashboard.aiContext),N=s.useEditorStore(ne=>ne.card.dataSource),S=s.useEditorStore(ne=>ne.actions.setCardSql),v=s.useEditorStore(ne=>ne.actions.setRunSql),k=s.useEditorStore(ne=>ne.showAIDialog),C=s.useDashboardStore(ne=>ne.handleOpenAssistantProfile),{setShowAIDialog:F,setCardPython:T}=s.useEditorActions(),{setDataSource:B}=s.useEditorActions(),{assistantProfile:E}=s.useAssistantProfile(),{messages:w,setMessages:M,sendMessage:L,isLoading:O,stop:R,status:P,llmUsage:G,errorMessage:J,clearError:V}=jl(),[K,$]=A.useState(""),X=ne=>{$(ne.target.value)},q=ne=>{ne.preventDefault();const ve=K.trim();if(!ve&&I.length===0)return;const Qe=[];ve&&Qe.push({type:"text",text:ve}),I.forEach(Re=>{Re.data&&Qe.push({type:"file",mediaType:Re.type,filename:Re.name,url:`data:${Re.type};base64,${Re.data}`})}),L({role:"user",parts:Qe}),$(""),y("editor"),oe({force:!0})},{visibleMessages:Q,hasMoreMessages:_,totalMessageCount:te,loadMoreMessages:re,resetMessageWindow:he}=s.useMessageWindow(w,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ge,isAtBottom:z,hasNewMessages:Z,newMessageCount:ae,scrollToBottom:oe,handleScroll:de,resetNewMessageCount:ue}=s.useAutoScroll(Q,{threshold:50,delay:0,dependencies:[P,w.length]});A.useEffect(()=>{var ne;k&&((ne=r.current)==null||ne.focus(),j({selectedEntities:(N==null?void 0:N.selectedEntities)||[]}))},[k,N,j]),s.useAutoSubmitQueue({assistantType:"editor",status:P,isLoading:O,sendMessage:L});const{hasActiveTools:xe}=s.useActiveToolStatus(w),W=A.useCallback(ne=>{n==null||n(ne),t===void 0&&g(ne)},[t,n]);A.useEffect(()=>{if(!b)return;function ne(ve){ve.key==="Escape"&&W(!1)}return window.addEventListener("keydown",ne),()=>{window.removeEventListener("keydown",ne)}},[b,W]);const U=A.useCallback(ne=>{L({role:"user",parts:[{type:"text",text:ne}]}),oe({force:!0})},[L,oe]),ee=A.useCallback(async()=>{const ne=JSON.stringify(w??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ne),s.ue.success("Conversation copied")}catch(ve){console.error("Failed to copy conversation",ve),s.ue.error("Unable to copy conversation")}},[w]),Y=A.useCallback(()=>{W(!b)},[b,W]);function le(ne,ve){ve==="sql"?(S(ne),v(!0)):ve==="python"&&(T(ne),v(!0))}function se(){var ne;(ne=D==null?void 0:D.selectedEntities)==null||ne[0],h(!0)}function ie(){p.selectedEntities.length===0&&j({selectedEntities:(D==null?void 0:D.selectedEntities)||[]})}function ce(ne){ie();const ve={role:"user",parts:[{type:"text",text:ne.title+" "+ne.subtitle}]};L(ve)}function je(ne){ie(),L({role:"user",parts:[{type:"text",text:ne}]})}function Ee(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:o,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:u,children:"System Message"})]})]})}function be(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Ce=(K==null?void 0:K.length)===0&&(w==null?void 0:w.filter(ne=>ne.role==="user").length)===0,me=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:[be(),C&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:C,children:(E==null?void 0:E.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Ee(),c&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground/70 hover:text-foreground",onClick:ee,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:b?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:Y,children:b?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:se,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:"New Chat",onClick:()=>{M([]),f("editor"),V(),he()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",onClick:()=>{F(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:ge,className:"mt-2 flex w-full grow basis-0",onScroll:de,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[_&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:re,className:"text-xs",children:["Load ",Math.min(5,te-Q.length)," ","more messages (",te-Q.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:Q,showTools:c,handleRun:le,showSystemMessage:d,onQuickReply:U,disableQuickReplies:O}),!xe&&e.jsx(s.AssistantStatus,{status:P,errorMessage:J})]})}),!z&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{oe({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"}),Z&&ae>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:ae>9?"9+":ae})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Ce&&!E&&e.jsx(s.Placeholders,{onClick:ce,placeholders:bl}),e.jsx("div",{children:Ce&&E&&e.jsx(s.SeedQuestions,{seedQuestions:E.seedQuestions||[],handleSeedQuestionClick:je})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:$,stop:R,input:K,handleInputChange:X,handleSubmit:ne=>{ie(),q(ne),oe({force:!0})},isLoading:O,status:P,assistantType:"editor",onFocus:()=>{}})]}),G&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",G.inputTokens," prompt tokens, ",G.outputTokens," ","completion tokens, ",G.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(N==null?void 0:N.selectedEntities)||[],open:m,onOpenChange:h,dataSource:N||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return b&&a?ra.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:me})}),a):me}const Fs=t=>{var T;const{updateCardConfig:n,updateGroupByColumn:a,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(B=>B.card.type),h=t==null?void 0:t.id,x=A.useCallback(B=>{if(!(t!=null&&t.config))return[];switch(B){case"groupBy":return(t.config.groupByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType,dateFormat:E.dateFormat,customFormat:E.customFormat,granularity:E.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType,direction:E.direction}));case"source":return[];default:return[]}},[t]),g=A.useCallback((B,E)=>{if(h)switch(B){case"groupBy":{n(h,{groupByColumns:E});break}case"metrics":{n(h,{metricColumns:E});break}case"pivotBy":{n(h,{pivotByColumns:E});break}case"sortBy":{n(h,{sortByColumns:E});break}}},[h,n]),b=A.useCallback((B,E,w)=>{if(!h)return;const L=x(B)[E];if(L)switch(B){case"groupBy":a(h,L.id,{label:w});break;case"metrics":r(h,L.id,{label:w});break;case"pivotBy":l(h,L.id,{label:w});break;case"sortBy":o(h,L.id,{label:w});break}},[h,x,a,r,l,o]),p=A.useCallback((B,E)=>{if(!h)return;const M=x("metrics")[B];M&&r(h,M.id,{aggregate:E,label:s.getAggregationLabel(M.name,E)})},[h,x,r]),j=A.useCallback((B,E,w)=>{if(!h)return;const L=x("groupBy")[B];if(!L)return;const O={dateFormat:E};E==="custom"&&w?O.customFormat=w:O.customFormat=void 0,a(h,L.id,O)},[h,x,a]),f=A.useCallback((B,E)=>{if(!h)return;const M=x("groupBy")[B];M&&a(h,M.id,{granularity:E})},[h,x,a]),y=A.useCallback((B,E)=>{if(!h)return;const M=x("metrics")[B];M&&r(h,M.id,{aliasTemplate:E})},[h,x,r]),I=A.useCallback((B,E)=>{if(console.log("handleValueAliasesChange",B,E),!h)return;console.log("handleValueAliasesChange",B,E);const M=x("metrics")[B];M&&(console.log("handleValueAliasesChange",E),r(h,M.id,{valueAliases:E}))},[h,x,r]),D=A.useCallback(B=>{h&&n(h,{comparisonType:B})},[h,n]),N=A.useCallback(B=>{h&&n(h,{showTrendline:B})},[h,n]),S=A.useCallback(B=>{h&&n(h,{trendlineWindow:B})},[h,n]),v=A.useCallback(B=>{h&&n(h,{trendlineGranularity:B})},[h,n]),k=A.useCallback(B=>{h&&n(h,{targetValue:B})},[h,n]),C=A.useCallback(B=>{var P;if(!h)return;const E=[...x("groupBy"),...x("pivotBy"),...x("metrics"),...x("sortBy")],w=(P=t==null?void 0:t.config)==null?void 0:P.joinPlan,M=s.validateEntityConsistency(B,E,w);if(!M.isValid){M.showError&&s.showJoinRequiredNotification();return}const L=s.getSmartContainerForField(B,E),O=x(L);if(s.fieldAlreadyExists(B,O))return;const R=s.getNewField(B,L,O);R&&g(L,[...O,R])},[h,(T=t==null?void 0:t.config)==null?void 0:T.joinPlan,x,g]),F=A.useCallback((B,E)=>{if(!h)return;const M=x(B)[E];if(M){if(B!=="sortBy"){const L=x("sortBy"),O=L.filter(R=>!(R.name===M.name&&R.qualifiedEntityName===M.qualifiedEntityName));O.length!==L.length&&n(h,{sortByColumns:O})}switch(B){case"groupBy":c(h,M.id);break;case"metrics":i(h,M.id);break;case"pivotBy":d(h,M.id);break;case"sortBy":u(h,M.id);break}}},[h,x,c,i,d,u,n]);return{getFieldsForContainer:x,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:p,handleDateFormatChange:j,handleGranularityChange:f,handleAliasTemplateChange:y,handleValueAliasesChange:I,removeField:F,handleFieldClick:C,handleKpiComparisonTypeChange:D,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:S,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:k,cardType:m}};function vl({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function yl({field:t}){const{attributes:n,listeners:a,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,d]=A.useState(!1),u=s.useEditorStore(b=>b.card),{handleFieldClick:m}=Fs(u),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const x=b=>{const p=(b||"").toLowerCase();switch(s.getDataType(p)){case"number":return Me;case"date":return s.Calendar;case"boolean":return ze;case"json":return $e;case"geo":return Xe;default:return we}},g=b=>{const p=(b||"").toLowerCase(),j=s.getDataType(p);return j==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(we,{className:"h-3 w-3"})}):j==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Me,{className:"h-3 w-3"})}):j==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):j==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ze,{className:"h-3 w-3"})}):j==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx($e,{className:"h-3 w-3"})}):j==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Xe,{className:"h-3 w-3"})}):j==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ss,{className:"h-3 w-3"})}):null};return x(t.dataType),e.jsxs("div",{ref:r,style:h,...n,...a,className:`group/container max-w-[265px] overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>m(t),children:[g(t.dataType),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(vl,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{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(Wa,{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 Nl(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useEditorStore(I=>I.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),u=o.filter(I=>I.name.toLowerCase().includes(t.toLowerCase())||I.dataType.toLowerCase().includes(t.toLowerCase())||I.qualifiedEntityName&&I.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=I=>{if(I.dataType==="number"||I.dataType==="integer"||I.dataType==="float"||I.dataType==="decimal"||I.dataType==="currency")return"metrics";const D=s.getDataType(I.dataType);return["date","string","boolean"].includes(D)?"dimensions":D==="number"?"metrics":"dimensions"},x=(a==="all"?u:u.filter(I=>m(I)===a)).reduce((I,D)=>{const N=D.qualifiedEntityName||"Other Fields";return I[N]||(I[N]={label:s.toLabel(D.entityName),fields:[]}),I[N].fields.push(D),I},{}),b=Object.keys(x),p=u.filter(I=>m(I)==="dimensions").length,j=u.filter(I=>m(I)==="metrics").length,f=u.filter(I=>m(I)==="calculated").length,y=u.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[o.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:t,onChange:I=>n(I.target.value)}),t&&e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:e.jsx(s.X,{className:"size-3.5"})})]}),y&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:I=>r(I),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:u.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(ss,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:b,className:"space-y-2",children:Object.entries(x).map(([I,D])=>{const N=c.find(S=>S.entityName===I)||{entityName:I,label:D.label};return e.jsxs(s.AccordionItem,{value:I,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{title:N.label||N.entityName,className:"flex items-center gap-2",children:[e.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:N.label||N.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:D.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:D.fields.map(S=>e.jsx(yl,{field:S},S.id))})})]},I)})}),Object.keys(x).length===0&&o.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(x).length===0&&o.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function Cl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(Nl,{})," "]})}function Sl({initialJoinPlan:t,availableDataSources:n}){const[a,r]=A.useState(t),[l,o]=A.useState(new Set),c=()=>{const S=a.joins.length>0?Math.max(...a.joins.map(k=>k.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:S,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,v]}),o(new Set([...l,v.id]))},i=S=>{r({...a,joins:a.joins.filter(v=>v.id!==S)}),o(new Set([...l].filter(v=>v!==S)))},d=(S,v)=>{var T,B;const k=a.joins.find(E=>E.id===S);if(!k)return;const C={...k,...v},F=a.joins.map(E=>E.id===S?C:E);if((T=C.source)!=null&&T.name&&((B=C.target)!=null&&B.name)&&C.joinKeyGroups[0].keys.length===0){const E=n.find(O=>{var R;return O.name===((R=C.source)==null?void 0:R.name)}),w=n.find(O=>{var R;return O.name===((R=C.target)==null?void 0:R.name)}),M={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(E==null?void 0:E.name)||"",entityName:(E==null?void 0:E.name)||"",entityType:(E==null?void 0:E.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},operator:"="},L=[...C.joinKeyGroups];L[0]={...L[0],keys:[M]},C.joinKeyGroups=L,F[F.findIndex(O=>O.id===S)]=C}r({...a,joins:F})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:S=>{const v=a.joins.findIndex(k=>k.id===S);if(v>0){const k=[...a.joins],C={...k[v]},F={...k[v-1]};k[v]=F,k[v-1]=C,k.forEach((B,E)=>{B.sequence=E+1});const T={...a,joins:k};r(T)}},moveJoinDown:S=>{const v=a.joins.findIndex(k=>k.id===S);if(v<a.joins.length-1){const k=[...a.joins],C={...k[v]},F={...k[v+1]};k[v]=F,k[v+1]=C,k.forEach((B,E)=>{B.sequence=E+1});const T={...a,joins:k};r(T)}},toggleJoinExpansion:S=>{const v=new Set(l);v.has(S)?v.delete(S):v.add(S),o(v)},getAvailableSourceEntities:S=>{if(a.joins.length===0)return n;const v=a.joins.findIndex(C=>C.id===S);if(v===0)return n;const k=new Set;return a.baseEntity.name&&k.add(a.baseEntity.name),a.joins.slice(0,v).forEach(C=>{k.add(C.source.name),k.add(C.target.name)}),n.filter(C=>k.has(C.name))},getAvailableTargetEntities:S=>n.filter(v=>v.name!==S),addJoinKeyGroup:S=>{const v=a.joins.find(C=>C.id===S);if(!v)return;const k=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(S,{joinKeyGroups:k})},updateGroupOperator:(S,v,k)=>{const C=a.joins.find(T=>T.id===S);if(!C)return;const F=[...C.joinKeyGroups];F[v]={...F[v],operator:k},d(S,{joinKeyGroups:F})},removeJoinKeyGroup:(S,v)=>{const k=a.joins.find(F=>F.id===S);if(!k)return;const C=[...k.joinKeyGroups];C.splice(v,1),d(S,{joinKeyGroups:C})},addJoinKey:(S,v)=>{const k=a.joins.find(E=>E.id===S);if(!k)return;const C=n.find(E=>E.name===k.source.name),F=n.find(E=>E.name===k.target.name),T=[...k.joinKeyGroups],B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(C==null?void 0:C.name)||"",entityName:(C==null?void 0:C.name)||"",entityType:(C==null?void 0:C.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(F==null?void 0:F.name)||"",entityName:(F==null?void 0:F.name)||"",entityType:(F==null?void 0:F.type)||"table"},operator:"="};T[v]={...T[v],keys:[...T[v].keys,B]},d(S,{joinKeyGroups:T})},updateJoinKey:(S,v,k,C,F)=>{const T=a.joins.find(L=>L.id===S);if(!T)return;const B=n.find(L=>L.name===T.source.name),E=n.find(L=>L.name===T.target.name),w=[...T.joinKeyGroups],M=w[v].keys[k];C==="sourceColumnName"&&B?w[v].keys[k]={...M,source:{...M.source,name:F}}:C==="targetColumnName"&&E?w[v].keys[k]={...M,target:{...M.target,name:F}}:C==="operator"&&(w[v].keys[k]={...M,operator:F}),d(S,{joinKeyGroups:w})},removeJoinKey:(S,v,k)=>{const C=a.joins.find(T=>T.id===S);if(!C)return;const F=[...C.joinKeyGroups];F[v].keys.splice(k,1),d(S,{joinKeyGroups:F})},generateSQLPreview:()=>{const S=[...a.joins].sort((C,F)=>C.sequence-F.sequence),v=a.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let k=`SELECT *
329
+ FROM ${v.name}`;return S.forEach(C=>{const F=n.find(E=>E.name===C.target.name);if(!F)return;const T=C.joinKeyGroups.filter(E=>E.keys&&E.keys.length>0).map(E=>{const w=E.keys.filter(M=>{var L,O,R,P;return((L=M.source)==null?void 0:L.name)&&((O=M.target)==null?void 0:O.name)&&((R=M.source)==null?void 0:R.entityName)&&((P=M.target)==null?void 0:P.entityName)}).map(M=>`${M.source.entityName}.${M.source.name} ${M.operator} ${M.target.entityName}.${M.target.name}`);return w.length>1?`(${w.join(` ${E.operator} `)})`:w[0]}).filter(Boolean),B=T.length>1?T.join(" OR "):T[0]||"condition_here";k+=`
330
+ ${C.joinType} JOIN ${F.name}
331
+ ON ${B}`}),k},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(C=>!C.source.name||!C.target.name)||a.joins.some(C=>C.joinKeyGroups.some(F=>F.keys.length===0))||a.joins.some(C=>C.joinKeyGroups.some(F=>F.keys.some(T=>!T.source.name||!T.target.name||!T.operator))))}}function wl({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(T=>T.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:x,moveJoinUp:g,moveJoinDown:b,toggleJoinExpansion:p,getAvailableSourceEntities:j,getAvailableTargetEntities:f,addJoinKeyGroup:y,updateGroupOperator:I,removeJoinKeyGroup:D,addJoinKey:N,updateJoinKey:S,removeJoinKey:v,generateSQLPreview:k,isValidConfiguration:C}=Sl({initialJoinPlan:t,availableDataSources:n}),F=T=>{const B=c.find(E=>E.entityName===T);return(B==null?void 0:B.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:T=>{const B=n.find(E=>E.name===T);u({...i,baseEntity:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:T,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(T=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:T.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:T.type}),T.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},T.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:k()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(T=>{const B=n.find(M=>M.name===T.source.name),E=n.find(M=>M.name===T.target.name),w=d.has(T.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:T.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",T.sequence,B&&E&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",B.name," → ",E.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(T.id),disabled:T.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(T.id),disabled:T.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(T.id),children:w?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(T.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),w&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:T.source.name,onValueChange:M=>{const L=n.find(O=>O.name===M);x(T.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:M,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:j(T.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:T.joinType,onValueChange:M=>x(T.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:T.target.name,onValueChange:M=>{const L=n.find(O=>O.name===M);x(T.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:M,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},disabled:!T.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:T.source.name?f(T.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===T.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},M.name)):[]})]})]})]}),T.source.name&&T.target.name&&B&&E&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>y(T.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),T.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:T.joinKeyGroups.map((M,L)=>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 ",L+1]}),L>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:O=>I(T.id,L,O),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:()=>D(T.id,L),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((O,R)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[R>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:O.source.name,onValueChange:P=>S(T.id,L,R,"sourceColumnName",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:F(T.source.name).map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:P.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:O.operator,onValueChange:P=>S(T.id,L,R,"operator",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:O.target.name,onValueChange:P=>S(T.id,L,R,"targetColumnName",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:F(T.target.name).map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:P.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>v(T.id,L,R),children:e.jsx(s.X,{className:"size-3.5"})})]},O.id||R))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>N(T.id,L),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},M.id))})]})]})]},T.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(i),disabled:!C(),children:"Save"})]})]})}function Zs({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(wl,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function Dl({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=a.find(c=>c.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=a.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=a.find(d=>d.name===l.source.name),i=a.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function Tl(){var m,h;const t=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>x.actions.updateCardConfig),a=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=A.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=x=>{n(t.id,{...t==null?void 0:t.config,joinPlan:x}),l(!1)},i=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},u=()=>{const x=[...a.joins].sort((p,j)=>p.sequence-j.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let b=`SELECT *
332
+ FROM ${g.name}`;return x.forEach(p=>{const j=o.find(I=>I.name===p.target.name);if(!j)return;const f=p.joinKeyGroups.filter(I=>I.keys&&I.keys.length>0).map(I=>{const D=I.keys.filter(N=>{var S,v,k,C;return((S=N.source)==null?void 0:S.name)&&((v=N.target)==null?void 0:v.name)&&((k=N.source)==null?void 0:k.entityName)&&((C=N.target)==null?void 0:C.entityName)}).map(N=>`${N.source.entityName}.${N.source.name} ${N.operator} ${N.target.entityName}.${N.target.name}`);return D.length>1?`(${D.join(` ${I.operator} `)})`:D[0]}).filter(Boolean),y=f.length>1?f.join(" OR "):f[0]||"condition_here";b+=`
333
333
  ${p.joinType} JOIN ${j.name}
334
- ON ${y}`}),b};return o.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[a.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>l(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":a.joins.length>0,"text-gray-500":a.joins.length===0})}),"Join",a.joins.length>1?"s":""," (",a.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(Dl,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:o,generateSQLPreview:u})})]})}),e.jsx(Zs,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(Zs,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function kl({open:t,onOpenChange:n}){const[a,r]=A.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(p=>p.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];A.useEffect(()=>{t&&r([])},[t]);const i=p=>{r(j=>j.some(y=>y.name===p.name&&y.type===p.type)?j.filter(y=>!(y.name===p.name&&y.type===p.type)):[...j,p])},d=()=>{r([...c])},u=()=>{r([])},m=()=>{if(a.length===0)return;const p=a[0],j=p.connectionId||"",f=p.connectionType||"",E=a.some(C=>C.type==="dataset")?"semanticDomain":"database";l({connectionId:j,connectionType:f,mode:E,selectedEntities:a}),n(!1)},h=p=>{switch(p.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Ka,{className:"h-4 w-4"});case"model":return e.jsx(va,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},x=p=>"label"in p&&p.label?p.label:p.name,g=p=>{if("description"in p&&p.description)return p.description;const j=[];return p.database&&j.push(p.database),p.schema&&j.push(p.schema),p.name&&j.push(p.name),j.join(".")},b=p=>a.some(j=>j.name===p.name&&j.type===p.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:a.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((p,j)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",b(p)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:b(p),onCheckedChange:()=>i(p)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(p)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:x(p)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(p)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p.type})]},`${p.type}-${p.name}-${j}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function El({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function Il({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((n,a)=>{const r=s.getEntityDetails(n),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function Al({isVisible:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(!1),[o,c]=A.useState(!0),i=s.useEditorStore(h=>h.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:d}=s.useEditorActions(),u={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},m={...u,...i,selectedEntities:(i==null?void 0:i.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:"p-4 px-6 pb-2",children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>a(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Add Data"]})}),e.jsxs("div",{className:"relative px-6",children:[e.jsx("div",{className:"absolute inset-0 flex items-center px-6",children:e.jsx("div",{className:"w-full border-t border-border"})}),e.jsx("div",{className:"relative flex justify-center",children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>c(!o),className:"size-6 bg-background p-1 py-1 hover:bg-accent",children:o?e.jsx(s.ChevronUp,{className:"h-3.5 w-3.5"}):e.jsx(s.ChevronDown,{className:"h-3.5 w-3.5"})})})]}),e.jsxs("div",{className:`overflow-hidden px-6 ${o?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[m.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[m.selectedEntities.slice(0,3).map((h,x)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(h),e.jsx("button",{onClick:g=>{g.stopPropagation();const b=m.selectedEntities.filter(p=>!(p.name===h.name&&p.type===h.type));d({...u,...i,selectedEntities:b})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(El,{entity:h})]},`${h.type}-${h.name}-${x}`)),m.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",m.selectedEntities.length-3," more"]})}),e.jsx(Il,{entities:m.selectedEntities.slice(3)})]})]})}),e.jsx(Tl,{})]})]}),e.jsx(Cl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(i==null?void 0:i.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:a,dataSource:m,fallbackDataSource:u}),e.jsx(kl,{open:r,onOpenChange:l})]})}function Bs(t,n){const[a,r]=A.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):n});return A.useEffect(()=>{localStorage.setItem(t,JSON.stringify(a))},[a,t]),[a,r]}const Ml="chart-selector-standard-first";function Ll(){const[t,n]=Bs(Ml,!0);return{standardFirst:t,updatePreference:n}}const et=({pluginVisual:t,index:n,onSelect:a})=>{const r=ps(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},st=["default","standardPlugin","customPlugin"];function Rl({selectedChart:t,onChartChange:n}){var D;const[a,r]=A.useState(!1),{data:l}=Ot();Ll();const c=((D=s.useEditorStore(C=>C.card).customCardPreferences)==null?void 0:D.url)||"";As(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(C=>C.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:x}=s.useEditorActions(),[g,b]=Bs("chart-section-active",null),p=A.useMemo(()=>g?[g,...st.filter(C=>C!==g)]:st,[g]);function j(C){m(null),d({}),i(C),["custom","map"].includes(C)&&(u(!0),x(void 0)),n(C),r(!1)}function f(C){m(null),d({}),i("custom"),h({type:"component",visualType:"single",url:C.url,componentName:C.name,icon:C.icon,pluginChartType:C.chartType}),x(void 0),n("custom"),r(!1)}const y=()=>{var S;if(t==="custom"){const v=s.useEditorStore.getState().card;return((S=v==null?void 0:v.customCardPreferences)==null?void 0:S.componentName)||"Custom Visual"}const C=s.chartTypes.find(v=>v.id===t);return(C==null?void 0:C.label)||"Select chart type"},E=()=>{var S,v;if(t==="custom"){const k=s.useEditorStore.getState().card,N=(S=k==null?void 0:k.customCardPreferences)==null?void 0:S.icon,F=(v=k==null?void 0:k.customCardPreferences)==null?void 0:v.componentName;if(N&&F)return e.jsx(Ol,{icon:N,componentName:F});if(F){const T=s.getAutoDetectedChartIcon(F);if(T)return T}return e.jsx(Ze,{className:"h-4 w-4"})}const C=s.chartTypes.find(k=>k.id===t);if(C){const k=C.icon;return e.jsx(k,{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:[E(),e.jsx("span",{children:y()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),p.map(C=>{if(C==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="default",onCheckedChange:S=>b(S?"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(S=>{const v=S.icon;return e.jsx(s.CommandItem,{value:`${S.label} ${S.id} chart graph visualization`,onSelect:()=>j(S.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{className:"h-4 w-4"}),e.jsx("span",{children:S.label})]})},S.id)})},"default");if(C==="standardPlugin"){const S=l.filter(v=>v.pluginType==="standard");return S.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="standardPlugin",onCheckedChange:v=>b(v?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:S.filter(v=>v.componentType==="chart").map((v,k)=>e.jsx(et,{pluginVisual:v,index:k,onSelect:()=>f(v)},`${v.url}-${v.name}-${k}`))},"standardPlugin"):null}if(C==="customPlugin"){const S=l.filter(v=>v.pluginType==="custom");return S.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="customPlugin",onCheckedChange:v=>b(v?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:S.map((v,k)=>e.jsx(et,{pluginVisual:v,index:k,onSelect:()=>f(v)},`${v.url}-${v.name}-${k}`))},"customPlugin"):null}return null})]})]})})]})})}const Ol=({icon:t,componentName:n})=>{const a=ps(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(Ze,{className:"h-4 w-4"})},Fl=[{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 Bl({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(o=>o.card),r=((l=a==null?void 0:a.config)==null?void 0:l.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center justify-center gap-1",children:Fl.map(o=>{if(o.requiresPivot&&!r)return null;const c=o.icon,i=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(o.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o.label})})]},o.id)})})}const 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(Se,{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(Ie,{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(Pe,{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(Se,{className:"h-3 w-3"})})};function Pl({aliasTemplate:t,onAliasTemplateChange:n}){var d;const[a,r]=A.useState(t),[l,o]=A.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?a:t,onChange:u=>{r(u.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&a!==t?(n(a),o(!1)):u.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function zl({valueAliases:t,onValueAliasesChange:n}){const[a,r]=A.useState(null),[l,o]=A.useState(""),[c,i]=A.useState(""),d=()=>{n({...t,"":""})},u=h=>{const x={...t};delete x[h],n(x)},m=h=>{const x={...t};delete x[h],x[l]=c,n(x),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,x],g)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:b=>i(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(x)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(x)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+g)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Vl({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),o=s.useEditorStore(u=>u.card),c=o==null?void 0:o.dataSource,i=["attribute-values",t.entityName,t.name,n,a],d=s.useQuery({queryKey:i,queryFn:async()=>{if(!(c!=null&&c.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},m={connection_id:c.connectionId,cardConfig:u,cardDataSource:c,cache_config:s.getCacheConfig({card:o})};console.log("requestBody",m);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const x=t.name;return((h==null?void 0:h.records)||[]).map(b=>{const p=b[x]||b[t.alias||x]||b[t.label];return{id:p||"",value:p||"",label:String(p||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(c!=null&&c.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:d.data||[],isLoading:d.isLoading,isFetching:d.isFetching,isError:d.isError,error:d.error,refetch:d.refetch}}function _l({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:o}){var E,D;const c=!!l,[i,d]=A.useState(c?"values":"fields"),[u,m]=A.useState(""),[h,x]=A.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),g=a.filter(C=>{var v;return c?!1:!((v=r==null?void 0:r.conditions)==null?void 0:v.some(k=>k.field.id===C.id))&&C.label.toLowerCase().includes(u.toLowerCase())}),b=C=>{x({...h,field:C}),d("values")},p=()=>{if(h.field&&h.selectedValues.length>0){const C={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let S;if(c){const v=((r==null?void 0:r.conditions)||[]).map(k=>k.id===l.id?C:k);S={...r,conditions:v}}else{const v=(r==null?void 0:r.conditions)||[];S={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...v,C],groups:[]}}o(S),n(!1)}},j=()=>{if(!c||!l)return;const C=((r==null?void 0:r.conditions)||[]).filter(S=>S.id!==l.id);if(C.length>0){const S={...r,conditions:C};o(S)}else o(void 0);n(!1)},f=C=>{x({...h,selectedValues:C})},y=()=>{c&&l?(x({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(x({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return A.useEffect(()=>{t&&y()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(E=h.field)==null?void 0:E.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(D=h.field)==null?void 0:D.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(C=>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:[C.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(C.value)?`${C.value.length} values`:String(C.value)})]},C.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:u,onChange:C=>m(C.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(C=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(C),children:[e.jsx(Ps,{dataType:s.getDataType(C.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:C.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[C.entityName,".",C.name]})]})]},C.id))}),g.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),g.length===0&&!u&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Ul,{field:h.field,selectedValues:h.selectedValues,onValuesChange:f,onBack:c?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:j,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:y,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:p,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Ul({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,o]=A.useState(""),{values:c,isLoading:i,isFetching:d}=Vl({field:t,searchQuery:l,limit:500}),u=l?c.filter(x=>String(x.value).toLowerCase().includes(l.toLowerCase())):c,m=x=>{const g=n.includes(x);a(g?n.filter(b=>b!==x):[...n,x])},h=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(x=>x.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:x=>o(x.target.value),className:"pl-10"})]}),i||d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(x=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(x.value),children:[e.jsx(s.Checkbox,{checked:n.includes(x.value),onCheckedChange:()=>m(x.value)}),e.jsx(fs,{className:"text-sm",children:x.label})]},x.id))})]})]})}function Gl({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Vs,_s,Us;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:x}=s.useSortable({id:t.id}),g=s.useEditorStore(q=>q.card),{updateLabel:b,handleAggregationChange:p,handleDateFormatChange:j,handleGranularityChange:f,handleAliasTemplateChange:y,handleValueAliasesChange:E,removeField:D,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:N}=Fs(g),[F,T]=A.useState(!1),[B,I]=A.useState(!1),[w,M]=A.useState(null),[L,O]=A.useState(t.dateFormat||"YYYY-MM-DD"),[R,z]=A.useState(t.customFormat||""),[G,Q]=A.useState(!!t.customFormat),[_,W]=A.useState(t.granularity||"day"),[$,X]=A.useState(t.aliasTemplate||""),[Y,K]=A.useState(t.valueAliases||{}),[U,ee]=A.useState((Vs=t.parameters)==null?void 0:Vs.filters),ne=q=>{q==="custom"?Q(!0):(Q(!1),O(q),n==="groupBy"&&j(a,q,""))},he=q=>{z(q),n==="groupBy"&&j(a,"custom",q)},ge=q=>{var ve;W(q);const fe=(ve=J(q)[0])==null?void 0:ve.value;fe&&!G&&(O(fe),n==="groupBy"&&j(a,fe,"")),n==="groupBy"&&f(a,q)},V=q=>{X(q),n==="metrics"&&y(a,q)},Z=q=>{K(q),n==="metrics"&&E(a,q)},te=q=>{b(n,a,q)},re=q=>{var pe;if(ee(q),n==="metrics"){const fe={...t,parameters:{...t.parameters,filters:q}},ve=[...((pe=g.config)==null?void 0:pe.metricColumns)||[]];ve[a]=fe,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:ve})}I(!1)},ie=()=>{D(n,a)},de={transform:s.CSS.Transform.toString(m),transition:h},xe=s.getDataType(t.dataType),H=xe==="date",P=c==="kpi",J=q=>{switch(q){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..."}]}},se=J(_),oe=n!=="pivotBy",le=H&&n==="groupBy",ue=!P&&H&&n==="groupBy",ce=P&&H&&n==="groupBy",be=P&&n==="metrics"&&((_s=g.config)==null?void 0:_s.comparisonType)==="target",Ue=n==="metrics",Me=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:q=>{q.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}`}),Ne=()=>oe?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Ee,{value:t.label??"",onSave:te,placeholder:"Display label...",type:"text"})]}):null,me=()=>le?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:_,onValueChange:ge,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(q=>e.jsx(s.SelectItem,{className:"text-xs",value:q,children:s.toTitleCase(q)},q))})]})]}):null,ae=()=>ue?e.jsxs(e.Fragment,{children:[me(),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:G?"custom":L,onValueChange:ne,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:se.map(q=>e.jsx(s.SelectItem,{className:"text-xs",value:q.value,children:q.label},q.value))})]}),G&&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:R,onChange:q=>{q.stopPropagation(),he(q.target.value)},onClick:q=>q.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,je=()=>{var q,pe,fe,ve,Ae;return ce?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:((q=g.config)==null?void 0:q.comparisonType)||"none",onValueChange:C,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((pe=g.config)==null?void 0:pe.showTrendline)||!1,onCheckedChange:S})]})}),((fe=g.config)==null?void 0:fe.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:((ve=g.config)==null?void 0:ve.trendlineWindow)||30,onChange:ts=>{const na=parseInt(ts.target.value)||30;v(na)},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:((Ae=g.config)==null?void 0:Ae.trendlineGranularity)||"day",onValueChange:k,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},Qe=()=>{var q,pe;return be?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(Ee,{value:((q=g.config)==null?void 0:q.targetValue)!==void 0&&((pe=g.config)==null?void 0:pe.targetValue)!==null?String(g.config.targetValue):"",onSave:fe=>{!isNaN(Number(fe))&&fe!==null?N(Number(fe)):N(0)},placeholder:"Enter target value...",type:"text"})]}):null},Le=()=>Ue?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:q=>{p(a,q)},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"}),(U==null?void 0:U.conditions)&&U.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:U.conditions.map(q=>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(q),I(!0)},children:[e.jsxs("span",{className:"font-medium",children:[q.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(q.value)?q.value.length===1?String(q.value[0]):q.value.length<=2?q.value.join(", "):`${q.value.slice(0,2).join(", ")} +${q.value.length-2}`:String(q.value)})}),Array.isArray(q.value)&&q.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 (",q.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:q.value.map((pe,fe)=>e.jsx("div",{children:String(pe)},fe))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:pe=>{var ve;pe.stopPropagation();const fe=U.conditions.filter(Ae=>Ae.id!==q.id);if(fe.length>0){const Ae={...U,conditions:fe};re(Ae)}else if(ee(void 0),n==="metrics"){const Ae={...t,parameters:{...t.parameters,filters:void 0}},ts=[...((ve=g.config)==null?void 0:ve.metricColumns)||[]];ts[a]=Ae,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:ts})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},q.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(Qt,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(Pl,{aliasTemplate:$,onAliasTemplateChange:V}),e.jsx(zl,{valueAliases:Y,onValueAliasesChange:Z})]})]}):null,{columns:ta=[]}=s.useColumns(),aa=(U==null?void 0:U.conditions)&&U.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:de,...i,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${x?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Ps,{dataType:xe}),e.jsx(fs,{className:s.cn("w-[140px] flex-1 text-sm",aa&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Us=U==null?void 0:U.conditions)==null?void 0:Us.length)&&!F&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:U.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:U.conditions.map(q=>e.jsxs("div",{children:[q.field.label,":"," ",Array.isArray(q.value)?`${q.value.length} values`:String(q.value)]},q.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:q=>{q.stopPropagation(),T(!F)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${F?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:q=>{q.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const pe=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",pe),l(pe)},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:q=>{q.stopPropagation(),ie()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),F&&e.jsxs("div",{className:"space-y-3",children:[Me(),Ne(),c==="kpi"&&me(),ae(),je(),Qe(),Le()]})]}),B&&e.jsx(_l,{open:B,onOpenChange:q=>{I(q),q||M(null)},availableFields:ta,existingFilters:U,editingCondition:w,onSave:q=>{var pe;if(q)re(q);else if(ee(void 0),n==="metrics"){const fe={...t,parameters:{...t.parameters,filters:void 0}},ve=[...((pe=g.config)==null?void 0:pe.metricColumns)||[]];ve[a]=fe,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:ve})}M(null)}})]})}function Yl({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 rs({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(b=>b.card),m=s.useEditorStore(b=>b.card.type),h=n.length>0,x=(b,p)=>{var f;!((f=u.config)!=null&&f.sortByColumns)||u.config.sortByColumns.findIndex(y=>y.id===b)===-1||d(u.id,b,{direction:p})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),g&&e.jsx(Yl,{concept:t})]}),e.jsx("div",{ref:i,className:`rounded-lg border-2 border-dashed p-1 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"min-h-[60px] border-muted-foreground/20 bg-background"}`,children:n.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:n.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((b,p)=>{const f=b.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Gl,{field:b,zone:t,index:p,sortDirection:f,onSortDirectionChange:y=>x(b.id,y),hasPivotColumns:o,cardType:m})})},b.id)})})})})]})}const tt=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],$l=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function ws({value:t,onChange:n,label:a}){const[r,l]=A.useState(!1),[o,c]=A.useState(!1),i=()=>{const d=tt.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:tt[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:$l.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{n(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Yt,{color:i(),onColorChange:d=>{n(d),c(!1)},onClose:()=>c(!1)})})]})]})}const ls={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%
335
- 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 ql(){var i,d,u,m,h,x,g,b,p,j;const t=s.useEditorStore(f=>f.card),{setCardPreferences:n}=s.useEditorActions(),a=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(a.length>=2&&r.length===0||a.length>=1&&r.length>0)))return null;const o=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=f=>{var E;const y={...t.preferences,kpiVisualOptions:{...(E=t.preferences)==null?void 0:E.kpiVisualOptions,metricComparison:{...o,...f}}};n(y)};return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:f=>c({enabled:f,...f&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:f=>c({calculationType:f}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(ls).map(([f,y])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:y.label},f))})]}),(()=>{var y,E,D;const f=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(y=ls[f])==null?void 0:y.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(E=ls[f])==null?void 0:E.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(D=ls[f])==null?void 0:D.example]})]})})()]}),e.jsx(Rs,{formatOptions:o.formatOptions||{},onFormatOptionsChange:f=>c({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"left",onValueChange:f=>c({position:f}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:f=>c({showArrow:f})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:f=>c({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(ws,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:f=>c({colorConfig:{...o.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(ws,{value:((x=o.colorConfig)==null?void 0:x.decrease)||"red",onChange:f=>c({colorConfig:{...o.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(ws,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:f=>c({colorConfig:{...o.colorConfig,noChange:f}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:f=>c({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((b=o.conditionalLabels)==null?void 0:b.increase)??"Increase",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,increase:f.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((p=o.conditionalLabels)==null?void 0:p.decrease)??"Decrease",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,decrease:f.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((j=o.conditionalLabels)==null?void 0:j.noChange)??"No change",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,noChange:f.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:f=>c({labelName:f.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function Hl(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var d;const i={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};n(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ie,{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(Rs,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function Wl({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const l=s.useEditorStore(b=>{var p;return((p=b.card.customCardPreferences)==null?void 0:p.url)&&b.card.type==="custom"}),o=s.useEditorStore(b=>b.card),c=o==null?void 0:o.type,i=t.length>0||a.length>0,d=c!=="kpi",u=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel","aggregateTable"].includes(c),h=d&&!m,x=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(rs,{zone:"groupBy",fields:t,label:x().label,placeholder:x().placeholder}),h&&e.jsx(rs,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(rs,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),u&&e.jsx(rs,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(Hl,{}),e.jsx(ql,{}),e.jsx($t,{}),e.jsx(qt,{}),e.jsx(Ht,{}),e.jsx(Wt,{})]})})]})]})}function Kl({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}){const[c,i]=A.useState(!1);s.useEditorStore(p=>p.showAIDialog);const d=s.useEditorStore(p=>p.card),{isLoading:u,isFetching:m,refetch:h}=s.useDashboardCardQuery(d),x=a.length>0||r.length>0||l.length>0,{setShowAIDialog:g}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(d);return A.useEffect(()=>{m||i(!1)},[m]),e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx(Rl,{selectedChart:t,onChartChange:n}),e.jsx(Bl,{selectedChart:t,onChartChange:n})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsxs("div",{className:s.cn("invisible flex gap-2",{visible:x||b}),children:[e.jsx(xs,{}),e.jsx(s.Button,{disabled:u||m,onClick:()=>{i(!0),h()},className:"h-8 shrink-0",size:"sm",variant:"secondary",children:c?e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}):e.jsx(s.RefreshCcw,{className:"h-4 w-4"})})]})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(Wl,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Ql({initialFilters:t,availableFields:n}={}){const[a,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(C=>C.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=n||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=C=>{const S=v=>{if(v.id===C){const k=i[0]||d,N=s.getDataType(k.dataType)==="date";return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:k,operator:N?"between":"=",value:N?[]:""}]}}return{...v,groups:v.groups.map(S)}};r(S(a))},m=C=>{const S=v=>{if(v.id===C){const k=i[0]||d,N=s.getDataType(k.dataType)==="date";return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:k,operator:N?"between":"=",value:N?[]:""}],groups:[]}]}}return{...v,groups:v.groups.map(S)}};r(S(a))},h=(C,S)=>{const v=k=>k.id===C?{...k,conditions:k.conditions.filter(N=>N.id!==S)}:{...k,groups:k.groups.map(v)};r(v(a))},x=(C,S)=>{const v=k=>k.id===C?{...k,groups:k.groups.filter(N=>N.id!==S)}:{...k,groups:k.groups.map(v)};r(v(a))},g=(C,S,v,k)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const N=F=>F.id===C?{...F,conditions:F.conditions.map(T=>T.id===S?{...T,[v]:k}:T)}:{...F,groups:F.groups.map(N)};r(N(a))},b=(C,S,v)=>{const k=N=>N.id===C?{...N,conditions:N.conditions.map(F=>F.id===S?{...F,...v}:F)}:{...N,groups:N.groups.map(k)};r(k(a))},p=(C,S)=>{const v=k=>k.id===C?{...k,logicalOperator:S}:{...k,groups:k.groups.map(v)};r(v(a))},j=(C,S)=>{const v=k=>k.id===C?{...k,negate:S}:{...k,groups:k.groups.map(v)};r(v(a))},f=(C,S,v)=>{const k=N=>N.id===C?{...N,conditions:s.arrayMove(N.conditions,S,v)}:{...N,groups:N.groups.map(k)};r(k(a))},y=(C,S,v)=>{const k=N=>N.id===C?{...N,groups:s.arrayMove(N.groups,S,v)}:{...N,groups:N.groups.map(k)};r(k(a))},E=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const S=k=>{let N="";typeof k.field=="object"?N=k.field.entityName?`${k.field.entityName}.${k.field.name}`:k.field.name:N=String(k.field);const F=k.operator;let T=k.value;if(k.field.dataType==="string"&&!["in","not in"].includes(k.operator))typeof T=="string"?T=`'${T}'`:Array.isArray(T)&&(T=`'${T.join(", ")}'`);else if(k.field.dataType==="date"||k.field.dataType==="datetime"||k.field.dataType==="timestamp")if(k.operator==="between"&&Array.isArray(T)&&T.length===2){const B=T[0]?`'${T[0]}'`:"NULL",I=T[1]?`'${T[1]}'`:"NULL";return`${N} BETWEEN ${B} AND ${I}`}else if((k.operator==="in"||k.operator==="not in")&&Array.isArray(T)){const B=T.map(I=>I?`'${I}'`:"NULL").join(", ");return`${N} ${F} (${B})`}else typeof T=="string"||T instanceof Date?T=`'${T}'`:Array.isArray(T)&&T.length>0&&(T=`'${T[0]}'`);else if(["in","not in"].includes(k.operator)){let B=[];Array.isArray(T)?B=T.map(I=>typeof I=="string"?`'${I}'`:String(I)):typeof T=="string"?B=T.split(",").map(I=>{const w=I.trim();return k.field.dataType==="string"?`'${w}'`:w}):typeof T=="number"&&(B=[String(T)]),T=`(${B.join(", ")})`}switch(F){case"contains":return typeof T=="string"?`${N} LIKE '%${T.replace(/'/g,"")}'`:`${N} LIKE '%${String(T)}'`;case"startsWith":return typeof T=="string"?`${N} LIKE '${T.replace(/'/g,"")}%'`:`${N} LIKE '${String(T)}%'`;case"endsWith":return typeof T=="string"?`${N} LIKE '%${T.replace(/'/g,"")}'`:`${N} LIKE '%${String(T)}'`;case"isNull":return`${N} IS NULL`;case"isNotNull":return`${N} IS NOT NULL`;default:return`${N} ${F} ${T}`}},v=k=>{const N=k.conditions.map(S),F=k.groups.map(w=>v(w)),T=[...N,...F].filter(Boolean);if(T.length===0)return"";const B=T.join(` ${k.logicalOperator} `),I=T.length>1?`(${B})`:B;return k.negate?`NOT ${I}`:I};return v(C)},D=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:u,addGroup:m,removeCondition:h,removeGroup:x,updateCondition:g,updateConditionFields:b,updateGroupOperator:p,updateGroupNegate:j,reorderConditions:f,reorderGroups:y,generateSQLPreview:E,hasAnyFilters:D}}function Jl({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 Xl=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"})}},Zl=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function eo({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[o,c]=A.useState(!1),i=A.useMemo(()=>{const d={};return a.forEach(u=>{const m=Zl(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[a]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Jl,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Xl(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((x,g)=>e.jsxs(s.CommandItem,{value:x.id,onSelect:()=>{n(x),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===x.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:x.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:x.description&&e.jsx("span",{children:x.description})})]})]},x.id+g))]},`${d}-${m}`))},d))})]})})]})}function zs(t){var p;const n=s.useEditorStore(j=>j.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(j=>j.card.config),o=l==null?void 0:l.joinPlan,c={...t,alias:t.name,label:"value",role:"groupby"},i={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...c,role:"sortby",direction:"asc"},u={joinPlan:o,groupByColumns:[c],metricColumns:[i],sortByColumns:[d]},m=((p=n.dataSource)==null?void 0:p.connectionId)||n.connectionId,{data:h,isPending:x,error:g}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:m,cardConfig:u,cardDataSource:n.dataSource})}catch(j){console.log(t),console.error("error",j)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:x,error:g}}function so({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[o,c]=Re.useState(!1),{filterValues:i}=zs(t),d=m=>{a(n.filter(h=>h!==m))},u=m=>{n.includes(m)?a(n.filter(h=>h!==m)):a([...n,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(m=>{const h=i.find(x=>x.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:x=>{x.key==="Enter"&&d(m)},onMouseDown:x=>{x.preventDefault(),x.stopPropagation()},onClick:x=>{x.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function to({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=zs(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:o.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function ao({value:t,operator:n,onChange:a,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),o=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=A.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(u&&m)return{from:u,to:m}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:m}}}},[t,n]),i=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),a([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),a([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const no=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ro=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],lo=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],oo=["=","!=","isNull","isNotNull"],io=["between","isNull","isNotNull"],co={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null"};function at(t){return co[t]||s.titleCase(t)}function uo(t){switch(t){case"string":return ro;case"number":return lo;case"boolean":return oo;case"date":return io;default:return no}}function Xt({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:x,transition:g,isDragging:b}=s.useSortable({id:t.id}),{isPending:p,error:j}=zs(t.field),f={transform:s.CSS.Transform.toString(x),transition:g};return e.jsxs("div",{ref:h,style:f,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:y=>c(a,y),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(eo,{value:t.field,onValueChange:y=>{const E=y,D=s.getDataType(E.dataType)==="date";d(a,t.id,{field:E,value:"",operator:D?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:y=>{y==="in"||y==="not in"?d(a,t.id,{operator:y,value:[]}):y==="isNull"||y==="isNotNull"?d(a,t.id,{operator:y,value:null}):d(a,t.id,{operator:y,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?at(t.operator):""})}),e.jsx(s.SelectContent,{children:uo(s.getDataType(t.field.dataType)).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y,children:at(y)},y))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?p?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):j?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(so,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(y=>typeof y=="string")?t.value:[],onChange:y=>d(a,t.id,{value:y}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:y=>d(a,t.id,{value:y.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(to,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:y=>d(a,t.id,{value:y}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:y=>d(a,t.id,{value:y==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(ao,{value:t.value,operator:t.operator,onChange:y=>d(a,t.id,{value:y}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:y=>l(a,t.id,"value",y.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function mo({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:x,availableFields:g,renderFilterGroup:b,updateConditionFields:p}){const{attributes:j,listeners:f,setNodeRef:y,transform:E,transition:D,isDragging:C}=s.useSortable({id:t.id}),S={transform:s.CSS.Transform.toString(E),transition:D},v=N=>{const{active:F,over:T}=N;if(T&&F.id!==T.id){const B=t.conditions.findIndex(w=>w.id===F.id),I=t.conditions.findIndex(w=>w.id===T.id);B!==-1&&I!==-1&&u(t.id,B,I)}},k=N=>{const{active:F,over:T}=N;if(T&&F.id!==T.id&&a){const B=t.groups.findIndex(w=>w.id===F.id),I=t.groups.findIndex(w=>w.id===T.id);B!==-1&&I!==-1&&m(a,B,I)}};return e.jsxs("div",{ref:y,style:S,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${C?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...j,...f,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:N=>r(t.id,N),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&o(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:v,children:e.jsx(s.SortableContext,{items:t.conditions.map(N=>N.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((N,F)=>e.jsx(Xt,{condition:N,index:F,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:p},N.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:k,children:e.jsx(s.SortableContext,{items:t.groups.map(N=>N.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(N=>b(N,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function ho({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:x,updateConditionFields:g,updateGroupOperator:b,updateGroupNegate:p,reorderConditions:j,reorderGroups:f,generateSQLPreview:y,hasAnyFilters:E,setCurrentFilters:D}=Ql({initialFilters:t,availableFields:n}),C=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[S,v]=A.useState(!1),k=(T,B,I)=>{const w=M=>M.id===T?{...M,conditions:M.conditions.map(L=>L.id===B?{...L,field:I,dataType:I.dataType}:L)}:{...M,groups:M.groups.map(w)};D(w(o))},N=(T,B=0,I)=>B===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:w=>{const{active:M,over:L}=w;if(L&&M.id!==L.id){const O=T.conditions.findIndex(z=>z.id===M.id),R=T.conditions.findIndex(z=>z.id===L.id);O!==-1&&R!==-1&&j(T.id,O,R)}},children:e.jsx(s.SortableContext,{items:T.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:T.conditions.map((w,M)=>e.jsx(Xt,{condition:w,index:M,groupId:T.id,groupLogicalOperator:T.logicalOperator,onUpdateCondition:x,onUpdateField:k,onRemoveCondition:m,onUpdateGroupOperator:b,availableFields:c,updateConditionFields:g},w.id))})}),e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:w=>{const{active:M,over:L}=w;if(L&&M.id!==L.id){const O=T.groups.findIndex(z=>z.id===M.id),R=T.groups.findIndex(z=>z.id===L.id);O!==-1&&R!==-1&&f(T.id,O,R)}},children:e.jsx(s.SortableContext,{items:T.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:T.groups.map(w=>N(w,B+1,T.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(T.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),S&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(T.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},T.id):e.jsx(mo,{group:T,depth:B,parentGroupId:I,onUpdateGroupOperator:b,onUpdateGroupNegate:p,onRemoveGroup:h,onUpdateCondition:x,onUpdateField:k,onRemoveCondition:m,onReorderConditions:j,onReorderGroups:f,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:N,updateConditionFields:g},T.id),F=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):N(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{id:"advanced-mode",checked:S,onCheckedChange:T=>v(T)}),e.jsx(s.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),E&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:y(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),F>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(E?o:null),children:"Apply Filters"})]})]})}function xo({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=u=>{a(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(ho,{filters:n,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function po({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[l,o]=A.useState(null),c=s.useEditorStore(b=>b.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],u=A.useCallback(b=>b.startsWith("card-")?null:b.startsWith("source-")||n.find(p=>p.id===b)?"source":a("groupBy").find(p=>p.id===b)?"groupBy":a("metrics").find(p=>p.id===b)?"metrics":a("pivotBy").find(p=>p.id===b)?"pivotBy":a("sortBy").find(p=>p.id===b)?"sortBy":null,[n,a]),m=A.useCallback(b=>{o(b.active.id)},[]),h=A.useCallback(b=>{const{active:p,over:j}=b;if(!j||!t){o(null);return}const f=p.id,y=j.id,E=u(f),D=u(y)||y;if(D==="sortBy"){if(E==="source"){const C=n.find(v=>v.id===f);if(!C){o(null);return}if(!(a("groupBy").some(v=>v.name===C.name&&v.qualifiedEntityName===C.qualifiedEntityName)||a("metrics").some(v=>v.name===C.name&&v.qualifiedEntityName===C.qualifiedEntityName))){o(null);return}}else if(E==="pivotBy"){o(null);return}else if(E!=="groupBy"&&E!=="metrics"&&E!=="sortBy"){o(null);return}}if(E==="source"&&D==="sortBy"){const C=[...n].find(k=>k.id===f);if(!C){o(null);return}const S=a("sortBy");if(s.fieldAlreadyExists(C,S)){o(null);return}const v=s.getNewField(C,"sortBy",S);o(null),r("sortBy",[...S,v]);return}if(E==="source"&&D!=="source"&&D!=="sortBy"){const C=[...n].find(N=>N.id===f);if(!C){o(null);return}const S=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(S.length>0){const N=S[0].qualifiedEntityName;if(!N){o(null);return}if(N!==C.qualifiedEntityName&&C.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(N,C.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const v=a(D);if(s.fieldAlreadyExists(C,v)){o(null);return}const k=s.getNewField(C,D,v);o(null),r(D,[...v,k]);return}if(E&&D&&E!=="source"&&D!=="source"&&E!==D){const C=a(E),S=a(D),v=C.find(F=>F.id===f);if(!v){o(null);return}const k=s.getNewField(v,D,S);if(o(null),D==="sortBy"){s.fieldAlreadyExists(v,S)||r(D,[...S,k]);return}const N=C.filter(F=>F.id!==f);r(E,N),r(D,[...S,k]);return}if(E&&D&&E===D&&E!=="source"){const C=a(E),S=C.findIndex(k=>k.id===f),v=C.findIndex(k=>k.id===y);if(S!==v){const k=s.arrayMove(C,S,v);r(E,k)}}o(null)},[t,n,a,r,u,i]),x=l?d.find(b=>b.id===l):null;return{activeId:l,activeField:x,handleDragStart:m,handleDragEnd:h}}function fo({dashboardFilterCount:t=0,cardFilterCount:n=0,clickFilterCount:a=0,onClick:r,className:l,showIcon:o=!0}){const c=t+n+a,i=c>0,d=t>0,u=n>0,m=a>0,h=e.jsxs(e.Fragment,{children:[o&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),x=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",l),children:h});return i?e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:x}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"p-2 text-xs",children:e.jsxs("div",{className:"space-y-1.5",children:[d&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-purple-500"}),e.jsxs("span",{children:[t," Dashboard filter",t!==1?"s":""]})]}),u&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),e.jsxs("span",{children:[n," Card filter",n!==1?"s":""]})]}),m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-gray-500"}),e.jsxs("span",{children:[a," Click filter",a!==1?"s":""]})]})]})})]})}):x}function go({activeView:t,onViewChange:n}){const a=s.useEditorStore(c=>c.card),{config:r}=A.useContext(s.SemaphorContext).tokenProps,l=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:o}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:c=>n(c),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),a.type!=="kpi"&&l&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",o&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:o?"Error":"Info"})]})})}const jo=[{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 bo(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=A.useState(!1),[l,o]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:jo.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function vo({isOpen:t,onClose:n}){const a=xt(n,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=A.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function yo({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:l,filterCount:o,activeCard:c,columns:i,columnsLoading:d,columnsError:u}){var Y;const m=s.useEditorStore(K=>K.card),h=s.useDashboardStore(K=>K.filterValues),x=(h==null?void 0:h.length)||0,{updateCardConfig:g,setCard:b,updateCardInFrame:p,setCardId:j,setShowAIDialog:f}=s.useEditorActions(),{updateCardId:y}=s.useDashboardActions(),[E,D]=A.useState(null),C=s.useEditorStore(K=>K.showAIDialog),[S,v]=A.useState(!1),[k,N]=A.useState(!1),[F,T]=A.useState(null),{isConsoleMode:B}=s.useDashboardPreferences(),{config:I}=A.useContext(s.SemaphorContext).tokenProps,w=(I==null?void 0:I.showInfoTab)!==!1,M=s.useEditorStore(K=>{var U;return((U=K.card.customCardPreferences)==null?void 0:U.url)&&K.card.type==="custom"}),{data:L,errorMessage:O,isLoading:R,isFetching:z,errorSql:G,pagination:Q}=s.useDashboardCardQuery(c),_=(K,U)=>{const ee={...c,paginationConfig:{page:K+1,pageSize:U}};b(ee),p(ee)};function W(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(m.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(h||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(c.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",i.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:d?"Loading...":u?"Error loading columns":JSON.stringify(i.slice(0,5),null,2)})]})]})]})}const $=K=>{if(!m.config)return;if(!K.length){g(m.id,{...m.config,sortByColumns:[]});return}const U=m.config,ee=K.map(({id:ne,desc:he})=>{var te,re;const ge=(te=U.metricColumns)==null?void 0:te.find(ie=>ie.label===ne),V=(re=U.groupByColumns)==null?void 0:re.find(ie=>ie.label===ne),Z=ge||V;return Z?{id:s.getFieldId("sortBy",Z),name:Z.name,dataType:Z.dataType,label:Z.label,qualifiedEntityName:Z.qualifiedEntityName,entityId:Z.entityId,entityName:Z.entityName,entityType:Z.entityType,role:"sortby",direction:he?"desc":"asc"}:null}).filter(ne=>ne!==null);g(m.id,{...U,sortByColumns:ee})},X=A.useMemo(()=>{var K,U;return(U=(K=m.config)==null?void 0:K.sortByColumns)==null?void 0:U.map(ee=>({id:ee.label,desc:ee.direction==="desc"}))},[(Y=m.config)==null?void 0:Y.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[a&&W(),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"&&C&&e.jsx(Bt,{variant:"outline"}),e.jsx(go,{activeView:t,onViewChange:n}),l&&e.jsx(fo,{dashboardFilterCount:x,cardFilterCount:o,onClick:l,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(bo,{})}),C&&e.jsx(xs,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end"),children:[t==="chart"&&e.jsx(Pt,{}),!C&&e.jsx(s.IconButton,{onClick:()=>f(!C),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!S&&M&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>v(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(zt,{})}),t==="table"&&(L==null?void 0:L.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:(L==null?void 0:L.records)||[],paginationMetadata:Q,onPaginationChange:_,isLoading:R||z,onSortChange:$,sortState:X})}),t==="info"&&w&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[B&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:m.id,onSave:K=>{const U=s.sanitizeCardId(K);if(!U){D("Card ID cannot be empty");return}const ee=y(m.id,U);if(ee.success){j(U);const ne={...m,id:U};b(ne),p(ne),D(null),s.ue.success("Card ID updated successfully")}else D(ee.error||"Failed to update Card ID"),s.ue.error(ee.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:m.id,className:"h-5 w-5"})]}),E&&e.jsx("p",{className:"text-xs text-destructive",children:E})]}),O||G?e.jsx(Et,{error:O,errorSql:G,onSendFeedback:()=>{const K=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:m.config,dataSource:c.dataSource,dashboardFilters:h,errorMessage:O,errorSql:G,generatedSql:L==null?void 0:L.sql});T(K),N(!0)}}):e.jsxs(e.Fragment,{children:[(L==null?void 0:L.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(It,{sql:L==null?void 0:L.sql,error:O,errorSql:G})]})]})})]}),e.jsx(vo,{isOpen:S,onClose:()=>v(!1)}),F&&e.jsx(s.FeedbackDialog,{open:k,onOpenChange:N,feedbackData:F})]})]})}function No({activeField:t}){const[n,a]=A.useState(!0);return A.useEffect(()=>{t&&a(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(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 Co=()=>{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 So(){var G,Q;const[t,n]=A.useState("chart"),[a,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(_=>_.showAIDialog),u=s.useDashboardStore(_=>_.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(_=>_.card.type);A.useEffect(()=>Co(),[]);const x=()=>{o(!0)},g=_=>{m(_)},b=s.useEditorStore(_=>_.frame),p=s.useEditorStore(_=>_.card);s.useEditorStore(_=>_.activeTabCardId),s.useEditorStore(_=>_.actions.getAvailableFields);const{addCard:j,removeCard:f,updateCard:y,setActiveCard:E,updateFilters:D}=s.useEditorActions(),{columns:C=[],isLoading:S,error:v}=s.useColumns(),k=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),N=p,{getFieldsForContainer:F,setFieldsForContainer:T}=Fs(N),{activeField:B,handleDragStart:I,handleDragEnd:w}=po({activeCardId:b.activeCardId,sourceFields:C,getFieldsForContainer:F,setFieldsForContainer:T}),M=(_,W)=>{W&&D(_,W)},L=_=>{var W;y(_,{config:{...(W=b.cards.find($=>$.id===_))==null?void 0:W.config,filters:void 0}})},O=C,R=_=>{if(!_)return 0;let W=_.conditions.length;return _.groups.forEach($=>{W+=R($)}),W},z=R(((G=N==null?void 0:N.config)==null?void 0:G.filters)||null);return e.jsxs(s.DndContext,{sensors:k,collisionDetection:s.closestCenter,onDragStart:I,onDragEnd:w,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Al,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Kl,{selectedChart:h,onChartChange:g,groupByFields:F("groupBy"),pivotByFields:F("pivotBy"),metricsFields:F("metrics"),sortByFields:F("sortBy")}),e.jsx(yo,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:x,filterCount:z,activeCard:N,dataSourceState:p.dataSource||s.EMPTY_DATA_SOURCE,columns:C,columnsLoading:S,columnsError:v,getFieldsForContainer:F,cards:b.cards,activeCardId:b.activeCardId,addCard:j,setActiveCard:E})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),N&&e.jsx(xo,{cardId:N.id,filters:((Q=N.config)==null?void 0:Q.filters)||null,onFiltersChange:M,onClearFilters:L,availableFields:O,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(No,{activeField:B||null})})]})}function wo({authToken:t,onSave:n,onClose:a}){const r=A.useRef(null),l=s.useEditorStore(T=>T.showAIDialog),o=s.useEditorStore(T=>T.isDevMode),c=s.useAssistantLayoutStore(T=>T.setFullscreen),i=s.useAssistantLayoutStore(T=>T.setPanelOpen),d=s.useAssistantLayoutStore(T=>T.setContainer),u=s.useAssistantPanel("editor"),m=s.useFullscreenAssistant(),h=s.useAssistantContainer("editor"),x=m==="editor",g=A.useCallback(T=>{d("editor",T)},[d]),{setAuthToken:b}=s.useDashboardActions(),{setShowAIDialog:p,setOnSave:j,setOnClose:f}=s.useEditorActions(),{setActiveAssistantType:y}=s.useAIActions(),{handleDragOver:E,handleDragEnd:D,handleDragStart:C,handleDragCancel:S,sensors:v}=Xn();A.useEffect(()=>{n&&j(n),a&&f(a)},[n,j,a,f]),A.useEffect(()=>{t&&t.accessToken&&b(t)},[t,b]),A.useEffect(()=>{var T,B;l?((T=r.current)==null||T.resize(40),i("editor",!0),y("editor")):((B=r.current)==null||B.resize(0),i("editor",!1),m==="editor"&&c(null),y(null))},[l,i,y,c,m]);function k(T){T<1?(p(!1),i("editor",!1),m==="editor"&&c(null),y(null)):(l||(p(!0),y("editor")),u.isOpen||i("editor",!0))}function N(){return e.jsxs(e.Fragment,{children:[e.jsx(kt,{type:"main"}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",x&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(gl,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:k,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Xs,{isFullscreen:x,onFullscreenChange:T=>c(T?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:g,className:s.cn("absolute inset-0",!x&&"pointer-events-none")})]})]})}function F(){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",x&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(So,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:k,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Xs,{isFullscreen:x,onFullscreenChange:T=>c(T?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:g,className:s.cn("absolute inset-0",!x&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:v,onDragStart:C,onDragEnd:D,onDragOver:E,onDragCancel:S,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:N()})}):F()})}function Do(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(c=>c.actions),a=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),n(!1))}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(wo,{onSave:l,onClose:o})})}function To({column:t}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{className:"shrink-0",asChild:!0,children:s.isTextDataType(t.data_type)?e.jsx(s.TextIcon,{className:"size-3 text-muted-foreground"}):s.isNumberDataType(t.data_type)?e.jsx(Ie,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(Pe,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(pa,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})})}function ko(){const t=s.useEditorStore(o=>o.selectedDatabaseName),n=s.useEditorStore(o=>o.selectedTableName),a=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=Ls();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(o.column_name)&&i.table===n&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(To,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function Eo({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Se,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ie,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Pe,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx($e,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Xe,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ss,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Se,{className:"h-3 w-3"})})}function Io(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useDashboardStore(f=>f.dashboard.filters)||[],{assignFilter:o}=Ls(),c=s.useEditorStore(f=>f.card.dataSource),{columns:i=[],isLoading:d,error:u}=s.useColumns(),m=i.filter(f=>f.name.toLowerCase().includes(t.toLowerCase())||f.dataType.toLowerCase().includes(t.toLowerCase())||f.label&&f.label.toLowerCase().includes(t.toLowerCase())),h=f=>{const y=s.getDataType(f.dataType);return y==="number"?"metrics":(["date","string","boolean"].includes(y),"dimensions")},x=a==="all"?m:m.filter(f=>h(f)===a),g=m.filter(f=>h(f)==="dimensions").length,b=m.filter(f=>h(f)==="metrics").length,p=f=>{const y={column_name:f.name,data_type:f.dataType,label:f.label,description:f.description};o(y,"dashboard",f)};if(d)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(u)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:u.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const j=m.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:f=>n(f.target.value)})]}),j&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:f=>r(f),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:b})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[x.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),x.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),x.map(f=>{const y=l==null?void 0:l.some(E=>{var D;return E.title===f.name||((D=E.column)==null?void 0:D.includes(f.name))});return e.jsx("div",{onClick:()=>p(f),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":y}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Eo,{dataType:f.dataType}),e.jsx("span",{children:f.label||f.name})]})},f.id)})]})]})}function Ao(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),n=s.useCurrentActiveCard(),a=n&&((r=n.dataSource)==null?void 0:r.selectedEntities)&&n.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:a?e.jsx(Io,{}):e.jsx(kt,{type:"filter",ColumnsComponent:()=>e.jsx(ko,{})})})]})}function Mo(){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 Lo(){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(Mo,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Ao,{})})]})}function Ro(){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 Zt(){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 Oo=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 Fo({visual:t,isDeleting:n,isDuplicating:a,onAddVisual:r,onOpenVisual:l,onEditDetails:o,onDeleteClick:c,onDuplicateVisual:i,onShareVisual:d,formatDate:u}){var C,S,v,k;const{selectVisual:m}=s.useManagementActions(),h=s.useIsVisualSelected(t.id),x=Oo(t.id),{isConsoleMode:g}=s.useDashboardPreferences(),b=A.useRef(null),[p,j]=A.useState(!1),[f,y]=A.useState(!1);A.useEffect(()=>{a?(j(!0),y(!0)):f&&(j(!1),y(!1))},[a,f]),A.useEffect(()=>{x&&b.current&&b.current.scrollIntoView({behavior:"smooth",block:"center"})},[x]);const E=()=>e.jsx(ms,{className:"h-4 w-4"}),D=()=>{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",x?"border-purple-500":h&&"border-primary"),onClick:D,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children:E()}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx("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:(C=t.description)!=null&&C.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",h&&"visible"),onClick:N=>N.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:N=>{N.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:N=>{N.stopPropagation(),o==null||o(t)},title:"Edit details",children:e.jsx(os,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:p,onOpenChange:j,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),r(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),l==null||l(t)},children:[e.jsx(wa,{className:"mr-2 h-3 w-3"}),"Open"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.preventDefault(),N.stopPropagation(),i(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:N=>{N.stopPropagation(),o==null||o(t)},children:[e.jsx(os,{className:"mr-2 h-3 w-3"}),"Edit details"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),d(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.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:[(((S=t.ownership.createdBy)==null?void 0:S.type)==="tenant"||((v=t.ownership.createdBy)==null?void 0:v.type)==="organization"&&g)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((k=t.ownership.createdBy)==null?void 0:k.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 ea({open:t,resourceLabel:n,initialTitle:a,initialDescription:r="",onClose:l,onSave:o,isSaving:c=!1}){const[i,d]=A.useState(a),[u,m]=A.useState(r??"");A.useEffect(()=>{t&&(d(a),m(r??""))},[t,a,r]);const h=x=>{x.preventDefault();const g=i.trim();g&&o({title:g,description:u.trim()})};return e.jsx(s.Dialog,{open:t,onOpenChange:x=>x?null:l(),children:e.jsx(s.DialogContent,{className:"sm:max-w-md",children:e.jsxs("form",{onSubmit:h,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:i,onChange:x=>d(x.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:x=>m(x.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:c,children:"Cancel"}),e.jsx(s.Button,{type:"submit",disabled:c||!i.trim(),children:c?"Saving...":"Save changes"})]})]})})})}function Bo(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(!1),[m,h]=A.useState(null),[x,g]=A.useState(!1),[b,p]=A.useState(null),[j,f]=A.useState(null),[y,E]=A.useState(null),{selectVisual:D}=s.useManagementActions(),{handleEditLibraryVisual:C,handleAddLibraryVisual:S}=Ve(),{resources:v,isLoading:k,isError:N,createResource:F,updateResource:T,deleteResource:B,duplicateResource:I,isCreating:w,isDeleting:M}=s.useVisualManagement(()=>{g(!1),p(null)},V=>{r(!1),o(""),i(""),V&&(D(V),C(V))});s.useCurrentUserInfo();const L=v.filter(V=>{var Z,te;return((Z=V==null?void 0:V.title)==null?void 0:Z.toLowerCase().includes(t.toLowerCase()))||((te=V==null?void 0:V.description)==null?void 0:te.toLowerCase().includes(t.toLowerCase()))}),O=V=>new Date(V).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),R=()=>{l.trim()&&F({title:l,description:c,isPrivate:!1})},z=V=>{p(V),g(!0)},G=()=>{b&&B(b.id)},{startUpdating:Q,stopUpdating:_,isUpdating:W}=s.useResourceUpdateState(),$=(V,Z,te)=>{var xe;const re=Object.fromEntries(Object.entries(Z).filter(([,H])=>H!==void 0));if(Object.keys(re).length===0){(xe=te==null?void 0:te.onSuccess)==null||xe.call(te);return}const ie=Object.keys(re),de=ie.length===1?ie[0]:void 0;Q(V,de),T({resourceId:V,data:re},{onSuccess:()=>{var H;_(V,de),(H=te==null?void 0:te.onSuccess)==null||H.call(te)},onError:()=>{var H;_(V,de),(H=te==null?void 0:te.onError)==null||H.call(te)}})},X=V=>{f(V),I(V,{onSettled:()=>f(null)})},Y=V=>{C(V)},K=V=>{S(V)},U=V=>{const Z=v.find(te=>te.id===V);Z&&T({resourceId:V,data:{isPrivate:!Z.isPrivate}})},ee=V=>{h(V),u(!0)},ne=V=>{E(V)},he=()=>{E(null)},ge=({title:V,description:Z})=>{if(!y)return;const te={};V!==y.title&&(te.title=V),(y.description||"")!==Z&&(te.description=Z),$(y.id,te,{onSuccess:()=>{E(null)}})};return k?e.jsx(Zt,{}):N?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:[a&&e.jsx("div",{children:e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:V=>o(V.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:V=>i(V.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:R,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||w,children:w?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:w,children:"Cancel"})]})]})]})}),v&&v.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:V=>n(V.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:L.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(ms,{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"]})]}):L.map(V=>e.jsx(Fo,{visual:V,onAddVisual:K,onOpenVisual:Y,onEditDetails:ne,onDeleteClick:z,onDuplicateVisual:X,onTogglePrivacy:U,onShareVisual:ee,isDeleting:M,isDuplicating:j===V.id,formatDate:O},V.id))})}),d&&m&&e.jsx(hs,{resource:m,resourceType:s.ResourceType.VISUAL,onClose:()=>{u(!1),h(null)}}),y&&e.jsx(ea,{open:!!y,resourceLabel:"Visual",initialTitle:y.title||"",initialDescription:y.description||"",onClose:he,onSave:ge,isSaving:W(y.id)}),e.jsx(s.AlertDialog,{open:x,onOpenChange:V=>{!V&&M||(g(V),V||p(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',b==null?void 0:b.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:M,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:V=>{V.preventDefault(),V.stopPropagation(),G()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:M,children:[M?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"}),M?"Deleting...":"Delete"]})]})]})}),!a&&e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 right-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 Po({dashboard:t,isDeleting:n,isDuplicating:a,onLoadDashboard:r,onEditDetails:l,onDeleteClick:o,onDuplicateDashboard:c,onShareDashboard:i,formatDate:d,onDashboardItemClick:u}){var E,D,C,S;const{selectDashboard:m}=s.useManagementActions(),h=s.useIsDashboardSelected(t.id),{isConsoleMode:x}=s.useDashboardPreferences(),[g,b]=A.useState(!1),[p,j]=A.useState(!1);A.useEffect(()=>{a?(b(!0),j(!0)):p&&(b(!1),j(!1))},[a,p]);const f=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),y=()=>{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",h&&"border-primary"),onClick:y,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:f()}),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:(E=t.description)!=null&&E.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:v=>v.stopPropagation(),children:[t.permissions.canEdit&&e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:v=>{v.stopPropagation(),l==null||l(t)},title:"Edit details",children:e.jsx(os,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:b,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.preventDefault(),v.stopPropagation(),c(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:v=>{v.stopPropagation(),l==null||l(t)},children:[e.jsx(os,{className:"mr-2 h-3 w-3"}),"Edit details"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),i(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:v=>{v.stopPropagation(),o(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"||((C=t.ownership.createdBy)==null?void 0:C.type)==="organization"&&x)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((S=t.ownership.createdBy)==null?void 0:S.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:d(t.lastModified)})]})]})]})]})]})]})},t.id)}function zo({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function Vo(t){const{onLoadDashboard:n,onEditDashboard:a,onDashboardItemClick:r}=t,[l,o]=A.useState(""),[c,i]=A.useState(!1),[d,u]=A.useState(""),[m,h]=A.useState(""),[x,g]=A.useState(!1),[b,p]=A.useState(null),[j,f]=A.useState(!1),[y,E]=A.useState(null),[D,C]=A.useState(null),[S,v]=A.useState(null),k=s.useManagementStore(P=>P.lastSelectedDashboard),N=s.useManagementStore(P=>P.selectedDashboard),F=s.useManagementStore(P=>P.actions.selectDashboard),T=s.useManagementStore(P=>P.actions.clearSelectedDashboard),{tokenProps:B,id:I}=s.useSemaphorContext(),{permissions:w}=s.useRoleAwareDisplayPreferences(),{resources:M,isLoading:L,isError:O,createResource:R,updateResource:z,deleteResource:G,duplicateResource:Q,isCreating:_,isDeleting:W}=s.useDashboardManagement(()=>{f(!1);const P=y==null?void 0:y.id;E(null),(N==null?void 0:N.id)===P&&(!(B!=null&&B.dashboard_id)&&!I?T():k&&k.id!==P&&F(k))},P=>{i(!1),u(""),h(""),P&&(F(P),r==null||r(P.id))}),{currentUser:$}=s.useCurrentUserInfo(),X=M.filter(P=>{var J,se;return((J=P==null?void 0:P.title)==null?void 0:J.toLowerCase().includes(l.toLowerCase()))||((se=P==null?void 0:P.description)==null?void 0:se.toLowerCase().includes(l.toLowerCase()))}),Y=P=>new Date(P).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),K=()=>{d.trim()&&R({title:d,description:m,isPrivate:!1})},U=P=>{n==null||n(P)},ee=P=>{E(P),f(!0)},ne=()=>{y&&G(y.id)},he=P=>{C(P),Q(P,{onSettled:()=>C(null)})},{startUpdating:ge,stopUpdating:V,isUpdating:Z}=s.useResourceUpdateState(),te=(P,J,se)=>{var ce;const oe=Object.fromEntries(Object.entries(J).filter(([,be])=>be!==void 0));if(Object.keys(oe).length===0){(ce=se==null?void 0:se.onSuccess)==null||ce.call(se);return}const le=Object.keys(oe),ue=le.length===1?le[0]:void 0;ge(P,ue),z({resourceId:P,data:oe},{onSuccess:()=>{var be;V(P,ue),(be=se==null?void 0:se.onSuccess)==null||be.call(se)},onError:()=>{var be;V(P,ue),(be=se==null?void 0:se.onError)==null||be.call(se)}})},re=P=>{const J=M.find(se=>se.id===P);J&&z({resourceId:P,data:{isPrivate:!J.isPrivate}})},ie=P=>{p(P),$==null||$.type,g(!0)},de=P=>{a==null||a(P.id),v(P)},xe=()=>{v(null)},H=({title:P,description:J})=>{if(!S)return;const se={};P!==S.title&&(se.title=P),(S.description||"")!==J&&(se.description=J),te(S.id,se,{onSuccess:()=>{v(null)}})};return L?e.jsx(Zt,{}):O?e.jsx(zo,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[w.canCreateDashboards&&c&&e.jsx("div",{children:e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:d,onChange:P=>u(P.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:m,onChange:P=>h(P.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:K,size:"sm",className:"h-7 text-xs",disabled:!d.trim()||_,children:_?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{i(!1),u(""),h("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:_,children:"Cancel"})]})]})]})}),M&&M.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:P=>o(P.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:X.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":w.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),w.canCreateDashboards&&!l&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>i(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Dashboard"]})]}):X.map(P=>e.jsx(Po,{dashboard:P,isDeleting:W,isDuplicating:D===P.id,onLoadDashboard:U,onEditDetails:de,onDeleteClick:ee,onDuplicateDashboard:he,onTogglePrivacy:re,onShareDashboard:ie,formatDate:Y,onDashboardItemClick:r},P.id))})}),x&&b&&e.jsx(hs,{resource:b,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{g(!1),p(null)}}),e.jsx(s.AlertDialog,{open:j,onOpenChange:P=>{!P&&W||(f(P),P||E(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 "',y==null?void 0:y.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:W,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:P=>{P.preventDefault(),P.stopPropagation(),ne()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:W,children:[W?e.jsx(s.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):e.jsx(s.Trash2,{className:"mr-2 h-3.5 w-3.5"}),W?"Deleting...":"Delete"]})]})]})}),S&&e.jsx(ea,{open:!!S,resourceLabel:"Dashboard",initialTitle:S.title||"",initialDescription:S.description||"",onClose:xe,onSave:H,isSaving:Z(S.id)}),w.canCreateDashboards&&!c&&e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 right-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>i(!0),"aria-label":"Create dashboard",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function sa({isOpen:t,onClose:n,className:a,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(E=>E.dashboard);const{setDashboard:o,addSheet:c}=s.useDashboardStore(E=>E.actions),{currentUser:i}=s.useCurrentUserInfo(),d=i,{permissions:u}=s.useRoleAwareDisplayPreferences(),m=(u.canAccessVisuals,"dashboards"),[h,x]=Bs("resource-management-active-tab",m),g=u.canAccessVisuals?h:"dashboards",b=l==="overlay",p=xt(n,{enabled:t&&b}),j=s.cn("flex h-full flex-col border-r bg-background",b?s.cn("absolute inset-y-0 left-0 z-[51] w-96 shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"pointer-events-none -translate-x-full"):"w-full max-w-[28rem] min-w-[18rem] overflow-hidden shadow-sm",a),f=E=>{},y=E=>{console.log("Editing dashboard:",E)};return e.jsx(s.TooltipProvider,{children:(!b||t)&&e.jsxs("div",{ref:p,className:j,children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border p-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:d&&e.jsxs(e.Fragment,{children:[e.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:d.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:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email}),d.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(d.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",d.id]})]})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"text-sm font-medium text-foreground",children:d.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(za,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:g,onValueChange:u.canAccessVisuals?x:void 0,className:"flex h-9 grow flex-col",children:[u.canAccessVisuals?e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}):e.jsx("div",{className:"px-4 pb-0 pt-4",children:e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Dashboards"})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1 px-4 py-4",children:e.jsx(Vo,{onLoadDashboard:f,onEditDashboard:y,onDashboardItemClick:r})}),u.canAccessVisuals&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 px-4 py-4",children:e.jsx(Bo,{})})]})})]})})}function _o({showControls:t=!1,showFooter:n=!0,...a}){const r=s.useDashboardStore(x=>x.isDashboardPanelOpen);s.useDashboardStore(x=>x.isVisualEditing);const l=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),o=20,c=20,i=30,d=r,u=A.useRef(null),m=A.useRef(null);A.useEffect(()=>{u.current&&m.current&&(r?(u.current.resize(o),m.current.resize(100-o)):(u.current.resize(0),m.current.resize(100)))},[r]);const{preferences:h}=a;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:h,children:[e.jsx(Ro,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(qn,{}),e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",className:"flex grow overflow-hidden",children:[e.jsx(s.ResizablePanel,{ref:u,className:s.cn("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?o:0,minSize:d?c:0,maxSize:d?i:0,children:e.jsx(sa,{isOpen:r,onClose:()=>l(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{withHandle:d,className:s.cn("w-1",{"w-0":!d})}),e.jsx(s.ResizablePanel,{ref:m,className:"flex min-w-0 flex-1",defaultSize:d?100-o:100,minSize:d?40:100,children:e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(Do,{}),e.jsx(Lo,{})]})})]})]})]})})]})})}exports.AdvancedModeToggle=Dt;exports.DashboardPlus=_o;exports.ResourceManagementPanel=sa;exports.ScheduleDashboard=dt;exports.SelectComponent=Ge;exports.ShareDialog=hs;exports.VisualBadge=yt;exports.VisualEditingControls=wt;exports.cleanCard=ct;exports.getDashbaordStateWithoutData=is;
334
+ ON ${y}`}),b};return o.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[a.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>l(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":a.joins.length>0,"text-gray-500":a.joins.length===0})}),"Join",a.joins.length>1?"s":""," (",a.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(Dl,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:o,generateSQLPreview:u})})]})}),e.jsx(Zs,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(Zs,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function kl({open:t,onOpenChange:n}){const[a,r]=A.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(p=>p.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];A.useEffect(()=>{t&&r([])},[t]);const i=p=>{r(j=>j.some(y=>y.name===p.name&&y.type===p.type)?j.filter(y=>!(y.name===p.name&&y.type===p.type)):[...j,p])},d=()=>{r([...c])},u=()=>{r([])},m=()=>{if(a.length===0)return;const p=a[0],j=p.connectionId||"",f=p.connectionType||"",I=a.some(N=>N.type==="dataset")?"semanticDomain":"database";l({connectionId:j,connectionType:f,mode:I,selectedEntities:a}),n(!1)},h=p=>{switch(p.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Ka,{className:"h-4 w-4"});case"model":return e.jsx(va,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},x=p=>"label"in p&&p.label?p.label:p.name,g=p=>{if("description"in p&&p.description)return p.description;const j=[];return p.database&&j.push(p.database),p.schema&&j.push(p.schema),p.name&&j.push(p.name),j.join(".")},b=p=>a.some(j=>j.name===p.name&&j.type===p.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:a.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((p,j)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",b(p)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:b(p),onCheckedChange:()=>i(p)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(p)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:x(p)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(p)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p.type})]},`${p.type}-${p.name}-${j}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function El({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function Il({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((n,a)=>{const r=s.getEntityDetails(n),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function Al({isVisible:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(!1),[o,c]=A.useState(!0),i=s.useEditorStore(h=>h.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:d}=s.useEditorActions(),u={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},m={...u,...i,selectedEntities:(i==null?void 0:i.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:"p-4 px-6 pb-2",children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>a(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Add Data"]})}),e.jsxs("div",{className:"relative px-6",children:[e.jsx("div",{className:"absolute inset-0 flex items-center px-6",children:e.jsx("div",{className:"w-full border-t border-border"})}),e.jsx("div",{className:"relative flex justify-center",children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>c(!o),className:"size-6 bg-background p-1 py-1 hover:bg-accent",children:o?e.jsx(s.ChevronUp,{className:"h-3.5 w-3.5"}):e.jsx(s.ChevronDown,{className:"h-3.5 w-3.5"})})})]}),e.jsxs("div",{className:`overflow-hidden px-6 ${o?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[m.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[m.selectedEntities.slice(0,3).map((h,x)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(h),e.jsx("button",{onClick:g=>{g.stopPropagation();const b=m.selectedEntities.filter(p=>!(p.name===h.name&&p.type===h.type));d({...u,...i,selectedEntities:b})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(El,{entity:h})]},`${h.type}-${h.name}-${x}`)),m.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",m.selectedEntities.length-3," more"]})}),e.jsx(Il,{entities:m.selectedEntities.slice(3)})]})]})}),e.jsx(Tl,{})]})]}),e.jsx(Cl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(i==null?void 0:i.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:a,dataSource:m,fallbackDataSource:u}),e.jsx(kl,{open:r,onOpenChange:l})]})}function Bs(t,n){const[a,r]=A.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):n});return A.useEffect(()=>{localStorage.setItem(t,JSON.stringify(a))},[a,t]),[a,r]}const Ml="chart-selector-standard-first";function Ll(){const[t,n]=Bs(Ml,!0);return{standardFirst:t,updatePreference:n}}const et=({pluginVisual:t,index:n,onSelect:a})=>{const r=ps(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},st=["default","standardPlugin","customPlugin"];function Rl({selectedChart:t,onChartChange:n}){var D;const[a,r]=A.useState(!1),{data:l}=Ot();Ll();const c=((D=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:D.url)||"";As(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:x}=s.useEditorActions(),[g,b]=Bs("chart-section-active",null),p=A.useMemo(()=>g?[g,...st.filter(N=>N!==g)]:st,[g]);function j(N){m(null),d({}),i(N),["custom","map"].includes(N)&&(u(!0),x(void 0)),n(N),r(!1)}function f(N){m(null),d({}),i("custom"),h({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),x(void 0),n("custom"),r(!1)}const y=()=>{var S;if(t==="custom"){const v=s.useEditorStore.getState().card;return((S=v==null?void 0:v.customCardPreferences)==null?void 0:S.componentName)||"Custom Visual"}const N=s.chartTypes.find(v=>v.id===t);return(N==null?void 0:N.label)||"Select chart type"},I=()=>{var S,v;if(t==="custom"){const k=s.useEditorStore.getState().card,C=(S=k==null?void 0:k.customCardPreferences)==null?void 0:S.icon,F=(v=k==null?void 0:k.customCardPreferences)==null?void 0:v.componentName;if(C&&F)return e.jsx(Ol,{icon:C,componentName:F});if(F){const T=s.getAutoDetectedChartIcon(F);if(T)return T}return e.jsx(Ze,{className:"h-4 w-4"})}const N=s.chartTypes.find(k=>k.id===t);if(N){const k=N.icon;return e.jsx(k,{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:[I(),e.jsx("span",{children:y()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),p.map(N=>{if(N==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="default",onCheckedChange:S=>b(S?"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(S=>{const v=S.icon;return e.jsx(s.CommandItem,{value:`${S.label} ${S.id} chart graph visualization`,onSelect:()=>j(S.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{className:"h-4 w-4"}),e.jsx("span",{children:S.label})]})},S.id)})},"default");if(N==="standardPlugin"){const S=l.filter(v=>v.pluginType==="standard");return S.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="standardPlugin",onCheckedChange:v=>b(v?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:S.filter(v=>v.componentType==="chart").map((v,k)=>e.jsx(et,{pluginVisual:v,index:k,onSelect:()=>f(v)},`${v.url}-${v.name}-${k}`))},"standardPlugin"):null}if(N==="customPlugin"){const S=l.filter(v=>v.pluginType==="custom");return S.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="customPlugin",onCheckedChange:v=>b(v?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:S.map((v,k)=>e.jsx(et,{pluginVisual:v,index:k,onSelect:()=>f(v)},`${v.url}-${v.name}-${k}`))},"customPlugin"):null}return null})]})]})})]})})}const Ol=({icon:t,componentName:n})=>{const a=ps(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(Ze,{className:"h-4 w-4"})},Fl=[{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 Bl({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(o=>o.card),r=((l=a==null?void 0:a.config)==null?void 0:l.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center justify-center gap-1",children:Fl.map(o=>{if(o.requiresPivot&&!r)return null;const c=o.icon,i=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(o.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o.label})})]},o.id)})})}const 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(we,{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(Me,{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(ze,{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(we,{className:"h-3 w-3"})})};function Pl({aliasTemplate:t,onAliasTemplateChange:n}){var d;const[a,r]=A.useState(t),[l,o]=A.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?a:t,onChange:u=>{r(u.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&a!==t?(n(a),o(!1)):u.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function zl({valueAliases:t,onValueAliasesChange:n}){const[a,r]=A.useState(null),[l,o]=A.useState(""),[c,i]=A.useState(""),d=()=>{n({...t,"":""})},u=h=>{const x={...t};delete x[h],n(x)},m=h=>{const x={...t};delete x[h],x[l]=c,n(x),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,x],g)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:b=>i(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(x)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(x)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+g)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Vl({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),o=s.useEditorStore(u=>u.card),c=o==null?void 0:o.dataSource,i=["attribute-values",t.entityName,t.name,n,a],d=s.useQuery({queryKey:i,queryFn:async()=>{if(!(c!=null&&c.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},m={connection_id:c.connectionId,cardConfig:u,cardDataSource:c,cache_config:s.getCacheConfig({card:o})};console.log("requestBody",m);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const x=t.name;return((h==null?void 0:h.records)||[]).map(b=>{const p=b[x]||b[t.alias||x]||b[t.label];return{id:p||"",value:p||"",label:String(p||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(c!=null&&c.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:d.data||[],isLoading:d.isLoading,isFetching:d.isFetching,isError:d.isError,error:d.error,refetch:d.refetch}}function _l({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:o}){var I,D;const c=!!l,[i,d]=A.useState(c?"values":"fields"),[u,m]=A.useState(""),[h,x]=A.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),g=a.filter(N=>{var v;return c?!1:!((v=r==null?void 0:r.conditions)==null?void 0:v.some(k=>k.field.id===N.id))&&N.label.toLowerCase().includes(u.toLowerCase())}),b=N=>{x({...h,field:N}),d("values")},p=()=>{if(h.field&&h.selectedValues.length>0){const N={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let S;if(c){const v=((r==null?void 0:r.conditions)||[]).map(k=>k.id===l.id?N:k);S={...r,conditions:v}}else{const v=(r==null?void 0:r.conditions)||[];S={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...v,N],groups:[]}}o(S),n(!1)}},j=()=>{if(!c||!l)return;const N=((r==null?void 0:r.conditions)||[]).filter(S=>S.id!==l.id);if(N.length>0){const S={...r,conditions:N};o(S)}else o(void 0);n(!1)},f=N=>{x({...h,selectedValues:N})},y=()=>{c&&l?(x({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(x({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return A.useEffect(()=>{t&&y()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(I=h.field)==null?void 0:I.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(D=h.field)==null?void 0:D.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(N=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[N.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(N.value)?`${N.value.length} values`:String(N.value)})]},N.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:u,onChange:N=>m(N.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(N=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(N),children:[e.jsx(Ps,{dataType:s.getDataType(N.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:N.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[N.entityName,".",N.name]})]})]},N.id))}),g.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),g.length===0&&!u&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Ul,{field:h.field,selectedValues:h.selectedValues,onValuesChange:f,onBack:c?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:j,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:y,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:p,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Ul({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,o]=A.useState(""),{values:c,isLoading:i,isFetching:d}=Vl({field:t,searchQuery:l,limit:500}),u=l?c.filter(x=>String(x.value).toLowerCase().includes(l.toLowerCase())):c,m=x=>{const g=n.includes(x);a(g?n.filter(b=>b!==x):[...n,x])},h=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(x=>x.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:x=>o(x.target.value),className:"pl-10"})]}),i||d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(x=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(x.value),children:[e.jsx(s.Checkbox,{checked:n.includes(x.value),onCheckedChange:()=>m(x.value)}),e.jsx(fs,{className:"text-sm",children:x.label})]},x.id))})]})]})}function Gl({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Vs,_s,Us;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:x}=s.useSortable({id:t.id}),g=s.useEditorStore(H=>H.card),{updateLabel:b,handleAggregationChange:p,handleDateFormatChange:j,handleGranularityChange:f,handleAliasTemplateChange:y,handleValueAliasesChange:I,removeField:D,handleKpiComparisonTypeChange:N,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:C}=Fs(g),[F,T]=A.useState(!1),[B,E]=A.useState(!1),[w,M]=A.useState(null),[L,O]=A.useState(t.dateFormat||"YYYY-MM-DD"),[R,P]=A.useState(t.customFormat||""),[G,J]=A.useState(!!t.customFormat),[V,K]=A.useState(t.granularity||"day"),[$,X]=A.useState(t.aliasTemplate||""),[q,Q]=A.useState(t.valueAliases||{}),[_,te]=A.useState((Vs=t.parameters)==null?void 0:Vs.filters),re=H=>{H==="custom"?J(!0):(J(!1),O(H),n==="groupBy"&&j(a,H,""))},he=H=>{P(H),n==="groupBy"&&j(a,"custom",H)},ge=H=>{var ye;K(H);const fe=(ye=ee(H)[0])==null?void 0:ye.value;fe&&!G&&(O(fe),n==="groupBy"&&j(a,fe,"")),n==="groupBy"&&f(a,H)},z=H=>{X(H),n==="metrics"&&y(a,H)},Z=H=>{Q(H),n==="metrics"&&I(a,H)},ae=H=>{b(n,a,H)},oe=H=>{var pe;if(te(H),n==="metrics"){const fe={...t,parameters:{...t.parameters,filters:H}},ye=[...((pe=g.config)==null?void 0:pe.metricColumns)||[]];ye[a]=fe,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:ye})}E(!1)},de=()=>{D(n,a)},ue={transform:s.CSS.Transform.toString(m),transition:h},xe=s.getDataType(t.dataType),W=xe==="date",U=c==="kpi",ee=H=>{switch(H){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..."}]}},Y=ee(V),le=n!=="pivotBy",se=W&&n==="groupBy",ie=!U&&W&&n==="groupBy",ce=U&&W&&n==="groupBy",je=U&&n==="metrics"&&((_s=g.config)==null?void 0:_s.comparisonType)==="target",Ee=n==="metrics",be=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:H=>{H.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}`}),Ce=()=>le?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Ae,{value:t.label??"",onSave:ae,placeholder:"Display label...",type:"text"})]}):null,me=()=>se?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:V,onValueChange:ge,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(H=>e.jsx(s.SelectItem,{className:"text-xs",value:H,children:s.toTitleCase(H)},H))})]})]}):null,ne=()=>ie?e.jsxs(e.Fragment,{children:[me(),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:G?"custom":L,onValueChange:re,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:Y.map(H=>e.jsx(s.SelectItem,{className:"text-xs",value:H.value,children:H.label},H.value))})]}),G&&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:R,onChange:H=>{H.stopPropagation(),he(H.target.value)},onClick:H=>H.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,ve=()=>{var H,pe,fe,ye,Le;return ce?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:((H=g.config)==null?void 0:H.comparisonType)||"none",onValueChange:N,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((pe=g.config)==null?void 0:pe.showTrendline)||!1,onCheckedChange:S})]})}),((fe=g.config)==null?void 0:fe.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:((ye=g.config)==null?void 0:ye.trendlineWindow)||30,onChange:ts=>{const na=parseInt(ts.target.value)||30;v(na)},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:((Le=g.config)==null?void 0:Le.trendlineGranularity)||"day",onValueChange:k,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},Qe=()=>{var H,pe;return je?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(Ae,{value:((H=g.config)==null?void 0:H.targetValue)!==void 0&&((pe=g.config)==null?void 0:pe.targetValue)!==null?String(g.config.targetValue):"",onSave:fe=>{!isNaN(Number(fe))&&fe!==null?C(Number(fe)):C(0)},placeholder:"Enter target value...",type:"text"})]}):null},Re=()=>Ee?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:H=>{p(a,H)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(_==null?void 0:_.conditions)&&_.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:_.conditions.map(H=>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(H),E(!0)},children:[e.jsxs("span",{className:"font-medium",children:[H.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(H.value)?H.value.length===1?String(H.value[0]):H.value.length<=2?H.value.join(", "):`${H.value.slice(0,2).join(", ")} +${H.value.length-2}`:String(H.value)})}),Array.isArray(H.value)&&H.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 (",H.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:H.value.map((pe,fe)=>e.jsx("div",{children:String(pe)},fe))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:pe=>{var ye;pe.stopPropagation();const fe=_.conditions.filter(Le=>Le.id!==H.id);if(fe.length>0){const Le={..._,conditions:fe};oe(Le)}else if(te(void 0),n==="metrics"){const Le={...t,parameters:{...t.parameters,filters:void 0}},ts=[...((ye=g.config)==null?void 0:ye.metricColumns)||[]];ts[a]=Le,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:ts})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},H.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{M(null),E(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Qt,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(Pl,{aliasTemplate:$,onAliasTemplateChange:z}),e.jsx(zl,{valueAliases:q,onValueAliasesChange:Z})]})]}):null,{columns:ta=[]}=s.useColumns(),aa=(_==null?void 0:_.conditions)&&_.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:ue,...i,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${x?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Ps,{dataType:xe}),e.jsx(fs,{className:s.cn("w-[140px] flex-1 text-sm",aa&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Us=_==null?void 0:_.conditions)==null?void 0:Us.length)&&!F&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:_.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:_.conditions.map(H=>e.jsxs("div",{children:[H.field.label,":"," ",Array.isArray(H.value)?`${H.value.length} values`:String(H.value)]},H.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:H=>{H.stopPropagation(),T(!F)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${F?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:H=>{H.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const pe=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",pe),l(pe)},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:H=>{H.stopPropagation(),de()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),F&&e.jsxs("div",{className:"space-y-3",children:[be(),Ce(),c==="kpi"&&me(),ne(),ve(),Qe(),Re()]})]}),B&&e.jsx(_l,{open:B,onOpenChange:H=>{E(H),H||M(null)},availableFields:ta,existingFilters:_,editingCondition:w,onSave:H=>{var pe;if(H)oe(H);else if(te(void 0),n==="metrics"){const fe={...t,parameters:{...t.parameters,filters:void 0}},ye=[...((pe=g.config)==null?void 0:pe.metricColumns)||[]];ye[a]=fe,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:ye})}M(null)}})]})}function Yl({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 rs({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(b=>b.card),m=s.useEditorStore(b=>b.card.type),h=n.length>0,x=(b,p)=>{var f;!((f=u.config)!=null&&f.sortByColumns)||u.config.sortByColumns.findIndex(y=>y.id===b)===-1||d(u.id,b,{direction:p})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),g&&e.jsx(Yl,{concept:t})]}),e.jsx("div",{ref:i,className:`rounded-lg border-2 border-dashed p-1 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"min-h-[60px] border-muted-foreground/20 bg-background"}`,children:n.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:n.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((b,p)=>{const f=b.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Gl,{field:b,zone:t,index:p,sortDirection:f,onSortDirectionChange:y=>x(b.id,y),hasPivotColumns:o,cardType:m})})},b.id)})})})})]})}const tt=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],$l=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function ws({value:t,onChange:n,label:a}){const[r,l]=A.useState(!1),[o,c]=A.useState(!1),i=()=>{const d=tt.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:tt[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:$l.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{n(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Yt,{color:i(),onColorChange:d=>{n(d),c(!1)},onClose:()=>c(!1)})})]})]})}const ls={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%
335
+ 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 ql(){var i,d,u,m,h,x,g,b,p,j;const t=s.useEditorStore(f=>f.card),{setCardPreferences:n}=s.useEditorActions(),a=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(a.length>=2&&r.length===0||a.length>=1&&r.length>0)))return null;const o=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=f=>{var I;const y={...t.preferences,kpiVisualOptions:{...(I=t.preferences)==null?void 0:I.kpiVisualOptions,metricComparison:{...o,...f}}};n(y)};return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:f=>c({enabled:f,...f&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:f=>c({calculationType:f}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(ls).map(([f,y])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:y.label},f))})]}),(()=>{var y,I,D;const f=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(y=ls[f])==null?void 0:y.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(I=ls[f])==null?void 0:I.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(D=ls[f])==null?void 0:D.example]})]})})()]}),e.jsx(Rs,{formatOptions:o.formatOptions||{},onFormatOptionsChange:f=>c({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"left",onValueChange:f=>c({position:f}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:f=>c({showArrow:f})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:f=>c({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(ws,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:f=>c({colorConfig:{...o.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(ws,{value:((x=o.colorConfig)==null?void 0:x.decrease)||"red",onChange:f=>c({colorConfig:{...o.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(ws,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:f=>c({colorConfig:{...o.colorConfig,noChange:f}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:f=>c({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((b=o.conditionalLabels)==null?void 0:b.increase)??"Increase",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,increase:f.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((p=o.conditionalLabels)==null?void 0:p.decrease)??"Decrease",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,decrease:f.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((j=o.conditionalLabels)==null?void 0:j.noChange)??"No change",onChange:f=>c({conditionalLabels:{...o.conditionalLabels,noChange:f.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:f=>c({labelName:f.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function Hl(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var d;const i={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};n(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Me,{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(Rs,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function Wl({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const l=s.useEditorStore(b=>{var p;return((p=b.card.customCardPreferences)==null?void 0:p.url)&&b.card.type==="custom"}),o=s.useEditorStore(b=>b.card),c=o==null?void 0:o.type,i=t.length>0||a.length>0,d=c!=="kpi",u=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel","aggregateTable"].includes(c),h=d&&!m,x=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(rs,{zone:"groupBy",fields:t,label:x().label,placeholder:x().placeholder}),h&&e.jsx(rs,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(rs,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),u&&e.jsx(rs,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(Hl,{}),e.jsx(ql,{}),e.jsx($t,{}),e.jsx(qt,{}),e.jsx(Ht,{}),e.jsx(Wt,{})]})})]})]})}function Kl({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}){const[c,i]=A.useState(!1);s.useEditorStore(p=>p.showAIDialog);const d=s.useEditorStore(p=>p.card),{isLoading:u,isFetching:m,refetch:h}=s.useDashboardCardQuery(d),x=a.length>0||r.length>0||l.length>0,{setShowAIDialog:g}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(d);return A.useEffect(()=>{m||i(!1)},[m]),e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx(Rl,{selectedChart:t,onChartChange:n}),e.jsx(Bl,{selectedChart:t,onChartChange:n})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsxs("div",{className:s.cn("invisible flex gap-2",{visible:x||b}),children:[e.jsx(xs,{}),e.jsx(s.Button,{disabled:u||m,onClick:()=>{i(!0),h()},className:"h-8 shrink-0",size:"sm",variant:"secondary",children:c?e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}):e.jsx(s.RefreshCcw,{className:"h-4 w-4"})})]})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(Wl,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Ql({initialFilters:t,availableFields:n}={}){const[a,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(N=>N.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=n||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=N=>{const S=v=>{if(v.id===N){const k=i[0]||d,C=s.getDataType(k.dataType)==="date";return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:k,operator:C?"between":"=",value:C?[]:""}]}}return{...v,groups:v.groups.map(S)}};r(S(a))},m=N=>{const S=v=>{if(v.id===N){const k=i[0]||d,C=s.getDataType(k.dataType)==="date";return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:k,operator:C?"between":"=",value:C?[]:""}],groups:[]}]}}return{...v,groups:v.groups.map(S)}};r(S(a))},h=(N,S)=>{const v=k=>k.id===N?{...k,conditions:k.conditions.filter(C=>C.id!==S)}:{...k,groups:k.groups.map(v)};r(v(a))},x=(N,S)=>{const v=k=>k.id===N?{...k,groups:k.groups.filter(C=>C.id!==S)}:{...k,groups:k.groups.map(v)};r(v(a))},g=(N,S,v,k)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const C=F=>F.id===N?{...F,conditions:F.conditions.map(T=>T.id===S?{...T,[v]:k}:T)}:{...F,groups:F.groups.map(C)};r(C(a))},b=(N,S,v)=>{const k=C=>C.id===N?{...C,conditions:C.conditions.map(F=>F.id===S?{...F,...v}:F)}:{...C,groups:C.groups.map(k)};r(k(a))},p=(N,S)=>{const v=k=>k.id===N?{...k,logicalOperator:S}:{...k,groups:k.groups.map(v)};r(v(a))},j=(N,S)=>{const v=k=>k.id===N?{...k,negate:S}:{...k,groups:k.groups.map(v)};r(v(a))},f=(N,S,v)=>{const k=C=>C.id===N?{...C,conditions:s.arrayMove(C.conditions,S,v)}:{...C,groups:C.groups.map(k)};r(k(a))},y=(N,S,v)=>{const k=C=>C.id===N?{...C,groups:s.arrayMove(C.groups,S,v)}:{...C,groups:C.groups.map(k)};r(k(a))},I=N=>{if(!N||N.conditions.length===0&&N.groups.length===0)return"-- No filters defined";const S=k=>{let C="";typeof k.field=="object"?C=k.field.entityName?`${k.field.entityName}.${k.field.name}`:k.field.name:C=String(k.field);const F=k.operator;let T=k.value;if(k.field.dataType==="string"&&!["in","not in"].includes(k.operator))typeof T=="string"?T=`'${T}'`:Array.isArray(T)&&(T=`'${T.join(", ")}'`);else if(k.field.dataType==="date"||k.field.dataType==="datetime"||k.field.dataType==="timestamp")if(k.operator==="between"&&Array.isArray(T)&&T.length===2){const B=T[0]?`'${T[0]}'`:"NULL",E=T[1]?`'${T[1]}'`:"NULL";return`${C} BETWEEN ${B} AND ${E}`}else if((k.operator==="in"||k.operator==="not in")&&Array.isArray(T)){const B=T.map(E=>E?`'${E}'`:"NULL").join(", ");return`${C} ${F} (${B})`}else typeof T=="string"||T instanceof Date?T=`'${T}'`:Array.isArray(T)&&T.length>0&&(T=`'${T[0]}'`);else if(["in","not in"].includes(k.operator)){let B=[];Array.isArray(T)?B=T.map(E=>typeof E=="string"?`'${E}'`:String(E)):typeof T=="string"?B=T.split(",").map(E=>{const w=E.trim();return k.field.dataType==="string"?`'${w}'`:w}):typeof T=="number"&&(B=[String(T)]),T=`(${B.join(", ")})`}switch(F){case"contains":return typeof T=="string"?`${C} LIKE '%${T.replace(/'/g,"")}'`:`${C} LIKE '%${String(T)}'`;case"startsWith":return typeof T=="string"?`${C} LIKE '${T.replace(/'/g,"")}%'`:`${C} LIKE '${String(T)}%'`;case"endsWith":return typeof T=="string"?`${C} LIKE '%${T.replace(/'/g,"")}'`:`${C} LIKE '%${String(T)}'`;case"isNull":return`${C} IS NULL`;case"isNotNull":return`${C} IS NOT NULL`;default:return`${C} ${F} ${T}`}},v=k=>{const C=k.conditions.map(S),F=k.groups.map(w=>v(w)),T=[...C,...F].filter(Boolean);if(T.length===0)return"";const B=T.join(` ${k.logicalOperator} `),E=T.length>1?`(${B})`:B;return k.negate?`NOT ${E}`:E};return v(N)},D=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:u,addGroup:m,removeCondition:h,removeGroup:x,updateCondition:g,updateConditionFields:b,updateGroupOperator:p,updateGroupNegate:j,reorderConditions:f,reorderGroups:y,generateSQLPreview:I,hasAnyFilters:D}}function Jl({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 Xl=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"})}},Zl=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function eo({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[o,c]=A.useState(!1),i=A.useMemo(()=>{const d={};return a.forEach(u=>{const m=Zl(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[a]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Jl,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Xl(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((x,g)=>e.jsxs(s.CommandItem,{value:x.id,onSelect:()=>{n(x),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===x.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:x.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:x.description&&e.jsx("span",{children:x.description})})]})]},x.id+g))]},`${d}-${m}`))},d))})]})})]})}function zs(t){var p;const n=s.useEditorStore(j=>j.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(j=>j.card.config),o=l==null?void 0:l.joinPlan,c={...t,alias:t.name,label:"value",role:"groupby"},i={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...c,role:"sortby",direction:"asc"},u={joinPlan:o,groupByColumns:[c],metricColumns:[i],sortByColumns:[d]},m=((p=n.dataSource)==null?void 0:p.connectionId)||n.connectionId,{data:h,isPending:x,error:g}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:m,cardConfig:u,cardDataSource:n.dataSource})}catch(j){console.log(t),console.error("error",j)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:x,error:g}}function so({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[o,c]=Oe.useState(!1),{filterValues:i}=zs(t),d=m=>{a(n.filter(h=>h!==m))},u=m=>{n.includes(m)?a(n.filter(h=>h!==m)):a([...n,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(m=>{const h=i.find(x=>x.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:x=>{x.key==="Enter"&&d(m)},onMouseDown:x=>{x.preventDefault(),x.stopPropagation()},onClick:x=>{x.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function to({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=zs(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:o.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function ao({value:t,operator:n,onChange:a,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),o=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=A.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(u&&m)return{from:u,to:m}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:m}}}},[t,n]),i=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),a([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),a([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const no=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ro=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],lo=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],oo=["=","!=","isNull","isNotNull"],io=["between","isNull","isNotNull"],co={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null"};function at(t){return co[t]||s.titleCase(t)}function uo(t){switch(t){case"string":return ro;case"number":return lo;case"boolean":return oo;case"date":return io;default:return no}}function Xt({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:x,transition:g,isDragging:b}=s.useSortable({id:t.id}),{isPending:p,error:j}=zs(t.field),f={transform:s.CSS.Transform.toString(x),transition:g};return e.jsxs("div",{ref:h,style:f,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:y=>c(a,y),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(eo,{value:t.field,onValueChange:y=>{const I=y,D=s.getDataType(I.dataType)==="date";d(a,t.id,{field:I,value:"",operator:D?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:y=>{y==="in"||y==="not in"?d(a,t.id,{operator:y,value:[]}):y==="isNull"||y==="isNotNull"?d(a,t.id,{operator:y,value:null}):d(a,t.id,{operator:y,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?at(t.operator):""})}),e.jsx(s.SelectContent,{children:uo(s.getDataType(t.field.dataType)).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y,children:at(y)},y))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?p?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):j?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(so,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(y=>typeof y=="string")?t.value:[],onChange:y=>d(a,t.id,{value:y}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:y=>d(a,t.id,{value:y.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(to,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:y=>d(a,t.id,{value:y}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:y=>d(a,t.id,{value:y==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(ao,{value:t.value,operator:t.operator,onChange:y=>d(a,t.id,{value:y}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:y=>l(a,t.id,"value",y.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function mo({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:x,availableFields:g,renderFilterGroup:b,updateConditionFields:p}){const{attributes:j,listeners:f,setNodeRef:y,transform:I,transition:D,isDragging:N}=s.useSortable({id:t.id}),S={transform:s.CSS.Transform.toString(I),transition:D},v=C=>{const{active:F,over:T}=C;if(T&&F.id!==T.id){const B=t.conditions.findIndex(w=>w.id===F.id),E=t.conditions.findIndex(w=>w.id===T.id);B!==-1&&E!==-1&&u(t.id,B,E)}},k=C=>{const{active:F,over:T}=C;if(T&&F.id!==T.id&&a){const B=t.groups.findIndex(w=>w.id===F.id),E=t.groups.findIndex(w=>w.id===T.id);B!==-1&&E!==-1&&m(a,B,E)}};return e.jsxs("div",{ref:y,style:S,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${N?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...j,...f,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:C=>r(t.id,C),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&o(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:v,children:e.jsx(s.SortableContext,{items:t.conditions.map(C=>C.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((C,F)=>e.jsx(Xt,{condition:C,index:F,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:p},C.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:k,children:e.jsx(s.SortableContext,{items:t.groups.map(C=>C.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(C=>b(C,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function ho({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:x,updateConditionFields:g,updateGroupOperator:b,updateGroupNegate:p,reorderConditions:j,reorderGroups:f,generateSQLPreview:y,hasAnyFilters:I,setCurrentFilters:D}=Ql({initialFilters:t,availableFields:n}),N=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[S,v]=A.useState(!1),k=(T,B,E)=>{const w=M=>M.id===T?{...M,conditions:M.conditions.map(L=>L.id===B?{...L,field:E,dataType:E.dataType}:L)}:{...M,groups:M.groups.map(w)};D(w(o))},C=(T,B=0,E)=>B===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:N,collisionDetection:s.closestCenter,onDragEnd:w=>{const{active:M,over:L}=w;if(L&&M.id!==L.id){const O=T.conditions.findIndex(P=>P.id===M.id),R=T.conditions.findIndex(P=>P.id===L.id);O!==-1&&R!==-1&&j(T.id,O,R)}},children:e.jsx(s.SortableContext,{items:T.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:T.conditions.map((w,M)=>e.jsx(Xt,{condition:w,index:M,groupId:T.id,groupLogicalOperator:T.logicalOperator,onUpdateCondition:x,onUpdateField:k,onRemoveCondition:m,onUpdateGroupOperator:b,availableFields:c,updateConditionFields:g},w.id))})}),e.jsx(s.DndContext,{sensors:N,collisionDetection:s.closestCenter,onDragEnd:w=>{const{active:M,over:L}=w;if(L&&M.id!==L.id){const O=T.groups.findIndex(P=>P.id===M.id),R=T.groups.findIndex(P=>P.id===L.id);O!==-1&&R!==-1&&f(T.id,O,R)}},children:e.jsx(s.SortableContext,{items:T.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:T.groups.map(w=>C(w,B+1,T.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(T.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),S&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(T.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},T.id):e.jsx(mo,{group:T,depth:B,parentGroupId:E,onUpdateGroupOperator:b,onUpdateGroupNegate:p,onRemoveGroup:h,onUpdateCondition:x,onUpdateField:k,onRemoveCondition:m,onReorderConditions:j,onReorderGroups:f,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:C,updateConditionFields:g},T.id),F=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):C(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{id:"advanced-mode",checked:S,onCheckedChange:T=>v(T)}),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)"})]})}),I&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:y(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),F>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(I?o:null),children:"Apply Filters"})]})]})}function xo({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=u=>{a(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(ho,{filters:n,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function po({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[l,o]=A.useState(null),c=s.useEditorStore(b=>b.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],u=A.useCallback(b=>b.startsWith("card-")?null:b.startsWith("source-")||n.find(p=>p.id===b)?"source":a("groupBy").find(p=>p.id===b)?"groupBy":a("metrics").find(p=>p.id===b)?"metrics":a("pivotBy").find(p=>p.id===b)?"pivotBy":a("sortBy").find(p=>p.id===b)?"sortBy":null,[n,a]),m=A.useCallback(b=>{o(b.active.id)},[]),h=A.useCallback(b=>{const{active:p,over:j}=b;if(!j||!t){o(null);return}const f=p.id,y=j.id,I=u(f),D=u(y)||y;if(D==="sortBy"){if(I==="source"){const N=n.find(v=>v.id===f);if(!N){o(null);return}if(!(a("groupBy").some(v=>v.name===N.name&&v.qualifiedEntityName===N.qualifiedEntityName)||a("metrics").some(v=>v.name===N.name&&v.qualifiedEntityName===N.qualifiedEntityName))){o(null);return}}else if(I==="pivotBy"){o(null);return}else if(I!=="groupBy"&&I!=="metrics"&&I!=="sortBy"){o(null);return}}if(I==="source"&&D==="sortBy"){const N=[...n].find(k=>k.id===f);if(!N){o(null);return}const S=a("sortBy");if(s.fieldAlreadyExists(N,S)){o(null);return}const v=s.getNewField(N,"sortBy",S);o(null),r("sortBy",[...S,v]);return}if(I==="source"&&D!=="source"&&D!=="sortBy"){const N=[...n].find(C=>C.id===f);if(!N){o(null);return}const S=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(S.length>0){const C=S[0].qualifiedEntityName;if(!C){o(null);return}if(C!==N.qualifiedEntityName&&N.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(C,N.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const v=a(D);if(s.fieldAlreadyExists(N,v)){o(null);return}const k=s.getNewField(N,D,v);o(null),r(D,[...v,k]);return}if(I&&D&&I!=="source"&&D!=="source"&&I!==D){const N=a(I),S=a(D),v=N.find(F=>F.id===f);if(!v){o(null);return}const k=s.getNewField(v,D,S);if(o(null),D==="sortBy"){s.fieldAlreadyExists(v,S)||r(D,[...S,k]);return}const C=N.filter(F=>F.id!==f);r(I,C),r(D,[...S,k]);return}if(I&&D&&I===D&&I!=="source"){const N=a(I),S=N.findIndex(k=>k.id===f),v=N.findIndex(k=>k.id===y);if(S!==v){const k=s.arrayMove(N,S,v);r(I,k)}}o(null)},[t,n,a,r,u,i]),x=l?d.find(b=>b.id===l):null;return{activeId:l,activeField:x,handleDragStart:m,handleDragEnd:h}}function fo({dashboardFilterCount:t=0,cardFilterCount:n=0,clickFilterCount:a=0,onClick:r,className:l,showIcon:o=!0}){const c=t+n+a,i=c>0,d=t>0,u=n>0,m=a>0,h=e.jsxs(e.Fragment,{children:[o&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),x=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",l),children:h});return i?e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:x}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"p-2 text-xs",children:e.jsxs("div",{className:"space-y-1.5",children:[d&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-purple-500"}),e.jsxs("span",{children:[t," Dashboard filter",t!==1?"s":""]})]}),u&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),e.jsxs("span",{children:[n," Card filter",n!==1?"s":""]})]}),m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-gray-500"}),e.jsxs("span",{children:[a," Click filter",a!==1?"s":""]})]})]})})]})}):x}function go({activeView:t,onViewChange:n}){const a=s.useEditorStore(c=>c.card),{config:r}=A.useContext(s.SemaphorContext).tokenProps,l=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:o}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:c=>n(c),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),a.type!=="kpi"&&l&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",o&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:o?"Error":"Info"})]})})}const jo=[{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 bo(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=A.useState(!1),[l,o]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:jo.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function vo({isOpen:t,onClose:n}){const a=xt(n,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=A.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function yo({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:l,filterCount:o,activeCard:c,columns:i,columnsLoading:d,columnsError:u}){var q;const m=s.useEditorStore(Q=>Q.card),h=s.useDashboardStore(Q=>Q.filterValues),x=(h==null?void 0:h.length)||0,{updateCardConfig:g,setCard:b,updateCardInFrame:p,setCardId:j,setShowAIDialog:f}=s.useEditorActions(),{updateCardId:y}=s.useDashboardActions(),[I,D]=A.useState(null),N=s.useEditorStore(Q=>Q.showAIDialog),[S,v]=A.useState(!1),[k,C]=A.useState(!1),[F,T]=A.useState(null),{isConsoleMode:B}=s.useDashboardPreferences(),{config:E}=A.useContext(s.SemaphorContext).tokenProps,w=(E==null?void 0:E.showInfoTab)!==!1,M=s.useEditorStore(Q=>{var _;return((_=Q.card.customCardPreferences)==null?void 0:_.url)&&Q.card.type==="custom"}),{data:L,errorMessage:O,isLoading:R,isFetching:P,errorSql:G,pagination:J}=s.useDashboardCardQuery(c),V=(Q,_)=>{const te={...c,paginationConfig:{page:Q+1,pageSize:_}};b(te),p(te)};function K(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(m.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(h||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(c.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",i.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:d?"Loading...":u?"Error loading columns":JSON.stringify(i.slice(0,5),null,2)})]})]})]})}const $=Q=>{if(!m.config)return;if(!Q.length){g(m.id,{...m.config,sortByColumns:[]});return}const _=m.config,te=Q.map(({id:re,desc:he})=>{var ae,oe;const ge=(ae=_.metricColumns)==null?void 0:ae.find(de=>de.label===re),z=(oe=_.groupByColumns)==null?void 0:oe.find(de=>de.label===re),Z=ge||z;return Z?{id:s.getFieldId("sortBy",Z),name:Z.name,dataType:Z.dataType,label:Z.label,qualifiedEntityName:Z.qualifiedEntityName,entityId:Z.entityId,entityName:Z.entityName,entityType:Z.entityType,role:"sortby",direction:he?"desc":"asc"}:null}).filter(re=>re!==null);g(m.id,{..._,sortByColumns:te})},X=A.useMemo(()=>{var Q,_;return(_=(Q=m.config)==null?void 0:Q.sortByColumns)==null?void 0:_.map(te=>({id:te.label,desc:te.direction==="desc"}))},[(q=m.config)==null?void 0:q.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[a&&K(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&N&&e.jsx(Bt,{variant:"outline"}),e.jsx(go,{activeView:t,onViewChange:n}),l&&e.jsx(fo,{dashboardFilterCount:x,cardFilterCount:o,onClick:l,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(bo,{})}),N&&e.jsx(xs,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end"),children:[t==="chart"&&e.jsx(Pt,{}),!N&&e.jsx(s.IconButton,{onClick:()=>f(!N),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!S&&M&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>v(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(zt,{})}),t==="table"&&(L==null?void 0:L.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:(L==null?void 0:L.records)||[],paginationMetadata:J,onPaginationChange:V,isLoading:R||P,onSortChange:$,sortState:X})}),t==="info"&&w&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[B&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:m.id,onSave:Q=>{const _=s.sanitizeCardId(Q);if(!_){D("Card ID cannot be empty");return}const te=y(m.id,_);if(te.success){j(_);const re={...m,id:_};b(re),p(re),D(null),s.ue.success("Card ID updated successfully")}else D(te.error||"Failed to update Card ID"),s.ue.error(te.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:m.id,className:"h-5 w-5"})]}),I&&e.jsx("p",{className:"text-xs text-destructive",children:I})]}),O||G?e.jsx(Et,{error:O,errorSql:G,onSendFeedback:()=>{const Q=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:m.config,dataSource:c.dataSource,dashboardFilters:h,errorMessage:O,errorSql:G,generatedSql:L==null?void 0:L.sql});T(Q),C(!0)}}):e.jsxs(e.Fragment,{children:[(L==null?void 0:L.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(It,{sql:L==null?void 0:L.sql,error:O,errorSql:G})]})]})})]}),e.jsx(vo,{isOpen:S,onClose:()=>v(!1)}),F&&e.jsx(s.FeedbackDialog,{open:k,onOpenChange:C,feedbackData:F})]})]})}function No({activeField:t}){const[n,a]=A.useState(!0);return A.useEffect(()=>{t&&a(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(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 Co=()=>{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 So(){var G,J;const[t,n]=A.useState("chart"),[a,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(V=>V.showAIDialog),u=s.useDashboardStore(V=>V.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(V=>V.card.type);A.useEffect(()=>Co(),[]);const x=()=>{o(!0)},g=V=>{m(V)},b=s.useEditorStore(V=>V.frame),p=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.activeTabCardId),s.useEditorStore(V=>V.actions.getAvailableFields);const{addCard:j,removeCard:f,updateCard:y,setActiveCard:I,updateFilters:D}=s.useEditorActions(),{columns:N=[],isLoading:S,error:v}=s.useColumns(),k=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),C=p,{getFieldsForContainer:F,setFieldsForContainer:T}=Fs(C),{activeField:B,handleDragStart:E,handleDragEnd:w}=po({activeCardId:b.activeCardId,sourceFields:N,getFieldsForContainer:F,setFieldsForContainer:T}),M=(V,K)=>{K&&D(V,K)},L=V=>{var K;y(V,{config:{...(K=b.cards.find($=>$.id===V))==null?void 0:K.config,filters:void 0}})},O=N,R=V=>{if(!V)return 0;let K=V.conditions.length;return V.groups.forEach($=>{K+=R($)}),K},P=R(((G=C==null?void 0:C.config)==null?void 0:G.filters)||null);return e.jsxs(s.DndContext,{sensors:k,collisionDetection:s.closestCenter,onDragStart:E,onDragEnd:w,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Al,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Kl,{selectedChart:h,onChartChange:g,groupByFields:F("groupBy"),pivotByFields:F("pivotBy"),metricsFields:F("metrics"),sortByFields:F("sortBy")}),e.jsx(yo,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:x,filterCount:P,activeCard:C,dataSourceState:p.dataSource||s.EMPTY_DATA_SOURCE,columns:N,columnsLoading:S,columnsError:v,getFieldsForContainer:F,cards:b.cards,activeCardId:b.activeCardId,addCard:j,setActiveCard:I})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),C&&e.jsx(xo,{cardId:C.id,filters:((J=C.config)==null?void 0:J.filters)||null,onFiltersChange:M,onClearFilters:L,availableFields:O,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(No,{activeField:B||null})})]})}function wo({authToken:t,onSave:n,onClose:a}){const r=A.useRef(null),l=s.useEditorStore(T=>T.showAIDialog),o=s.useEditorStore(T=>T.isDevMode),c=s.useAssistantLayoutStore(T=>T.setFullscreen),i=s.useAssistantLayoutStore(T=>T.setPanelOpen),d=s.useAssistantLayoutStore(T=>T.setContainer),u=s.useAssistantPanel("editor"),m=s.useFullscreenAssistant(),h=s.useAssistantContainer("editor"),x=m==="editor",g=A.useCallback(T=>{d("editor",T)},[d]),{setAuthToken:b}=s.useDashboardActions(),{setShowAIDialog:p,setOnSave:j,setOnClose:f}=s.useEditorActions(),{setActiveAssistantType:y}=s.useAIActions(),{handleDragOver:I,handleDragEnd:D,handleDragStart:N,handleDragCancel:S,sensors:v}=Xn();A.useEffect(()=>{n&&j(n),a&&f(a)},[n,j,a,f]),A.useEffect(()=>{t&&t.accessToken&&b(t)},[t,b]),A.useEffect(()=>{var T,B;l?((T=r.current)==null||T.resize(40),i("editor",!0),y("editor")):((B=r.current)==null||B.resize(0),i("editor",!1),m==="editor"&&c(null),y(null))},[l,i,y,c,m]);function k(T){T<1?(p(!1),i("editor",!1),m==="editor"&&c(null),y(null)):(l||(p(!0),y("editor")),u.isOpen||i("editor",!0))}function C(){return e.jsxs(e.Fragment,{children:[e.jsx(kt,{type:"main"}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",x&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(gl,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:k,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Xs,{isFullscreen:x,onFullscreenChange:T=>c(T?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:g,className:s.cn("absolute inset-0",!x&&"pointer-events-none")})]})]})}function F(){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",x&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(So,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:k,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Xs,{isFullscreen:x,onFullscreenChange:T=>c(T?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:g,className:s.cn("absolute inset-0",!x&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:v,onDragStart:N,onDragEnd:D,onDragOver:I,onDragCancel:S,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:C()})}):F()})}function Do(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(c=>c.actions),a=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),n(!1))}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(wo,{onSave:l,onClose:o})})}function To({column:t}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{className:"shrink-0",asChild:!0,children:s.isTextDataType(t.data_type)?e.jsx(s.TextIcon,{className:"size-3 text-muted-foreground"}):s.isNumberDataType(t.data_type)?e.jsx(Me,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(ze,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(pa,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})})}function ko(){const t=s.useEditorStore(o=>o.selectedDatabaseName),n=s.useEditorStore(o=>o.selectedTableName),a=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=Ls();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(o.column_name)&&i.table===n&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(To,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function Eo({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(we,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Me,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(ze,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx($e,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Xe,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ss,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(we,{className:"h-3 w-3"})})}function Io(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useDashboardStore(f=>f.dashboard.filters)||[],{assignFilter:o}=Ls(),c=s.useEditorStore(f=>f.card.dataSource),{columns:i=[],isLoading:d,error:u}=s.useColumns(),m=i.filter(f=>f.name.toLowerCase().includes(t.toLowerCase())||f.dataType.toLowerCase().includes(t.toLowerCase())||f.label&&f.label.toLowerCase().includes(t.toLowerCase())),h=f=>{const y=s.getDataType(f.dataType);return y==="number"?"metrics":(["date","string","boolean"].includes(y),"dimensions")},x=a==="all"?m:m.filter(f=>h(f)===a),g=m.filter(f=>h(f)==="dimensions").length,b=m.filter(f=>h(f)==="metrics").length,p=f=>{const y={column_name:f.name,data_type:f.dataType,label:f.label,description:f.description};o(y,"dashboard",f)};if(d)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(u)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:u.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const j=m.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:f=>n(f.target.value)})]}),j&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:f=>r(f),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:b})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[x.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),x.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),x.map(f=>{const y=l==null?void 0:l.some(I=>{var D;return I.title===f.name||((D=I.column)==null?void 0:D.includes(f.name))});return e.jsx("div",{onClick:()=>p(f),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":y}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Eo,{dataType:f.dataType}),e.jsx("span",{children:f.label||f.name})]})},f.id)})]})]})}function Ao(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),n=s.useCurrentActiveCard(),a=n&&((r=n.dataSource)==null?void 0:r.selectedEntities)&&n.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:a?e.jsx(Io,{}):e.jsx(kt,{type:"filter",ColumnsComponent:()=>e.jsx(ko,{})})})]})}function Mo(){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 Lo(){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(Mo,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Ao,{})})]})}function Ro(){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 Zt(){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 Oo=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 Fo({visual:t,isDeleting:n,isDuplicating:a,onAddVisual:r,onOpenVisual:l,onEditDetails:o,onDeleteClick:c,onDuplicateVisual:i,onShareVisual:d,formatDate:u}){var N,S,v,k;const{selectVisual:m}=s.useManagementActions(),h=s.useIsVisualSelected(t.id),x=Oo(t.id),{isConsoleMode:g}=s.useDashboardPreferences(),b=A.useRef(null),[p,j]=A.useState(!1),[f,y]=A.useState(!1);A.useEffect(()=>{a?(j(!0),y(!0)):f&&(j(!1),y(!1))},[a,f]),A.useEffect(()=>{x&&b.current&&b.current.scrollIntoView({behavior:"smooth",block:"center"})},[x]);const I=()=>e.jsx(ms,{className:"h-4 w-4"}),D=()=>{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",x?"border-purple-500":h&&"border-primary"),onClick:D,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children:I()}),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:(N=t.description)!=null&&N.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",h&&"visible"),onClick:C=>C.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:C=>{C.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:C=>{C.stopPropagation(),o==null||o(t)},title:"Edit details",children:e.jsx(os,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:p,onOpenChange:j,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),r(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),l==null||l(t)},children:[e.jsx(wa,{className:"mr-2 h-3 w-3"}),"Open"]}),e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.preventDefault(),C.stopPropagation(),i(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),o==null||o(t)},children:[e.jsx(os,{className:"mr-2 h-3 w-3"}),"Edit details"]}),e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),d(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),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:[(((S=t.ownership.createdBy)==null?void 0:S.type)==="tenant"||((v=t.ownership.createdBy)==null?void 0:v.type)==="organization"&&g)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((k=t.ownership.createdBy)==null?void 0:k.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 ea({open:t,resourceLabel:n,initialTitle:a,initialDescription:r="",onClose:l,onSave:o,isSaving:c=!1}){const[i,d]=A.useState(a),[u,m]=A.useState(r??"");A.useEffect(()=>{t&&(d(a),m(r??""))},[t,a,r]);const h=x=>{x.preventDefault();const g=i.trim();g&&o({title:g,description:u.trim()})};return e.jsx(s.Dialog,{open:t,onOpenChange:x=>x?null:l(),children:e.jsx(s.DialogContent,{className:"sm:max-w-md",children:e.jsxs("form",{onSubmit:h,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:i,onChange:x=>d(x.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:x=>m(x.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:c,children:"Cancel"}),e.jsx(s.Button,{type:"submit",disabled:c||!i.trim(),children:c?"Saving...":"Save changes"})]})]})})})}function Bo(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(!1),[m,h]=A.useState(null),[x,g]=A.useState(!1),[b,p]=A.useState(null),[j,f]=A.useState(null),[y,I]=A.useState(null),{selectVisual:D}=s.useManagementActions(),{handleEditLibraryVisual:N,handleAddLibraryVisual:S}=_e(),{resources:v,isLoading:k,isError:C,createResource:F,updateResource:T,deleteResource:B,duplicateResource:E,isCreating:w,isDeleting:M}=s.useVisualManagement(()=>{g(!1),p(null)},z=>{r(!1),o(""),i(""),z&&(D(z),N(z))});s.useCurrentUserInfo();const L=v.filter(z=>{var Z,ae;return((Z=z==null?void 0:z.title)==null?void 0:Z.toLowerCase().includes(t.toLowerCase()))||((ae=z==null?void 0:z.description)==null?void 0:ae.toLowerCase().includes(t.toLowerCase()))}),O=z=>new Date(z).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),R=()=>{l.trim()&&F({title:l,description:c,isPrivate:!1})},P=z=>{p(z),g(!0)},G=()=>{b&&B(b.id)},{startUpdating:J,stopUpdating:V,isUpdating:K}=s.useResourceUpdateState(),$=(z,Z,ae)=>{var xe;const oe=Object.fromEntries(Object.entries(Z).filter(([,W])=>W!==void 0));if(Object.keys(oe).length===0){(xe=ae==null?void 0:ae.onSuccess)==null||xe.call(ae);return}const de=Object.keys(oe),ue=de.length===1?de[0]:void 0;J(z,ue),T({resourceId:z,data:oe},{onSuccess:()=>{var W;V(z,ue),(W=ae==null?void 0:ae.onSuccess)==null||W.call(ae)},onError:()=>{var W;V(z,ue),(W=ae==null?void 0:ae.onError)==null||W.call(ae)}})},X=z=>{f(z),E(z,{onSettled:()=>f(null)})},q=z=>{N(z)},Q=z=>{S(z)},_=z=>{const Z=v.find(ae=>ae.id===z);Z&&T({resourceId:z,data:{isPrivate:!Z.isPrivate}})},te=z=>{h(z),u(!0)},re=z=>{I(z)},he=()=>{I(null)},ge=({title:z,description:Z})=>{if(!y)return;const ae={};z!==y.title&&(ae.title=z),(y.description||"")!==Z&&(ae.description=Z),$(y.id,ae,{onSuccess:()=>{I(null)}})};return k?e.jsx(Zt,{}):C?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[a&&e.jsx("div",{children:e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:z=>o(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:z=>i(z.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:R,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||w,children:w?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:w,children:"Cancel"})]})]})]})}),v&&v.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:z=>n(z.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:L.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(ms,{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"]})]}):L.map(z=>e.jsx(Fo,{visual:z,onAddVisual:Q,onOpenVisual:q,onEditDetails:re,onDeleteClick:P,onDuplicateVisual:X,onTogglePrivacy:_,onShareVisual:te,isDeleting:M,isDuplicating:j===z.id,formatDate:O},z.id))})}),d&&m&&e.jsx(hs,{resource:m,resourceType:s.ResourceType.VISUAL,onClose:()=>{u(!1),h(null)}}),y&&e.jsx(ea,{open:!!y,resourceLabel:"Visual",initialTitle:y.title||"",initialDescription:y.description||"",onClose:he,onSave:ge,isSaving:K(y.id)}),e.jsx(s.AlertDialog,{open:x,onOpenChange:z=>{!z&&M||(g(z),z||p(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',b==null?void 0:b.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:M,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:z=>{z.preventDefault(),z.stopPropagation(),G()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:M,children:[M?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"}),M?"Deleting...":"Delete"]})]})]})}),!a&&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 Po({dashboard:t,isDeleting:n,isDuplicating:a,onLoadDashboard:r,onEditDetails:l,onDeleteClick:o,onDuplicateDashboard:c,onShareDashboard:i,formatDate:d,onDashboardItemClick:u}){var I,D,N,S;const{selectDashboard:m}=s.useManagementActions(),h=s.useIsDashboardSelected(t.id),{isConsoleMode:x}=s.useDashboardPreferences(),[g,b]=A.useState(!1),[p,j]=A.useState(!1);A.useEffect(()=>{a?(b(!0),j(!0)):p&&(b(!1),j(!1))},[a,p]);const f=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),y=()=>{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",h&&"border-primary"),onClick:y,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:f()}),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:(I=t.description)!=null&&I.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:v=>v.stopPropagation(),children:[t.permissions.canEdit&&e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:v=>{v.stopPropagation(),l==null||l(t)},title:"Edit details",children:e.jsx(os,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:b,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.preventDefault(),v.stopPropagation(),c(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:v=>{v.stopPropagation(),l==null||l(t)},children:[e.jsx(os,{className:"mr-2 h-3 w-3"}),"Edit details"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:v=>{v.stopPropagation(),i(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:v=>{v.stopPropagation(),o(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"||((N=t.ownership.createdBy)==null?void 0:N.type)==="organization"&&x)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((S=t.ownership.createdBy)==null?void 0:S.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:d(t.lastModified)})]})]})]})]})]})]})},t.id)}function zo({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function Vo(t){const{onLoadDashboard:n,onEditDashboard:a,onDashboardItemClick:r}=t,[l,o]=A.useState(""),[c,i]=A.useState(!1),[d,u]=A.useState(""),[m,h]=A.useState(""),[x,g]=A.useState(!1),[b,p]=A.useState(null),[j,f]=A.useState(!1),[y,I]=A.useState(null),[D,N]=A.useState(null),[S,v]=A.useState(null),k=s.useManagementStore(Y=>Y.lastSelectedDashboard),C=s.useManagementStore(Y=>Y.selectedDashboard),F=s.useManagementStore(Y=>Y.actions.selectDashboard),T=s.useManagementStore(Y=>Y.actions.updateSelectedDashboard),B=s.useManagementStore(Y=>Y.actions.clearSelectedDashboard),{tokenProps:E,id:w}=s.useSemaphorContext(),{permissions:M}=s.useRoleAwareDisplayPreferences(),{resources:L,isLoading:O,isError:R,createResource:P,updateResource:G,deleteResource:J,duplicateResource:V,isCreating:K,isDeleting:$,refetch:X}=s.useDashboardManagement(()=>{f(!1);const Y=y==null?void 0:y.id;I(null),(C==null?void 0:C.id)===Y&&(!(E!=null&&E.dashboard_id)&&!w?B():k&&k.id!==Y&&F(k))},Y=>{i(!1),u(""),h(""),Y&&(F(Y),r==null||r(Y.id),X().then(le=>{var ce;const ie=(((ce=le.data)==null?void 0:ce.dashboards)||[]).find(je=>je.id===Y.id);if(ie){const je=s.useManagementStore.getState().selectedDashboard;(je==null?void 0:je.id)===ie.id&&T(ie)}}))}),{currentUser:q}=s.useCurrentUserInfo(),Q=L.filter(Y=>{var le,se;return((le=Y==null?void 0:Y.title)==null?void 0:le.toLowerCase().includes(l.toLowerCase()))||((se=Y==null?void 0:Y.description)==null?void 0:se.toLowerCase().includes(l.toLowerCase()))}),_=Y=>new Date(Y).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),te=()=>{d.trim()&&P({title:d,description:m,isPrivate:!1})},re=Y=>{n==null||n(Y)},he=Y=>{I(Y),f(!0)},ge=()=>{y&&J(y.id)},z=Y=>{N(Y),V(Y,{onSettled:()=>N(null)})},{startUpdating:Z,stopUpdating:ae,isUpdating:oe}=s.useResourceUpdateState(),de=(Y,le,se)=>{var Ee;const ie=Object.fromEntries(Object.entries(le).filter(([,be])=>be!==void 0));if(Object.keys(ie).length===0){(Ee=se==null?void 0:se.onSuccess)==null||Ee.call(se);return}const ce=Object.keys(ie),je=ce.length===1?ce[0]:void 0;Z(Y,je),G({resourceId:Y,data:ie},{onSuccess:()=>{var be;ae(Y,je),(be=se==null?void 0:se.onSuccess)==null||be.call(se)},onError:()=>{var be;ae(Y,je),(be=se==null?void 0:se.onError)==null||be.call(se)}})},ue=Y=>{const le=L.find(se=>se.id===Y);le&&G({resourceId:Y,data:{isPrivate:!le.isPrivate}})},xe=Y=>{p(Y),q==null||q.type,g(!0)},W=Y=>{a==null||a(Y.id),v(Y)},U=()=>{v(null)},ee=({title:Y,description:le})=>{if(!S)return;const se={};Y!==S.title&&(se.title=Y),(S.description||"")!==le&&(se.description=le),de(S.id,se,{onSuccess:()=>{v(null)}})};return O?e.jsx(Zt,{}):R?e.jsx(zo,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[M.canCreateDashboards&&c&&e.jsx("div",{children:e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:d,onChange:Y=>u(Y.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:m,onChange:Y=>h(Y.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:te,size:"sm",className:"h-7 text-xs",disabled:!d.trim()||K,children:K?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{i(!1),u(""),h("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:K,children:"Cancel"})]})]})]})}),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:l,onChange:Y=>o(Y.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:Q.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":M.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),M.canCreateDashboards&&!l&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>i(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Dashboard"]})]}):Q.map(Y=>e.jsx(Po,{dashboard:Y,isDeleting:$,isDuplicating:D===Y.id,onLoadDashboard:re,onEditDetails:W,onDeleteClick:he,onDuplicateDashboard:z,onTogglePrivacy:ue,onShareDashboard:xe,formatDate:_,onDashboardItemClick:r},Y.id))})}),x&&b&&e.jsx(hs,{resource:b,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{g(!1),p(null)}}),e.jsx(s.AlertDialog,{open:j,onOpenChange:Y=>{!Y&&$||(f(Y),Y||I(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 "',y==null?void 0:y.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:$,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),ge()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:$,children:[$?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"}),$?"Deleting...":"Delete"]})]})]})}),S&&e.jsx(ea,{open:!!S,resourceLabel:"Dashboard",initialTitle:S.title||"",initialDescription:S.description||"",onClose:U,onSave:ee,isSaving:oe(S.id)}),M.canCreateDashboards&&!c&&e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>i(!0),"aria-label":"Create dashboard",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function sa({isOpen:t,onClose:n,className:a,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(N=>N.dashboard);const{setDashboard:o,addSheet:c}=s.useDashboardStore(N=>N.actions),{currentUser:i}=s.useCurrentUserInfo(),d=i,{permissions:u}=s.useRoleAwareDisplayPreferences(),h=s.useSelectedDashboard()&&u.canAccessVisuals,x="dashboards",[g,b]=Bs("resource-management-active-tab",x),p=h?g:"dashboards",j=l==="overlay",f=xt(n,{enabled:t&&j}),y=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),I=N=>{},D=N=>{console.log("Editing dashboard:",N)};return e.jsx(s.TooltipProvider,{children:(!j||t)&&e.jsxs("div",{ref:f,className:y,children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border p-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:d&&e.jsxs(e.Fragment,{children:[e.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:d.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:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email}),d.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(d.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",d.id]})]})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"text-sm font-medium text-foreground",children:d.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(za,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:p,onValueChange:h?b:void 0,className:"flex h-9 grow flex-col",children:[h&&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(Vo,{onLoadDashboard:I,onEditDashboard:D,onDashboardItemClick:r})}),h&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 px-4 py-4",children:e.jsx(Bo,{})})]})})]})})}function _o({showControls:t=!1,showFooter:n=!0,...a}){const r=s.useDashboardStore(x=>x.isDashboardPanelOpen);s.useDashboardStore(x=>x.isVisualEditing);const l=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),o=20,c=20,i=30,d=r,u=A.useRef(null),m=A.useRef(null);A.useEffect(()=>{u.current&&m.current&&(r?(u.current.resize(o),m.current.resize(100-o)):(u.current.resize(0),m.current.resize(100)))},[r]);const{preferences:h}=a;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:h,children:[e.jsx(Ro,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(qn,{}),e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",className:"flex grow overflow-hidden",children:[e.jsx(s.ResizablePanel,{ref:u,className:s.cn("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?o:0,minSize:d?c:0,maxSize:d?i:0,children:e.jsx(sa,{isOpen:r,onClose:()=>l(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{withHandle:d,className:s.cn("w-1",{"w-0":!d})}),e.jsx(s.ResizablePanel,{ref:m,className:"flex min-w-0 flex-1",defaultSize:d?100-o:100,minSize:d?40:100,children:e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(Do,{}),e.jsx(Lo,{})]})})]})]})]})})]})})}exports.AdvancedModeToggle=Dt;exports.DashboardPlus=_o;exports.ResourceManagementPanel=sa;exports.ScheduleDashboard=dt;exports.SelectComponent=Ge;exports.ShareDialog=hs;exports.VisualBadge=yt;exports.VisualEditingControls=wt;exports.cleanCard=ct;exports.getDashbaordStateWithoutData=is;