react-semaphor 0.0.538 → 0.0.540

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-BuxOBuu9.js"),M=require("react");require("react-dom");function ln(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const ye=ln(M);/**
1
+ "use strict";const e=require("react/jsx-runtime"),s=require("./index-C4HtFfvy.js"),M=require("react");require("react-dom");function ln(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const ye=ln(M);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -398,7 +398,7 @@
398
398
  *
399
399
  * This source code is licensed under the ISC license.
400
400
  * See the LICENSE file in the root directory of this source tree.
401
- */const me=s.createLucideIcon("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function vs(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.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:ra(t.customCfg),data:[]}}function ra(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function la(t,a,n,r){if(!r)return null;const l=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:l,filterValues:n,operation:"create"})}async function rs(t,a){if(!a)return null;const{id:n,template:r,filterValues:l,isDefault:o,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:l,isDefault:o,shared:c,operation:"update"})}async function oa(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function ia(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),l=s.useDashboardStore(x=>x.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=M.useState(!1),[m,h]=M.useState(!1),u=s.useDashboardStore(x=>x.dashboard),p=s.useDashboardStore(x=>x.filterValues),{authToken:j}=s.useSemaphorContext();async function f(){d(!0);const x=vs(u),S=await la(t,x,p,j==null?void 0:j.accessToken);S&&(o([...l||[],S]),c(S.id),h(!1)),d(!1)}return e.jsxs(s.Dialog,{open:m,onOpenChange:h,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:x=>{a(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:f,disabled:i,children:i?"Creating...":"Add"})})]})]})}function ca(){const[t,a]=M.useState(!1),n=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(h){o(h)}async function d(h){if(await oa(h,c==null?void 0:c.accessToken)){const p=n==null?void 0:n.filter(j=>j.id!==h);l(p||[]),o("original")}}async function m(h){const u=n==null?void 0:n.map(f=>f.id===h.id?{...f,isDefault:!h.isDefault}:{...f,isDefault:!1});l(u||[]);const p={...h,isDefault:!h.isDefault};await rs(p,c==null?void 0:c.accessToken);const j=n==null?void 0:n.find(f=>f.isDefault);if(j&&j.id!==h.id){const f={...j,isDefault:!1};await rs(f,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Bn,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.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:u=>{u.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:u=>{u.preventDefault(),d(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 dt(){var o;const t=s.useDashboardStore.getState().authToken,a=s.useDashboardStore.getState().theme,n=s.useDashboardStore.getState().filterValues,r=(o=s.useDashboardStore.getState().dashboard)==null?void 0:o.title,l=s.useDashboardStore.getState().selectedSheetId;return{authToken:t,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:l||""}}async function ut(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:l,selectedSheetId:o}=dt();if(t)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",o||"");const i=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const h=(await(await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,u=document.createElement("a");u.href=h;const p=`${l}-${new Date().toISOString()}.pdf`;u.download=p,u.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function da({iconClassName:t}){const{authToken:a}=s.useSemaphorContext();s.useDashboardStore(l=>{var o;return(o=l.dashboard)==null?void 0:o.title}),s.useDashboardStore(l=>l.theme),s.useDashboardStore(l=>l.filterValues);const n=s.useDashboardStore(l=>l.isDownloadingPdf);async function r(){await ut()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function ce({defaultValue:t,label:a,options:n,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:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const Vs=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function mt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:l,error:o,isDeleting:c}=ua(),[i,d]=M.useState(""),[m,h]=M.useState(Vs[0].value),[u,p]=M.useState("06:00"),[j,f]=M.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"email",children:"Email"}),e.jsx(s.Input,{id:"email",value:i,onChange:x=>d(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(s.Input,{id:"subject",placeholder:"Monthly Sales Report",value:j,onChange:x=>{f(x.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(ce,{className:"col-span-2 h-8",label:"Select Frequency",options:Vs,value:m,onValueChange:x=>h(x)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"time",children:"Time"}),e.jsx(s.Input,{id:"time",type:"time",value:u,onChange:x=>p(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(s.Button,{onClick:async()=>{await n({email:i,frequency:m,time:u,subject:j}),p("00:00"),d(""),f("")},className:"h-8 p-2",disabled:l==="loading"||!i,children:[l==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),l==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),l==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(st,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:o})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),s.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(x=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[s.titleCase(x.frequency)," "]}),e.jsx(s.Label,{children:x.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(Us,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Sn,{className:"size-3.5"})}),e.jsx(Us,{tooltip:`${x.endUserEmail}`,children:e.jsx(Gn,{className:"size-3.5"})}),c===x.id?e.jsx(s.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(s.Trash2,{onClick:()=>r(x.id),className:"size-3.5 cursor-pointer"})]})]},x.id))})]})]})]})})]})})}const Us=({children:t,tooltip:a})=>e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:t}),e.jsx(s.TooltipContent,{children:a})]})});function ua(){const[t,a]=M.useState("idle"),[n,r]=M.useState(""),[l,o]=M.useState(null),c=s.useDashboardStore(N=>N.authToken),i=s.useDashboardStore(N=>N.dashboard.id),d=s.useDashboardStore(N=>N.dashboard.title),{endUserId:m}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),h="https://semaphor.cloud/api/v1/subscriptions/get",u={dashboardId:i,endUserId:m},{data:p,isLoading:j,isError:f,isFetching:x,refetch:S}=s.useQuery({queryKey:["subscriptions",i,m],queryFn:()=>s.getRequest(h,(c==null?void 0:c.accessToken)||"",u),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!m});async function g({email:N,subject:O,frequency:C,time:D}){const{authToken:b,...k}=dt(),w=Intl.DateTimeFormat().resolvedOptions().timeZone,L={email:N,frequency:C,time:D,timezone:w,endUserId:m,endUserEmail:N,subject:O||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:k};a("loading");const T="https://semaphor.cloud/api/v1/subscriptions/create";try{const R=await s.postRequestRegular(T,(b==null?void 0:b.accessToken)||"",{...L});a("success"),r(""),S(),setTimeout(()=>{a("idle")},2e3)}catch(R){console.error(R),a("error"),r(R.message)}}async function v(N){const O="https://semaphor.cloud/api/v1/subscriptions/delete";o(N);try{await s.postRequestRegular(O,(c==null?void 0:c.accessToken)||"",{id:N}),S(),setTimeout(()=>{o(null)},2e3)}catch(C){console.error(C),o(null),a("error"),r(C.message)}}return{data:p,isLoading:j,isFetching:x,isError:f,isDeleting:l,refetch:S,handleScheduleSubscription:g,handleDeleteSubscription:v,status:t,error:n}}function We(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();let n=null;a&&(a.endUserId&&a.endUserEmail&&a.tenantId?n={id:a.endUserId,name:a.endUserEmail?String(a.displayName):"",email:a.endUserEmail?String(a.endUserEmail):"",type:"tenant",tenantId:a.tenantId}:a.orgUserId&&a.orgUserEmail&&(n={id:a.orgUserId,name:a.orgUserEmail?String(a.displayName):"",email:a.orgUserEmail?String(a.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:l,isError:o}=s.useQuery({queryKey:["userInfo",n==null?void 0:n.id],queryFn:async()=>{if(!(n!=null&&n.id))return;const i=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${n.id}`,{headers:{Authorization:`Bearer ${(t==null?void 0:t.accessToken)||""}`,"Content-Type":"application/json"}});if(!i.ok)throw new Error("Failed to fetch user info");return(await i.json()).user},enabled:!!(t!=null&&t.accessToken)&&!!(n!=null&&n.id)});return{currentUser:n?{...n,...r||{}}:null,isLoading:l,isError:o}}function ht(){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,a)=>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"})})})]})]})},a))})]})})}function ma({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:m,onShareVisual:h,formatDate:u}){var C;const{selectVisual:p}=s.useManagementActions(),j=s.useIsVisualSelected(t.id),[f,x]=M.useState(!1),[S,g]=M.useState(!1);M.useEffect(()=>{n?(x(!0),g(!0)):S&&(x(!1),g(!1))},[n,S]);const v=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(nt,{className:"h-3 w-3 text-purple-500"}):e.jsx(me,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(fe,{className:"h-3.5 w-3.5 text-slate-500"}),N=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),O=()=>{p(t),c==null||c(t)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",j&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:O,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-slate-100 dark:bg-slate-800",children:N()})}),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(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:D=>i==null?void 0:i(t.id,{title:D}),isEditable:t.ownership.isOwner&&j,isPending:r,placeholder:"Untitled Visual",displayClassName:"line-clamp-1 max-w-[150px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:v()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:D=>i==null?void 0:i(t.id,{description:D}),isEditable:t.ownership.isOwner&&j,isPending:l,placeholder:"No description",displayClassName:"mt-0.5 max-w-[220px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsxs("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:D=>{D.stopPropagation(),o(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:f,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:D=>D.stopPropagation(),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:D=>{D.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:D=>{D.preventDefault(),D.stopPropagation(),m(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:D=>{D.stopPropagation(),c==null||c(t)},children:[e.jsx(Kn,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:D=>{D.stopPropagation(),h(t)},children:[e.jsx(me,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:D=>{D.stopPropagation(),d(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"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:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(fe,{className:"h-3 w-3"}),e.jsx("span",{children:((C=t.ownership.createdBy)==null?void 0:C.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:u(t.lastModified)})]})]})]})]})]})})]})]},t.id)}function xt({value:t,onChange:a,placeholder:n="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:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function Pe({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=n.find(m=>m.value===t))==null?void 0:d.label)||t,i=n.filter(m=>m.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}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:o}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(m=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:m.value,disabled:r}),a(m.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]})},m.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function pt({selectedUsers:t,selectedUserObjects:a,onRemove:n,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=>n(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:a.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(Pe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>n(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 ft({usersToRemove:t,allUsers:a,onRemove:n}){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=>n(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:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(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 gt({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=a.find(m=>m.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(m=>m.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(me,{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:()=>n(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function jt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,l=M.useRef(null);return M.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 n&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,n,r]),l}function de(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function ha(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function yt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function xa(t,a,n){const r=yt(t),l=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function pa({user:t}){return yt(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 fa({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(a!=null&&a.role))return null;const c=ha((r==null?void 0:r.type)||""),i=n.some(u=>u.id===t.id),d=n.find(u=>u.id===t.id),m=d?d.newRole:a==null?void 0:a.role,h=l(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Pe,{currentRole:m,onRoleChange:u=>{o(t.id,a.role,u)},roleOptions:h,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:de(m,h)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function ga({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&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"]}),a&&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"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Me,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function ja({isUserRemoving:t,isSelected:a,hasAccess:n,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"}),a&&!n&&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 ya({existingShares:t,allUsers:a,getRoleOptions:n,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||[],m=c.orgWide||[],h=c.orgUsersOnly||[],u=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((p,j)=>{var g,v;const f=((g=a.find(N=>N.id===p.orgUserId))==null?void 0:g.name)||"Unknown User",x=((v=a.find(N=>N.id===p.orgUserId))==null?void 0:v.type)||"",S=de(p.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:f}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:S})]},j)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((p,j)=>{var g,v;const f=((g=a.find(N=>N.id===p.tenantUserId))==null?void 0:g.name)||"Unknown User",x=((v=a.find(N=>N.id===p.tenantUserId))==null?void 0:v.type)||"",S=de(p.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:f}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:S})]},j)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),m.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:m.map((p,j)=>{const f=de(p.role,n(""));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:f})]},j)})})]}),h.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:h.map((p,j)=>{const f=de(p.role,n(""));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:f})]},j)})})]}),u.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:u.map((p,j)=>{const f=de(p.role,n(""));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:f})]},j)})})]}),!i.length&&!d.length&&!m.length&&!h.length&&!u.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,m)=>{var j,f;const h=((j=a.find(x=>x.id===d.tenantUserId))==null?void 0:j.name)||"Unknown User",u=((f=a.find(x=>x.id===d.tenantUserId))==null?void 0:f.type)||"",p=de(d.role,n(u));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:h}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:p})]},m)}),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,m)=>{const h=de(d.role,n(""));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:h})]},m)})})]}),!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 p,j;const m=((p=a.find(f=>f.id===i.tenantUserId))==null?void 0:p.name)||"Unknown User",h=((j=a.find(f=>f.id===i.tenantUserId))==null?void 0:j.type)||"",u=de(i.role,n(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:u})]},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 m=de(i.role,n(""));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})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function va({isInitialLoading:t,searchQuery:a,availableUsers:n}){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..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function ba({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:m,handleUserToggle:h,handleRemoveAccess:u,handleUpdateAccess:p,handleUserRoleChange:j}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"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?!n:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?n?h(t.id):u(t.id):h(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(pa,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(Pe,{currentRole:a==null?void 0:a.role,onRoleChange:f=>p(t.id,a.role,f),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(fa,{user:t,userShare:a,usersToUpdate:m,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:p}),o&&!l&&e.jsx("div",{onClick:f=>f.stopPropagation(),children:e.jsx(Pe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:f=>j(t.id,f),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(ga,{hasAccess:r,isUserRemoving:n,isSelected:o,hasAccessFromAPI:l}),e.jsx(ja,{isUserRemoving:n,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function vt({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:m}){const h=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),j=s.useShareSearchQuery(),f=s.useShareManagementActions(),x=c||(C=>{const D=h.some(k=>k.id===C),b=u.includes(C);D?f.removeSelectedUser(C):b?f.removeUserFromRemove(C):f.addSelectedUser({id:C,role:"VIEWER"})}),S=i||f.updateSelectedUserRole,g=d||f.addUserToRemove,v=m||((C,D,b)=>{f.addUserToUpdate({id:C,currentRole:D,newRole:b})}),N=l,O=u;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 (",(N??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{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(ya,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(N==null?void 0:N.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{h.length===N.length?f.setSelectedUsers([]):f.setSelectedUsers(N.map(C=>({id:C.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:h.length===N.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(va,{isInitialLoading:a,isSearching:n,searchQuery:j,availableUsers:N||[]}),!a&&!n&&(N==null?void 0:N.length)>0&&N.map(C=>{const D=t?xa(C,t,o):void 0,b=O.includes(C.id),k=!!D,w=k&&!b,L=h.some(A=>A.id===C.id),T=h.find(A=>A.id===C.id),R=r(C.type);return e.jsx(ba,{user:C,userShare:D,isUserRemoving:b,hasAccess:w,hasAccessFromAPI:k,isSelected:L,selectedUser:T,roleOptions:R,currentUser:o,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:g,handleUpdateAccess:v,handleUserRoleChange:S},C.id)})]})]})}function bt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const l=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,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(fe,{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 ve=()=>[{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 Na({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),m=ve().filter(v=>v.value==="VIEWER"||v.value==="EDITOR"||v.value==="CONTRIBUTOR"),h=a.role!=="NONE"?a.role:"NONE",u=l?l.newRole:h,p=a.role!=="NONE"&&!o&&(!l||l.newRole===h),j=l!==null&&l.newRole!==h,f=o,x=h==="NONE"||!h,S=v=>{switch(v){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(ea,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},g=v=>{r(h,v)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",j&&!f&&!x?"border-orange-300 bg-orange-50":p?"border-green-300 bg-green-50":f||x?"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(me,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",p&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),j&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(f||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:f||x?"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:m.map(v=>e.jsxs(s.Button,{variant:u===v.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>g(v.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[S(v.value),e.jsx("span",{className:"font-medium",children:v.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:v.description})]},v.value))})]})})]})})}function Nt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const m=x=>x==="OWNER"?"CONTRIBUTOR":x,u=a?{role:m(a.role)}:{role:"NONE"},p=i?{currentRole:m(i.currentRole),newRole:m(i.newRole)}:null,j=(x,S)=>{o(x,S)},f=()=>{c()};return e.jsx(Na,{currentUser:t,currentShare:u,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:j,onRemoveAccess:f,allUsersToUpdate:p,allUsersToRemove:d})}const Ca=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function Sa(t={}){var r,l,o;const{authToken:a}=s.useSemaphorContext(),n=s.useQuery({queryKey:["unified-users",t],queryFn:()=>Ca((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken),retry:(c,i)=>i instanceof Error&&i.message.includes("401")||i instanceof Error&&i.message.includes("403")?!1:c<2,retryDelay:c=>Math.min(1e3*2**c,3e4)});return{users:((r=n.data)==null?void 0:r.users)||[],userContext:(l=n.data)==null?void 0:l.userContext,total:((o=n.data)==null?void 0:o.total)||0,isLoading:n.isLoading,isError:n.isError,isFetching:n.isFetching,error:n.error,refetch:n.refetch}}function ge(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=M.useMemo(()=>({search:a,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[a,l,o]),{users:i,isLoading:d,isError:m}=Sa(c),h=s.useResourceShares(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:m,existingShares:h.data,isLoadingShares:h.isLoading,isErrorLoadingShares:h.isError,isFetchingShares:h.isFetching}}function wa({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var Y,V;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:m,setSearchQuery:h,debouncedSearchQuery:u}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),j=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),S=s.useShareOrgWideRole(),g=s.useShareManagementActions(),[v,N]=M.useState("specific_users"),O=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},C=()=>{if(i==="tenant"&&d)return d},{allUsers:D,existingShares:b,isLoadingUsers:k}=ge({debouncedSearchQuery:u,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:O(),tenantId:C()});M.useEffect(()=>{g.setCurrentContext("org-tab"),g.setCurrentMode(v==="all_users"?"allOrgUsers":"specificOrgUsers")},[g,v]);const w=q=>{var U,H;const $=q;if(N($),r==null||r($),g.setCurrentContext("org-tab"),$==="specific_users")g.setCurrentMode("specificOrgUsers");else if($==="all_users"){g.setCurrentMode("allOrgUsers");const W=(H=(U=b==null?void 0:b.shares)==null?void 0:U.orgUsersOnly)==null?void 0:H[0];W&&W.role!==void 0&&g.setOrgWideRole(W.role)}},L=D.filter(q=>q.name.toLowerCase().includes(m.toLowerCase())||q.email.toLowerCase().includes(m.toLowerCase())),T=D.filter(q=>p.some($=>$.id===q.id)),R=q=>{var W,G;const $=p.some(Z=>Z.id===q),U=j.includes(q),H=(G=(W=b==null?void 0:b.shares)==null?void 0:W.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===q);$?g.removeSelectedUser(q):U?g.removeUserFromRemove(q):H||g.addSelectedUser({id:q,role:"VIEWER"})},A=(q,$)=>{g.updateSelectedUserRole(q,$)},I=q=>{g.addUserToRemove(q),g.removeSelectedUser(q)},y=q=>{g.removeUserFromRemove(q)},E=q=>{g.removeUserFromUpdate(q)},F=(q,$)=>{g.setOrgWideRole($)},z=()=>{g.setOrgWideRole((_==null?void 0:_.role)||"NONE")},_=(V=(Y=b==null?void 0:b.shares)==null?void 0:Y.orgUsersOnly)==null?void 0:V[0];M.useEffect(()=>{v==="all_users"&&_&&_.role!==void 0&&g.setOrgWideRole(_.role)},[v,_,g]);const P=k,Q=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(bt,{shareType:v,onShareTypeChange:w,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(fe,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(me,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),v==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(xt,{value:m,onChange:h}),e.jsx(pt,{selectedUsers:p,selectedUserObjects:T,onRemove:R,onRoleChange:A,getRoleOptions:ve}),e.jsx(ft,{usersToRemove:j,allUsers:L,onRemove:y}),e.jsx(gt,{usersToUpdate:f,allUsers:L,onRemove:E,getRoleOptions:ve}),e.jsx(vt,{existingShares:b,isInitialLoading:P,isSearching:Q,resource:t,onShare:()=>{},getRoleOptions:ve,allUsers:L,currentUser:n,handleUserToggle:R,handleUserRoleChange:A,handleRemoveAccess:I,handleUpdateAccess:(q,$,U)=>{g.addUserToUpdate({id:q,currentRole:$,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Nt,{currentUser:n,currentShare:_,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:F,onRemoveAccess:z,allUsersToUpdate:x==="allOrgUsers"&&S!==((_==null?void 0:_.role)||"NONE")?{currentRole:(_==null?void 0:_.role)||"NONE",newRole:S}:null,allUsersToRemove:x==="allOrgUsers"&&(_==null?void 0:_.role)===void 0})})]}):null}function qs({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var W;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:m}=s.useShareSearchWithDebounce(),h=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),j=s.useShareCurrentMode(),f=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),S=s.useShareSelectedTenant(),g=s.useShareManagementActions(),{data:v,isLoading:N}=s.useTenants({enabled:(n==null?void 0:n.type)==="organization"}),[O,C]=M.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(g.setCurrentContext("tenant-dialog"),g.setCurrentMode("specificTenantUsers")):(g.setCurrentContext("tenant-tab"),g.setCurrentMode("allTenants"))},[g,n==null?void 0:n.type]);const D=G=>{var se,ne,ee,ae;C(G);let Z;if(G==="specific_tenant_users"?Z="specific_users":G==="all_tenant_users"||G==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(g.setCurrentContext("tenant-dialog"),G==="specific_tenant_users"?g.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"&&(g.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&g.setSelectedTenant(n.tenantId))):(g.setCurrentContext("tenant-tab"),G==="specific_tenant_users"?g.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"?g.setCurrentMode("allTenantUsers"):G==="all_tenants"&&g.setCurrentMode("allTenants")),G==="all_tenant_users"){const J=(ne=(se=w==null?void 0:w.shares)==null?void 0:se.tenantWide)==null?void 0:ne[0];J&&J.role!==void 0&&g.setTenantWideRole(J.role)}else if(G==="all_tenants"){const J=(ae=(ee=w==null?void 0:w.shares)==null?void 0:ee.allTenantsOnly)==null?void 0:ae[0];J&&J.role!==void 0&&g.setAllTenantsRole(J.role)}},b=G=>{g.setSelectedTenant(G)},{allUsers:k,existingShares:w,isLoadingUsers:L,isErrorLoadingUsers:T,isLoadingShares:R,isErrorLoadingShares:A}=ge({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:S}),I=G=>{var ee,ae;const Z=h.some(J=>J.id===G),se=u.includes(G),ne=(ae=(ee=w==null?void 0:w.shares)==null?void 0:ee.specificTenantUsers)==null?void 0:ae.some(J=>J.tenantUserId===G);Z?g.removeSelectedUser(G):se?g.removeUserFromRemove(G):ne||g.addSelectedUser({id:G,role:"VIEWER"})},y=(G,Z)=>{g.updateSelectedUserRole(G,Z)},E=G=>{g.addUserToRemove(G),g.removeSelectedUser(G)},F=G=>{g.removeUserFromRemove(G)},z=G=>{g.removeUserFromUpdate(G)},_=(G,Z,se)=>{g.addUserToUpdate({id:G,currentRole:Z,newRole:se})},P=(G,Z)=>{O==="all_tenant_users"?g.setTenantWideRole(Z):O==="all_tenants"&&g.setAllTenantsRole(Z)},Q=()=>{O==="all_tenant_users"?g.setTenantWideRole("VIEWER"):O==="all_tenants"&&g.setAllTenantsRole("VIEWER")},V=(()=>{var G,Z,se,ne;return j==="allTenants"?(Z=(G=w==null?void 0:w.shares)==null?void 0:G.allTenantsOnly)==null?void 0:Z[0]:j==="allTenantUsers"?(ne=(se=w==null?void 0:w.shares)==null?void 0:se.tenantWide)==null?void 0:ne[0]:null})();M.useEffect(()=>{var G,Z,se,ne;if(O==="all_tenant_users"){const ee=(Z=(G=w==null?void 0:w.shares)==null?void 0:G.tenantWide)==null?void 0:Z[0];ee&&ee.role!==void 0&&g.setTenantWideRole(ee.role)}else if(O==="all_tenants"){const ee=(ne=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:ne[0];ee&&ee.role!==void 0&&g.setAllTenantsRole(ee.role)}},[O,w,g]);const q=k.filter(G=>h.some(Z=>Z.id===G.id)),$=L||R,U=T||A,H=()=>(n==null?void 0:n.type)==="tenant"||O==="all_tenants"?!0:S&&(O==="specific_tenant_users"||O==="all_tenant_users");return e.jsxs(e.Fragment,{children:[U&&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"})]})}),!U&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(bt,{shareType:O,onShareTypeChange:D,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(me,{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(fe,{className:"mb-3 h-6 w-6 text-orange-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(zs,{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(fe,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(O==="specific_tenant_users"||O==="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:S||"",onValueChange:b,disabled:N,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:N?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(W=v==null?void 0:v.tenants)==null?void 0:W.map(G=>e.jsx(s.SelectItem,{value:G.id,children:G.name},G.id))})]})]}),H()?e.jsx(e.Fragment,{children:O==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(xt,{value:i,onChange:m}),e.jsx(pt,{selectedUsers:h,selectedUserObjects:q,onRemove:G=>I(G),onRoleChange:y,getRoleOptions:ve}),e.jsx(ft,{usersToRemove:u,allUsers:k,onRemove:F}),e.jsx(gt,{usersToUpdate:p,allUsers:k,onRemove:z,getRoleOptions:ve}),e.jsx(vt,{existingShares:w,isInitialLoading:!!$,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:ve,allUsers:k,currentUser:n,handleUserToggle:I,handleUserRoleChange:y,handleRemoveAccess:E,handleUpdateAccess:_})]}):O==="all_tenant_users"||O==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Nt,{currentUser:n,currentShare:V,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:P,onRemoveAccess:Q,allUsersToUpdate:j==="allTenantUsers"&&((V==null?void 0:V.role)===void 0||f!==V.role)||j==="allTenants"&&((V==null?void 0:V.role)===void 0||x!==V.role)?{currentRole:(V==null?void 0:V.role)||"VIEWER",newRole:j==="allTenantUsers"?f:x}:null,allUsersToRemove:j==="allTenantUsers"&&(V==null?void 0:V.role)===void 0||j==="allTenants"&&(V==null?void 0:V.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(O==="specific_tenant_users"||O==="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(zs,{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"})]})})]})]})}const Ct=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),m=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,a,n,r,l,o,c,i,d]),h=M.useMemo(()=>p=>s.validateShareData(p),[]),u=M.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!o)return!1}else if(a==="specificTenantUsers")return o?n.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||l.length>0:!0}return!1},[t,a,n,r,l,o]);return{buildShareData:m,validateShareData:h,isCurrentStateValid:u,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function $s({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:m}){const h=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const j=s.useShareSelectedTenant();s.useShareSelectedTab();const f=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),S=s.useShareTenantWideRole(),{buildShareData:g,validateShareData:v,isCurrentStateValid:N}=Ct(),O=n||r||l,C=()=>{var L,T,R,A;if(O)return"Updating...";if(i==="specific_users"){if(h.length===0&&u.length===0&&p.length===0)return"Select users to share with";const I=h.length+u.length+p.length;return I===0?"Select users to share with":h.length>0&&u.length>0?`Update access for ${I} user${I!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Share with ${h.length} user${h.length!==1?"s":""}`:p.length>0&&h.length===0&&u.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const I=d.role;return f===I?"Remove Access":"Update Access"}else if(i==="all_tenants"){const I=(T=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:T[0];if(!I||I.role===void 0)return"Share with All Tenants";const y=I.role;return x===y?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const I=(A=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const y=I.role;return S===y?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(h.length===0&&u.length===0&&p.length===0)return"Select users to share with";const I=h.length+u.length+p.length;return I===0?"Select users to share with":h.length>0&&u.length>0?`Update access for ${I} user${I!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Share with ${h.length} user${h.length!==1?"s":""}`:p.length>0&&h.length===0&&u.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}return"Share"},D=()=>O||!t||i==="all_tenant_users"&&!j||i==="specific_tenant_users"&&!j?!0:!N,b=()=>{const L=g();L&&v(L)&&o(L)},k=()=>{var L,T,R,A;if(i==="all_users")if(!d||d.role===void 0){const I=g();I&&v(I)&&o(I)}else{const I=d.role;if(f===I)m==null||m();else{const E=g();if(E&&v(E)){const F={...E,updateAccess:!0};o(F)}}}else if(i==="all_tenants"){const I=(T=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:T[0];if(!I||I.role===void 0){const y=g();y&&v(y)&&o(y)}else{const y=I.role;if(x===y)m==null||m();else{const F=g();if(F&&v(F)){const z={...F,updateAccess:!0};o(z)}}}}else if(i==="all_tenant_users"){const I=(A=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0){const y=g();y&&v(y)&&o(y)}else{const y=I.role;if(S===y)m==null||m();else{const F=g();if(F&&v(F)){const z={...F,updateAccess:!0};o(z)}}}}},w=()=>{var L,T,R,A;if(i==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return f===I?"destructive":"default"}else if(i==="all_tenants"){const I=(T=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:T[0];if(!I||I.role===void 0)return"default";const y=I.role;return x===y?"destructive":"default"}else if(i==="all_tenant_users"){const I=(A=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"default";const y=I.role;return S===y?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:O,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(h.length>0||u.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:b,disabled:!t||O,variant:"default",children:[O?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Me,{className:"mr-2 h-4 w-4"}),!O&&C()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,disabled:D(),variant:w(),children:[O?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(me,{className:"mr-2 h-4 w-4"}),!O&&C()]})]})}function Ta({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const u=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:j,isCurrentStateValid:f}=Ct(),x=a||n||r,S=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&m.length===0&&h.length===0)return"Select users to share with";const C=d.length+m.length+h.length;return C===0?"Select users to share with":d.length>0&&m.length>0?`Update access for ${C} user${C!==1?"s":""}`:m.length>0&&d.length===0&&h.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:d.length>0&&m.length===0&&h.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:h.length>0&&d.length===0&&m.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${C} user${C!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const C=i.role;return u===C?"Remove Access":"Update Access"}return"Share"},g=()=>x||!t?!0:!f,v=()=>{const C=p();C&&j(C)&&l(C)},N=()=>{if(!i||i.role==="NONE"){const C=p();C&&j(C)&&l(C)}else{const C=i.role;if(u===C){const b=p();if(b&&j(b)){const k={...b,removeAccess:!0};l(k)}}else{const b=p();if(b&&j(b)){const k={...b,updateAccess:!0};l(k)}}}},O=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:x,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||m.length>0||h.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||x,variant:"default",children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Me,{className:"mr-2 h-4 w-4"}),!x&&S()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:N,disabled:g(),variant:O(),children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Me,{className:"mr-2 h-4 w-4"}),!x&&S()]})]})}function St({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:l,onClose:o,onShare:c,onRemoveAccess:i}){var b,k,w,L;const{currentUser:d}=We(),[m,h]=M.useState("specific_users"),[u,p]=M.useState("specific_users"),j=s.useShareManagementActions(),f=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:S}=ge({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:g}=ge({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),v=(k=(b=S==null?void 0:S.shares)==null?void 0:b.tenantWide)==null?void 0:k[0],N=(L=(w=g==null?void 0:g.shares)==null?void 0:w.orgUsersOnly)==null?void 0:L[0],O=()=>{if(f==="org")return u;switch(x){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},C=M.useCallback(()=>{j.resetShareState(),o()},[j,o]),D=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:C,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(Me,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:D?"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."})]}),D?e.jsxs(s.Tabs,{value:f,onValueChange:T=>{const R=T;j.setSelectedTab(R),j.resetUserSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"})]}),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(wa,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:p,isSharing:n,isUpdating:l,isRemoving:r})})}),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:a,currentUser:d,onShareTabTypeChange:T=>h(T),isSharing:n,isUpdating:l,isRemoving:r})})})]}):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:a,currentUser:d,onShareTabTypeChange:T=>h(T),isSharing:n,isUpdating:l,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:D?f==="org"?e.jsx($s,{resource:t,existingShares:g,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:u,currentAllUsersShare:N,onRemoveAccess:i}):e.jsx($s,{resource:t,existingShares:S,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:O(),currentAllUsersShare:v,onRemoveAccess:i}):e.jsx(Ta,{resource:t,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:m,currentAllUsersShare:v,onRemoveAccess:i})})]})})}function ie(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function pe(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function wt(t,a){const{resourceType:n,resourceId:r,shareMutation:l,removeMutation:o,existingShares:c,resetUserSelections:i}=a;if(r)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=ie(n,r,[{scope:"org_users_only",role:t.orgWideRole}]);l(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h}=t;if(d&&d.length>0){const u=ie(n,r,d.map(p=>({scope:"specific_org_user",orgUserId:p.id,role:p.role})));l(u,{onSuccess:()=>{i()}})}if(m&&m.length>0){const u=pe(n,r,m.map(p=>{var f,x;const j=(x=(f=c==null?void 0:c.shares)==null?void 0:f.specificOrgUsers)==null?void 0:x.find(S=>S.orgUserId===p);return{scope:"specific_org_user",orgUserId:p,role:(j==null?void 0:j.role)||"VIEWER"}}));o(u,{onSuccess:()=>{i()}})}h&&h.length>0&&h.forEach(u=>{const p=ie(n,r,[{scope:"specific_org_user",orgUserId:u.id,role:u.newRole}]);l(p,{onSuccess:()=>{i()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=ie(n,r,[{scope:"all_tenants_only",role:t.allTenantsRole}]);l(d,{onSuccess:()=>{i()}})}else if(t.mode==="allTenantUsers"){const d=ie(n,r,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);l(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h,tenantId:u}=t;if(m&&m.length>0){const p=pe(n,r,m.map(j=>{var x,S;const f=(S=(x=c==null?void 0:c.shares)==null?void 0:x.specificTenantUsers)==null?void 0:S.find(g=>g.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,tenantId:u,role:(f==null?void 0:f.role)||"VIEWER"}}));o(p,{onSuccess:()=>{i()}})}if(h&&h.length>0&&h.forEach(p=>{const j=ie(n,r,[{scope:"specific_tenant_user",tenantUserId:p.id,tenantId:u,role:p.newRole}]);l(j,{onSuccess:()=>{i()}})}),d&&d.length>0){const p=ie(n,r,d.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,tenantId:u,role:j.role})));l(p,{onSuccess:()=>{i()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=pe(n,r,[{scope:"all_tenant_users",role:"VIEWER"}]);o(d,{onSuccess:()=>{i()}})}else if(t.updateAccess){const d=ie(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);l(d,{onSuccess:()=>{i()}})}else{const d=ie(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);l(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h}=t;if(d&&d.length>0){const u=ie(n,r,d.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,role:p.role})));l(u,{onSuccess:()=>{i()}})}if(m&&m.length>0){const u=pe(n,r,m.map(p=>{var f,x;const j=(x=(f=c==null?void 0:c.shares)==null?void 0:f.specificTenantUsers)==null?void 0:x.find(S=>S.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,role:(j==null?void 0:j.role)||"VIEWER"}}));o(u,{onSuccess:()=>{i()}})}h&&h.length>0&&h.forEach(u=>{const p=ie(n,r,[{scope:"specific_tenant_user",tenantUserId:u.id,role:u.newRole}]);l(p,{onSuccess:()=>{i()}})})}break}}function Tt(t,a,n,r){var m,h,u,p,j,f;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const x=pe(l,o,t.map(S=>{var v,N;const g=(N=(v=i==null?void 0:i.shares)==null?void 0:v.specificTenantUsers)==null?void 0:N.find(O=>O.tenantUserId===S);return{scope:"specific_tenant_user",tenantUserId:S,role:(g==null?void 0:g.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:S=>{console.error("Remove access failed:",S)}})}else{const x=a==="tenant"&&n==="allTenants",S=a==="tenant"&&n==="allTenantUsers";if(x){const g=(h=(m=i==null?void 0:i.shares)==null?void 0:m.allTenantsOnly)==null?void 0:h[0];if(g){const v=pe(l,o,[{scope:"all_tenants_only",role:g.role}]);c(v,{onSuccess:()=>{d()},onError:N=>{console.error("Remove all-tenants access failed:",N)}})}}else if(S){const g=(p=(u=i==null?void 0:i.shares)==null?void 0:u.tenantWide)==null?void 0:p[0];if(g){const v=pe(l,o,[{scope:"all_tenant_users",role:g.role}]);c(v,{onSuccess:()=>{d()},onError:N=>{console.error("Remove all-tenant-users access failed:",N)}})}}else{const g=(f=(j=i==null?void 0:i.shares)==null?void 0:j.orgUsersOnly)==null?void 0:f[0];if(g){const v=pe(l,o,[{scope:"org_users_only",role:g.role}]);c(v,{onSuccess:()=>{d()},onError:N=>{console.error("Remove org-wide access failed:",N)}})}}}}function ka(t,a,n){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=ge({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),m=M.useCallback(u=>{if(!t)return;const p={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};wt(u,p)},[t,a,n,i,d]),h=M.useCallback(()=>{if(!t)return;const u={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Tt(l,o||"",c||"",u)},[t,a,n,i,d,l,o,c]);return{handleShareSubmit:m,handleRemoveAccess:h}}function Da(t,a,n){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=ge({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),m=M.useCallback(u=>{if(!t)return;const p={resourceType:s.ResourceType.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};wt(u,p)},[t,a,n,i,d]),h=M.useCallback(()=>{if(!t)return;const u={resourceType:s.ResourceType.VISUAL,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Tt(l,o||"",c||"",u)},[t,a,n,i,d,l,o,c]);return{handleShareSubmit:m,handleRemoveAccess:h}}function Ea(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),[l,o]=M.useState(""),[c,i]=M.useState(""),[d,m]=M.useState(!1),[h,u]=M.useState(null),[p,j]=M.useState(!1),[f,x]=M.useState(null),[S,g]=M.useState(null),{setIsDashboardEditing:v,setIsVisualEditing:N}=s.useDashboardActions(),{handleEditLibraryVisual:O,handleAddLibraryVisual:C}=s.useVisualUtils(),{resources:D,isLoading:b,isError:k,createResource:w,updateResource:L,deleteResource:T,duplicateResource:R,shareResource:A,isCreating:I,isDeleting:y,removeResourceShares:E,isSharing:F,isRemovingShares:z,isUpdatingShares:_}=s.useVisualManagement(()=>{j(!1),x(null)},()=>{r(!1),o(""),i("")}),{handleShareSubmit:P,handleRemoveAccess:Q}=Da((h==null?void 0:h.id)||null,A,E);We();const Y=D.filter(B=>{var K,re;return((K=B==null?void 0:B.title)==null?void 0:K.toLowerCase().includes(t.toLowerCase()))||((re=B==null?void 0:B.description)==null?void 0:re.toLowerCase().includes(t.toLowerCase()))}),V=B=>new Date(B).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{l.trim()&&w({title:l,description:c,isPrivate:!1})},$=B=>{x(B),j(!0)},U=()=>{f&&T(f.id)},{startUpdating:H,stopUpdating:W,isUpdating:G}=s.useResourceUpdateState(),Z=(B,K)=>{const re=K.title!==void 0?"title":"description";H(B,re),L({resourceId:B,data:K},{onSuccess:()=>{W(B,re)},onError:()=>{W(B,re)}})},se=B=>{g(B),R(B,{onSettled:()=>g(null)})},ne=B=>{O(B)},ee=B=>{C(B)},ae=B=>{const K=D.find(re=>re.id===B);K&&L({resourceId:B,data:{isPrivate:!K.isPrivate}})},J=B=>{u(B),m(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),ge({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),b?e.jsx(ht,{}):k?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:n?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:B=>o(B.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:B=>i(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:q,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||I,children:I?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:I,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),I?"Creating...":"Create New Visual"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:B=>a(B.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:Y.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(He,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):Y.map(B=>e.jsx(ma,{visual:B,onAddVisual:ee,onEditVisual:ne,onUpdateVisual:Z,onDeleteClick:$,onDuplicateVisual:se,onTogglePrivacy:ae,onShareVisual:J,isDeleting:y,isDuplicating:S===B.id,isTitleUpdating:G(B.id,"title"),isDescriptionUpdating:G(B.id,"description"),formatDate:V},B.id))})}),d&&h&&e.jsx(St,{resource:h,resourceType:s.ResourceType.VISUAL,onShare:P,isSharing:F,isRemoving:z,isUpdating:_,onClose:()=>{m(!1),u(null)},onRemoveAccess:Q}),e.jsx(s.AlertDialog,{open:p,onOpenChange:B=>{!B&&y||(j(B),B||x(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',f==null?void 0:f.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:y,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:B=>{B.preventDefault(),B.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,children:y?"Deleting...":"Delete"})]})]})})]})}function Ia({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:m,formatDate:h}){var O;const{selectDashboard:u}=s.useManagementActions(),p=s.useIsDashboardSelected(t.id),[j,f]=M.useState(!1),[x,S]=M.useState(!1);M.useEffect(()=>{n?(f(!0),S(!0)):x&&(f(!1),S(!1))},[n,x]);const g=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(nt,{className:"h-3 w-3 text-purple-500"}):e.jsx(me,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(fe,{className:"h-3.5 w-3.5 text-slate-500"}),v=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),N=()=>{u(t),o(t.id)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",p&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:N,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-slate-100 dark:bg-slate-800",children:v()})}),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(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:C=>c==null?void 0:c(t.id,{title:C}),isEditable:t.permissions.canEdit&&p,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"line-clamp-1 max-w-[220px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:g()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:C=>c==null?void 0:c(t.id,{description:C}),isEditable:t.permissions.canEdit&&p,isPending:l,placeholder:"No description",displayClassName:"mt-0.5 max-w-[250px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsx("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:e.jsxs(s.DropdownMenu,{modal:!1,open:j,onOpenChange:f,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:C=>C.stopPropagation(),children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.preventDefault(),C.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),m(t)},children:[e.jsx(me,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),i(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"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:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(fe,{className:"h-3 w-3"}),e.jsx("span",{children:((O=t.ownership.createdBy)==null?void 0:O.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:h(t.lastModified)})]})]})]})]})})})]})]},t.id)}function Aa({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 Ma(t){const[a,n]=M.useState(""),[r,l]=M.useState(!1),[o,c]=M.useState(""),[i,d]=M.useState(""),[m,h]=M.useState(!1),[u,p]=M.useState(null),[j,f]=M.useState(!1),[x,S]=M.useState(null),[g,v]=M.useState(null),N=s.useManagementStore(J=>J.lastSelectedDashboard),O=s.useManagementStore(J=>J.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:C,isLoading:D,isError:b,createResource:k,updateResource:w,deleteResource:L,duplicateResource:T,isCreating:R,isDeleting:A,isSharing:I,isRemovingShares:y,isUpdatingShares:E,shareResource:F,removeResourceShares:z}=s.useDashboardManagement(()=>{f(!1),S(null),N&&O(N)},()=>{l(!1),c(""),d("")}),{handleShareSubmit:_,handleRemoveAccess:P}=ka((u==null?void 0:u.id)||null,F,z),{currentUser:Q}=We(),Y=C.filter(J=>{var B,K;return((B=J==null?void 0:J.title)==null?void 0:B.toLowerCase().includes(a.toLowerCase()))||((K=J==null?void 0:J.description)==null?void 0:K.toLowerCase().includes(a.toLowerCase()))}),V=J=>new Date(J).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{o.trim()&&k({title:o,description:i,isPrivate:!1})},$=J=>{var B;(B=t.onLoadDashboard)==null||B.call(t,J)},U=J=>{S(J),f(!0)},H=()=>{x&&L(x.id)},W=J=>{v(J),T(J,{onSettled:()=>v(null)})},{startUpdating:G,stopUpdating:Z,isUpdating:se}=s.useResourceUpdateState(),ne=(J,B)=>{const K=B.title!==void 0?"title":"description";G(J,K),w({resourceId:J,data:B},{onSuccess:()=>{Z(J,K)},onError:()=>{Z(J,K)}})},ee=J=>{const B=C.find(K=>K.id===J);B&&w({resourceId:J,data:{isPrivate:!B.isPrivate}})},ae=J=>{p(J),Q==null||Q.type,h(!0)};return ge({debouncedSearchQuery:"",resourceId:(u==null?void 0:u.id)||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),D?e.jsx(ht,{}):b?e.jsx(Aa,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:o,onChange:J=>c(J.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:J=>d(J.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:q,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||R,children:R?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:R,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"h-8 w-full",size:"sm",disabled:R,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),R?"Creating...":"Create New Dashboard"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:a,onChange:J=>n(J.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:Y.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(Rn,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):Y.map(J=>e.jsx(Ia,{dashboard:J,isDeleting:A,isDuplicating:g===J.id,isTitleUpdating:se(J.id,"title"),isDescriptionUpdating:se(J.id,"description"),onLoadDashboard:$,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ne,onDeleteClick:U,onDuplicateDashboard:W,onTogglePrivacy:ee,onShareDashboard:ae,formatDate:V},J.id))})}),m&&u&&e.jsx(St,{resource:u,resourceType:s.ResourceType.DASHBOARD,onShare:_,isSharing:I,isRemoving:y,isUpdating:E,onClose:()=>{h(!1),p(null)},onRemoveAccess:P}),e.jsx(s.AlertDialog,{open:j,onOpenChange:J=>{!J&&A||(f(J),J||S(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 "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:J=>{J.preventDefault(),J.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function kt({isOpen:t,onClose:a,className:n}){s.useDashboardStore(p=>p.dashboard);const{setDashboard:r,addSheet:l}=s.useDashboardStore(p=>p.actions),{currentUser:o}=We(),c=o,[i,d]=s.useLocalStorageState("resource-management-active-tab","dashboards"),m=jt(a,{enabled:t}),h=p=>{},u=p=>{console.log("Editing dashboard:",p)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:m,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"-translate-x-full",n),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:c&&e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-muted bg-muted/30 px-2 py-1",children:[e.jsxs(s.Avatar,{className:"h-5 w-5",children:[e.jsx(s.AvatarImage,{alt:c.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:c.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:c.name})]})}),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:c.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:c.email}),c.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(c.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",c.id]})]})})]})})}),e.jsx(s.IconButton,{className:"h-6 p-1 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Hide Dashboard Management",children:e.jsx(s.X,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:i,onValueChange:d,className:"flex h-9 grow flex-col",children:[e.jsx("div",{className:"px-5",children:e.jsxs(s.TabsList,{className:"grid h-8 w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"h-6",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"h-6",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1",children:e.jsx(Ma,{onLoadDashboard:h,onEditDashboard:u})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Ea,{})})]})})]})})}function La(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(E=>E.theme);const n=s.useDashboardStore(E=>E.lenses),r=s.useDashboardStore(E=>E.selectedLensId),l=n==null?void 0:n.find(E=>E.id===r),o=s.useDashboardStore(E=>E.dashboard);s.useDashboardStore(E=>E.selectedSheetId);const c=s.useDashboardStore(E=>E.isDashboardEditing),i=s.useEditorStore(E=>E.card),d=s.useEditorStore(E=>E.selectedConnectionId),[m,h]=M.useState(!1),u=s.useDashboardStore(E=>E.isDashboardPanelOpen),p=s.useDashboardStore(E=>E.actions.setIsDashboardPanelOpen),j=s.useDashboardStore(E=>E.filterValues),f=s.useDashboardStore(E=>E.isVisualEditing),x=s.useDashboardStore(E=>E.showFilters);s.useDashboardStore(E=>E.showDashboardJSON);const S=s.useDashboardStore(E=>E.onSaveFunction),g=s.useDashboardStore(E=>E.actions.setShowFilters),{addFrame:v,setSelectedFrameId:N}=s.useDashboardStore(E=>E.actions),{getSelectedSheet:O,setIsDashboardEditing:C,setShowDashboardJSON:D}=s.useDashboardStore(E=>E.actions),b=O(),{tenantId:k,endUserId:w}=M.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),L=M.useMemo(()=>k||w,[k,w]),T=()=>{if(!c||!b)return;const E={dataSource:i.dataSource,mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},F={id:s.v4(),cards:[E],activeCardId:E.id};v(b.id,F),N(F.id)},R=()=>{C(!0)};async function A(){if(h(!0),!r||!l)return;const E=vs(o),F=JSON.stringify(E),z={...l,template:F,filterValues:j};await rs(z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),S==null||S(E),h(!1)}if(f)return null;const I=(l==null?void 0:l.name)||o.title,y=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[y&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(Pn,{className:"h-4 w-4"})}),!f&&e.jsx(s.Label,{children:I})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!f&&e.jsx(da,{}),!f&&e.jsx(mt,{}),c&&!f&&L&&e.jsx(ia,{}),!f&&L&&e.jsx(ca,{}),c&&!f&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:T,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!f&&e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2",onClick:R,size:"sm",children:e.jsx(s.Pencil,{className:"h-4 w-4"})}),c&&!f&&e.jsx(s.IconButton,{className:"h-7 p-2",onClick:()=>{C(!1),D(!1)},children:e.jsx(s.Cross2Icon,{className:"h-4 w-4"})}),c&&!f&&L&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",disabled:m,onClick:A,size:"sm",children:e.jsx(s.Save,{className:"h-4 w-4"})}),!x&&!f&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>g(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!f&&c&&!1,!f&&!1,!f&&e.jsx(kt,{isOpen:u,onClose:()=>p(!1)})]})]})}function Oa({name:t,items:a,value:n,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:m=!1}){const h=ye.useRef(null),[u,p]=ye.useState(!1),[j,f]=ye.useState("100%"),x=m?[...a||[],{id:"none",name:"None"}]:a;ye.useLayoutEffect(()=>{h.current&&f(h.current.offsetWidth)},[]);function S(){var v;return l?"Loading...":o?"Error":n?(v=a==null?void 0:a.find(N=>N.id===n))==null?void 0:v.name:`Select ${t}`}function g(v,N){r(N),p(!1)}return e.jsxs(s.Popover,{open:u,onOpenChange:p,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:h,variant:"outline",role:"combobox","aria-expanded":u,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:S()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:j},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(at,{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:x==null?void 0:x.map(v=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:v.name,onSelect:N=>g(N,v.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===v.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:v.name,children:v.name})]})},v.id))})]})]})})]})}function ke({title:t,items:a,value:n,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:m=!1,type:h="combobox"}){const u=r?"Loading...":l?"Error":n;function p(){if(t==="Connection")return e.jsx(Qn,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Yn,{className:"size-4"});if(t==="Table")return e.jsx(Je,{className:"size-4"});if(t==="Model")return e.jsx(vn,{className:"size-4"})}function j(){return e.jsxs(s.Select,{disabled:m,value:u,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(at,{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"),a&&a.map((x,S)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},S))]}),(r||l)&&e.jsx(s.SelectItem,{value:u,children:u})]})})]})}function f(){return e.jsx(Oa,{icon:p(),items:a,value:u,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:h==="select"?j():f()})})}function Ra({column:t}){const[a,n]=M.useState(!1),r=s.useEditorStore(x=>x.selectedTableName),l=s.useEditorStore(x=>x.selectedSchemaName),o=s.useEditorStore(x=>x.selectedDatabaseName),c=s.useEditorStore(x=>x.selectedDatamodelId),i=s.useEditorStore(x=>x.sqlGen),{modelItems:d,connectionType:m}=s.useEditorAside(),h=s.useEditorStore(x=>x.actions.setSqlGen),u=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function j(x,S){var O;const g=s.createSqlGenConfig(x,i,S),v=(O=d==null?void 0:d.find(C=>C.id===c))==null?void 0:O.name;h(g);const N=s.getSql(g,s.fmt(l||""),s.fmt(r),v||"",m,o||"");N&&(u(N),p(!0)),n(!1)}function f(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>j(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>j(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>j(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>j(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>j(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,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:f()})]})}function bs({column:t}){return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger$1,{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(fs,{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(ot,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(bn,{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 Qe({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(bs,{column:t}),e.jsx("span",{children:t.column_name})]})}function Ba({id:t,children:a,type:n="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:n}}),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:a})}function Fa({onClick:t,column:a}){const n=s.useDndStore(h=>h.activeId),r=s.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.groupByColumns}),l=s.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.metricColumns}),o=s.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.filterColumns});function c(h){return i(h)||d(h)||m(h)}function i(h){return r==null?void 0:r.some(u=>u.name===h.column_name)}function d(h){return l==null?void 0:l.some(u=>u.name===h.column_name)}function m(h){return o==null?void 0:o.some(u=>u.name===h.column_name)}return e.jsxs("div",{onClick:()=>t(a),className:s.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(Qe,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(Qe,{column:a})}),e.jsx(Ba,{id:a.column_name,type:"column",children:e.jsx(Qe,{column:a})})]})}const Xe={id:"__placeholder__",role:"groupby",type:"string"},Ze={id:"__placeholder__",role:"groupby",type:"string"},es={id:"__placeholder__",role:"metric",type:"number"},ss={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},Dt={id:"__placeholder__"},be="droppable-group-by",Ne="droppable-metrics",Ce="droppable-pivot-by",_e="sortable-group-by",ls="sortable-metrics",Ve="sortable-pivot-by",os="droppable-filters",is="sortable-filters",Ns="sortable-order-by";function za(){const t=s.useDndStore(I=>I.insertIndex),a=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.groupByColumns)||[]}),n=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.metricColumns)||[]}),r=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.filterColumns)||[]}),l=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.orderBy)||[]}),o=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:m,setPreviewFilterColumns:h,setPreviewPivotColumns:u}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:j,setFilterColumns:f,setOrderByColumns:x,setPivotByColumns:S}=s.useEditorActions(),{columns:g}=s.useDataColumns(),{formattedTableName:v}=s.useEditorAside(),N=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),O=I=>{var F;const{active:y,over:E}=I;if(((F=y.data.current)==null?void 0:F.type)==="column"&&E){const z=E.id,_=g.find(V=>V.column_name===y.id);if(!_)return;const P=s.isNumberDataType(_.data_type),Q=s.isTextDataType(_.data_type),Y=s.isDateDataType(_.data_type);if(Q||Y){if(a.some(q=>q.id===z)){const q=a.findIndex(U=>U.id===z);c(q);const $=a.filter(U=>U.id!==Xe.id);$.splice(q,0,Xe),d($)}else if(E.id===be){c(a.length);const q=[...a,Xe];d(q),m(n),h(r)}}if(Q||Y){if(o.some(q=>q.id===z)){const q=o.findIndex(U=>U.id===z);c(q);const $=o.filter(U=>U.id!==Ze.id);$.splice(q,0,Ze),u($)}else if(E.id===Ce){c(o.length);const q=[...o,Ze];u(q),d(a),m(n),h(r)}}if(P||Q){if(n.some(q=>q.id===z)){console.log("isOverMetricSortable",z);const q=n.findIndex(U=>U.id===z);c(q);const $=n.filter(U=>U.id!==es.id);$.splice(q,0,es),m($)}else if(E.id===Ne){c(n.length);const q=[...n,es];m(q),h(r),d(a),u(o)}}if(D(_)){if(r.some(q=>q.id===z)){const q=r.findIndex(U=>U.id===z);c(q);const $=r.filter(U=>U.id!==ss.id);$.splice(q,0,ss),h($)}else if(E.id===os){c(r.length);const q=[...r,ss];h(q),m(n),d(a),u(o)}}}else d(a),m(n),h(r),u(o)};function C(I){i(I.active.id),c(null),d(a),m(n),h(r),u(o)}function D(I){return!r.some(y=>y.name===I.column_name)}function b(I,y="SUM"){const{column_name:E,data_type:F}=I,z=[...n],_=t!==null?t:n.length,P={...I,id:ue(E),name:E,label:Le(E,y),type:F,role:"metric",aggregate:y};z.splice(_,0,P),j(z)}function k(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const E=[...o],F=t!==null?t:o.length;let z;y?z={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:De(I.column_name,"month"),granularity:"month"},E.splice(F,0,z),S(E)}function w(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const E=[...a],F=t!==null?t:a.length;let z;y?z={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:De(I.column_name,"month"),granularity:"month"},E.splice(F,0,z),p(E)}function L(I){const y=[...r],E=t!==null?t:r.length,F={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,sql:s.getDefaultFilterSql(I.data_type,v,s.fmt(I.column_name)),role:"filter"};y.splice(E,0,F),f(y)}function T(I){var z,_,P,Q,Y,V,q,$;const{active:y,over:E}=I,F=y.data.current;if((F==null?void 0:F.type)==="column"&&E){const U=g.find(Z=>Z.column_name===y.id);if(!U)return;const H=s.isNumberDataType(U.data_type),W=s.isTextDataType(U.data_type),G=s.isDateDataType(U.data_type);(W||G)&&(E.id===be||((z=E.data.current)==null?void 0:z.type)===_e)&&w(U),(W||G)&&(E.id===Ce||((_=E.data.current)==null?void 0:_.type)===Ve)?k(U):(H||W)&&(E.id===Ne||((P=E.data.current)==null?void 0:P.type)===ls)?(H&&b(U),W&&b(U,"COUNT")):D(U)&&(E.id===os||((Q=E.data.current)==null?void 0:Q.type)===is)&&L(U)}if(E&&((Y=E.data.current)==null?void 0:Y.type)===_e&&a.some(U=>U.id===y.id)){const U=a.findIndex(W=>W.id===y.id),H=a.findIndex(W=>W.id===E.id);if(U!==-1&&H!==-1&&U!==H){const W=[...a],[G]=W.splice(U,1);W.splice(H,0,G),p(W)}}if(E&&((V=E.data.current)==null?void 0:V.type)===Ve&&o.some(U=>U.id===y.id)){const U=o.findIndex(W=>W.id===y.id),H=o.findIndex(W=>W.id===E.id);if(U!==-1&&H!==-1&&U!==H){const W=[...o],[G]=W.splice(U,1);W.splice(H,0,G),S(W)}}if(E&&((q=E.data.current)==null?void 0:q.type)===ls&&n.some(U=>U.id===y.id)){const U=n.findIndex(W=>W.id===y.id),H=n.findIndex(W=>W.id===E.id);if(U!==-1&&H!==-1&&U!==H){const W=[...n],[G]=W.splice(U,1);W.splice(H,0,G),j(W)}}if(E&&(($=E.data.current)==null?void 0:$.type)===is&&r.some(U=>U.id===y.id)){const U=r.findIndex(W=>W.id===y.id),H=r.findIndex(W=>W.id===E.id);if(U!==-1&&H!==-1&&U!==H){const W=[...r],[G]=W.splice(U,1);W.splice(H,0,G),f(W)}}R(I),i(null),c(null),d(a),m(n),h(r),u(o)}function R(I){const{active:y,over:E}=I,F=y.data.current;if((F==null?void 0:F.type)===Ns&&E){const z=l.findIndex(P=>Ie(P.columnId)===y.id),_=l.findIndex(P=>Ie(P.columnId)===E.id);if(z!==-1&&_!==-1&&z!==_){const P=[...l],[Q]=P.splice(z,1);P.splice(_,0,Q),x(P)}}}function A(){i(null),c(null),d(a),m(n),h(r)}return{handleDragOver:O,handleDragEnd:T,handleDragStart:C,handleDragCancel:A,sensors:N}}function ue(t){return`${t}-${s.v4()}`}function Le(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ie(t){return`${Ns}-${t}`}function De(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Pa({schemaName:t,tableName:a,columns:n,status:r}){const l=s.useEditorStore(y=>y.sqlGen),o=s.useEditorStore(y=>y.isDevMode),c=s.useEditorStore(y=>y.selectedConnectionId),i=s.useEditorStore(y=>{var E,F;return(F=(E=y.card)==null?void 0:E.queryConfig)==null?void 0:F.metricColumns});s.useEditorStore(y=>{var E,F;return(F=(E=y.card)==null?void 0:E.queryConfig)==null?void 0:F.groupByColumns});const d=s.useEditorStore(y=>y.selectedDatabaseName),m=s.useEditorStore(y=>y.selectedSchemaName),h=s.useEditorStore(y=>y.selectedTableName),u=s.useEditorStore(y=>y.selectedDatamodelId),p=s.useDashboardStore(y=>y.dashboard.aiScopeTables),{addToAIScope:j,removeFromAIScope:f}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:S,setCardSql:g,setRunSql:v,setSqlGen:N,setIsShowingVisual:O}=s.useEditorActions(),{connectionType:C,modelItems:D,selectedDatamodelName:b}=s.useEditorAside();function k(y){var E;if(o){const F=s.createSqlGenConfig(y,l);N(F);const z=(E=D==null?void 0:D.find(P=>P.id===u))==null?void 0:E.name,_=s.getSql(F,s.fmt(t),s.fmt(a),z||"",C,d||"");_&&(g(_),v(!0))}if(!o){if(s.isTextDataType(y.data_type))if(i&&i.length>0){const F={...y,role:"groupby",id:ue(y.column_name),name:y.column_name,type:y.data_type};S(F)}else{const F={...y,role:"metric",id:ue(y.column_name),name:y.column_name,label:Le(y.column_name,"COUNT"),type:y.data_type,aggregate:"COUNT"};x(F)}if(s.isDateDataType(y.data_type)){const F={...y,role:"groupby",id:ue(y.column_name),name:y.column_name,type:y.data_type,label:De(y.column_name,"month"),granularity:"month"};S(F)}if(s.isNumberDataType(y.data_type)){const F={...y,role:"metric",id:ue(y.column_name),name:y.column_name,label:Le(y.column_name,"SUM"),type:y.data_type,aggregate:"SUM"};x(F)}}}function w(y){y===!0&&(h||b)&&c?(j({connectionId:c,connectionType:C==="S3"||C==="API"?"DuckDb":C||"",databaseName:d||"",schemaName:m||"",tableName:h||"",datamodelName:s.resolveDatamodelName(b),datamodelId:u||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(f({connectionId:c||"",connectionType:C||"",tableName:h||"",datamodelName:s.resolveDatamodelName(b),datamodelId:u||"",databaseName:d||"",schemaName:m||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function L(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:b,connectionType:C,databaseName:d||""});O(!1);const E=C==="MSSQL"?`SELECT top 10 * FROM ${y}`:`SELECT * FROM ${y} LIMIT 10`;g(E),v(!0)}function T(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:b,connectionType:C,databaseName:d||""});g(`SELECT COUNT(*) as count FROM ${y}`),v(!0)}function R(){return(p==null?void 0:p.find(y=>y.connectionId===c&&(y.tableName===h||y.datamodelName===b)))!==void 0}function A(y){return o?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>k(y),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(bs,{column:y}),e.jsx("span",{children:y.column_name})]}),e.jsx("div",{onClick:E=>E.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(y.data_type)&&e.jsx(Ra,{column:y})})]}):e.jsx(Fa,{onClick:k,column:y})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${R()?"Remove from":"Add to"} Assistant Scope`,pressed:R(),onPressedChange:w,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":R(),"text-muted-foreground":!R()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:L,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx($n,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:T,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(rt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((y,E)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},E))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[o&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:I()}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(y=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:A(y)},y.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Et({ColumnsComponent:t,type:a}){var je;const n=s.useEditorStore(te=>te.card),r=s.useEditorStore(te=>te.selectedConnectionId),l=s.useDashboardStore(te=>te.showFilters),o=s.useEditorStore(te=>te.selectedDatamodelId),c=s.useEditorStore(te=>te.selectedDatabaseName),i=s.useEditorStore(te=>te.selectedSchemaName),d=s.useEditorStore(te=>te.selectedTableName),m=s.useEditorStore(te=>te.isDevMode),{setSelectedTableName:h,setIsDevMode:u,setCardSql:p}=s.useEditorActions(),{connectionItems:j,modelItems:f,schemaItems:x,databaseItems:S,tableItems:g,columns:v,isConnectionsLoading:N,isModelsLoading:O,isConnectionsError:C,isModelsError:D,isDatabasesLoadingOrFetching:b,isDatabaseError:k,isSchemaLoadingOrFetching:w,isSchemaError:L,isColumnsError:T,isColumnsLoadingOrFetching:R,isTableLoadingOrFetching:A,isTableError:I,connectionType:y,isNonDbConnection:E,refetchDatabases:F,refetchModels:z,refetchSchemas:_,refetchTables:P,refetchColumns:Q,refetchConnections:Y,handleConnectionChange:V,handleDatabaseChange:q,handleSchemaChange:$,handleDatamodelChange:U,handleTableChange:H,tableName:W,schemaName:G}=s.useEditorAside(),{data:Z,refetch:se}=s.useDashboardCardQuery(n);function ne(){return t?t(G,W,v):e.jsx(Pa,{schemaName:G,tableName:W,columns:v,status:R?"Loading...":T?"Error":"Success"})}function ee(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function ae(te){te===!0?Z&&(p(Z.userSql),setTimeout(()=>{se()},100)):p(""),u(te)}function J(){if(!r||y==="S3"||y==="API")return null;if(!o||o==="none")return e.jsx(ke,{refetch:F,showNone:!0,onChange:q,isError:k,isLoading:b,items:S,value:c||"",title:"Database",type:"combobox"})}function B(){if(r&&!E&&(!c||c==="none")&&(!o||o==="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 K(){if(!r||y==="S3"||y==="API")return null;if(!c||c==="none")return e.jsx(ke,{refetch:z,showNone:!0,onChange:U,isError:D,isLoading:O,items:f,value:o||"",title:"Model",type:"combobox"})}function re(){return!r||y==="S3"||y==="API"||!c||c==="none"?null:e.jsx(ke,{refetch:_,onChange:$,isError:L,isLoading:w,items:x,value:i||"",title:"Schema",type:"combobox"})}function he(){function te(){let le=!1;return y==="API"?(le=!1,le):((y==="S3"||r&&c&&c!=="none"&&i)&&(le=!0),le)}return te()?e.jsx(ke,{refetch:P,onChange:H,isError:I,items:g,isLoading:A,value:d||"",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]":!l}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(ke,{refetch:Y,items:j,title:"Connection",value:r||"",onChange:V,isLoading:N,isError:C,type:"combobox",connectionTooltip:((je=j==null?void 0:j.find(te=>te.id===r))==null?void 0:je.type)||""}),J(),B(),K(),re(),he()]}),ne(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:m,onCheckedChange:ae,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:ee,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Jn,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function It({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[l,o]=M.useState(!1),c=M.useRef(null),i=M.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function m(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),d())}function h(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const j=p.toString();navigator.clipboard.writeText(j),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function u(){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 ${a}`,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 ${n}`,onClick:d,onKeyDown:m,onMouseUp:h,onMouseDown:u,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 At({sql:t,error:a,onDebugWithAssistant:n}){const r=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:l,setCardSql:o,setRunSql:c}=s.useEditorActions();function i(){l(!r),o(t),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(It,{error:a}),t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!r&&t&&e.jsxs(s.Button,{onClick:i,variant:"secondary",size:"sm",children:[e.jsx(An,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(s.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(zn,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Mt({sql:t,error:a,onDebugWithAssistant:n}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(st,{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-[600px]",children:e.jsx(At,{sql:t,error:a,onDebugWithAssistant:n})})]})}var Lt={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Gs=M.createContext&&M.createContext(Lt),_a=["attr","size","title"];function Va(t,a){if(t==null)return{};var n=Ua(t,a),r,l;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(l=0;l<o.length;l++)r=o[l],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}function Ua(t,a){if(t==null)return{};var n={};for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){if(a.indexOf(r)>=0)continue;n[r]=t[r]}return n}function Ue(){return Ue=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Ue.apply(this,arguments)}function Hs(t,a){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);a&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(t,l).enumerable})),n.push.apply(n,r)}return n}function qe(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?Hs(Object(n),!0).forEach(function(r){qa(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Hs(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function qa(t,a,n){return a=$a(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function $a(t){var a=Ga(t,"string");return typeof a=="symbol"?a:a+""}function Ga(t,a){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function Ot(t){return t&&t.map((a,n)=>M.createElement(a.tag,qe({key:n},a.attr),Ot(a.child)))}function Se(t){return a=>M.createElement(Ha,Ue({attr:qe({},t.attr)},a),Ot(t.child))}function Ha(t){var a=n=>{var{attr:r,size:l,title:o}=t,c=Va(t,_a),i=l||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),M.createElement("svg",Ue({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:qe(qe({color:t.color||n.color},n.style),t.style),height:i,width:i,xmlns:"http://www.w3.org/2000/svg"}),o&&M.createElement("title",null,o),t.children)};return Gs!==void 0?M.createElement(Gs.Consumer,null,n=>a(n)):a(Lt)}function Ja(t){return Se({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 Rt(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(x=>x.theme),r=s.useEditorStore(x=>x.frame),l=s.useEditorStore(x=>x.card),o=s.useEditorStore(x=>x.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:m}=s.useEditorActions(),h=M.useRef(),u=M.useRef({}),p=r.cards.find(x=>x.id===o),j=M.useCallback(()=>{let x="";return t==="python"&&(x=(p==null?void 0:p.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(p==null?void 0:p.sql)||""),x},[t,p]);M.useEffect(()=>{if(o&&l.id&&l.id!==o){if(h.current&&c){const x=h.current.getModel();x&&(u.current[l.id]=x);let S=u.current[o];if(!S){const g=j();S=c.editor.createModel(g,t),u.current[o]=S}h.current.setModel(S)}d(o,l),m(!0)}},[o,l,d,c,m,t,j]),M.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",S=n==="system"?x:n;c.editor.defineTheme("default",{base:S==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":S==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),M.useEffect(()=>{const x=h.current;x&&c&&l&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function f(x,S){if(h.current=x,!u.current[l.id]){const g=x.getModel(),v=j();u.current[l.id]=g||(S==null?void 0:S.editor.createModel(v,t))||x.getModel()}x.setModel(u.current[l.id])}return{handleEditorDidMount:f}}function Wa(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Rt("sql");function o(c){n(c),s.isObjectEmpty(a)||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 Ya(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=Rt("python");function r(l){a(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:n})}function Ka({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 Qa(){const t=s.useQueryClient(),[a,n]=M.useState(!1),[r,l]=M.useState(!1);s.useEditorStore(P=>P.frame);const o=s.useEditorStore(P=>P.card);s.useEditorStore(P=>P.isShowingVisual),s.useEditorStore(P=>P.selectedConnectionId),s.useEditorStore(P=>P.tempQueryData),s.useEditorStore(P=>P.selectedDatabaseName),s.useEditorStore(P=>P.selectedDatamodelId),s.useEditorStore(P=>P.selectedSchemaName);const c=s.useEditorStore(P=>P.showAIDialog);s.useEditorStore(P=>P.selectedTableName);const i=s.useEditorStore(P=>{var Q;return(Q=P==null?void 0:P.card)==null?void 0:Q.sql}),d=s.useEditorStore(P=>{var Q;return(Q=P==null?void 0:P.card)==null?void 0:Q.python}),{sheetFilterValues:m}=s.useSheetFilterValues(),{setCardCustomCfg:h,setQueryResultColumns:u,setCardSql:p,setTempQueryData:j,setPythonStdOut:f,setCardPreferences:x,setCardType:S,setCardPython:g,runAssistant:v,setShowAIDialog:N}=s.useEditorActions();s.useEditorStore(P=>P.onSave),s.useEditorStore(P=>P.onClose),s.useEditorStore(P=>P.actions.setSqlGen);const O=s.useEditorStore(P=>P.runSql),C=s.useEditorStore(P=>P.actions.setRunSql),D=s.useEditorStore(P=>P.actions.setIsSqlRunning),{data:b,isLoading:k,isFetching:w,isSuccess:L,isError:T,error:R,queryKey:A,refetch:I,errorMessage:y}=s.useDashboardCardQuery(o);M.useEffect(()=>{if(b&&(b.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),f((b==null?void 0:b.output)||""),b.records.length>0)){const{dimensionKeys:P}=s.getKeys(b.records);u(P)}},[b,u,f]),M.useEffect(()=>{(k||w)&&D(!0),(T||L)&&D(!1),T&&(u([]),f(""))},[k,w,b,f,T,L,D,u,R]),M.useEffect(()=>{O&&(t.getQueryData(A)||I(),C(!1))},[O,I,C,A,t]);async function E(){const P=`Can you help me debug this query in the current table scope?
401
+ */const me=s.createLucideIcon("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function vs(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(l=>{var i;return{...l,cards:(i=l.cards)==null?void 0:i.map(c=>ct(c))}})}})}}function ct(t){return{...t,customCfg:ra(t.customCfg),data:[]}}function ra(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function la(t,a,n,r){if(!r)return null;const l=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:l,filterValues:n,operation:"create"})}async function rs(t,a){if(!a)return null;const{id:n,template:r,filterValues:l,isDefault:i,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:l,isDefault:i,shared:c,operation:"update"})}async function oa(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function ia(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),l=s.useDashboardStore(x=>x.lenses),{setLenses:i,setSelectedLensId:c}=s.useDashboardActions(),[o,d]=M.useState(!1),[m,h]=M.useState(!1),u=s.useDashboardStore(x=>x.dashboard),p=s.useDashboardStore(x=>x.filterValues),{authToken:g}=s.useSemaphorContext();async function f(){d(!0);const x=vs(u),S=await la(t,x,p,g==null?void 0:g.accessToken);S&&(i([...l||[],S]),c(S.id),h(!1)),d(!1)}return e.jsxs(s.Dialog,{open:m,onOpenChange:h,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:x=>{a(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:f,disabled:o,children:o?"Creating...":"Add"})})]})]})}function ca(){const[t,a]=M.useState(!1),n=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:i}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function o(h){i(h)}async function d(h){if(await oa(h,c==null?void 0:c.accessToken)){const p=n==null?void 0:n.filter(g=>g.id!==h);l(p||[]),i("original")}}async function m(h){const u=n==null?void 0:n.map(f=>f.id===h.id?{...f,isDefault:!h.isDefault}:{...f,isDefault:!1});l(u||[]);const p={...h,isDefault:!h.isDefault};await rs(p,c==null?void 0:c.accessToken);const g=n==null?void 0:n.find(f=>f.isDefault);if(g&&g.id!==h.id){const f={...g,isDefault:!1};await rs(f,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Bn,{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:o,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.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:u=>{u.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:u=>{u.preventDefault(),d(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 dt(){var i;const t=s.useDashboardStore.getState().authToken,a=s.useDashboardStore.getState().theme,n=s.useDashboardStore.getState().filterValues,r=(i=s.useDashboardStore.getState().dashboard)==null?void 0:i.title,l=s.useDashboardStore.getState().selectedSheetId;return{authToken:t,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:l||""}}async function ut(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:l,selectedSheetId:i}=dt();if(t)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",i||"");const o=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const h=(await(await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,u=document.createElement("a");u.href=h;const p=`${l}-${new Date().toISOString()}.pdf`;u.download=p,u.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function da({iconClassName:t}){const{authToken:a}=s.useSemaphorContext();s.useDashboardStore(l=>{var i;return(i=l.dashboard)==null?void 0:i.title}),s.useDashboardStore(l=>l.theme),s.useDashboardStore(l=>l.filterValues);const n=s.useDashboardStore(l=>l.isDownloadingPdf);async function r(){await ut()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function ce({defaultValue:t,label:a,options:n,value:r,onValueChange:l,className:i,icon:c,showPlaceholderLabel:o=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),o&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const Vs=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function mt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:l,error:i,isDeleting:c}=ua(),[o,d]=M.useState(""),[m,h]=M.useState(Vs[0].value),[u,p]=M.useState("06:00"),[g,f]=M.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"email",children:"Email"}),e.jsx(s.Input,{id:"email",value:o,onChange:x=>d(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(s.Input,{id:"subject",placeholder:"Monthly Sales Report",value:g,onChange:x=>{f(x.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(ce,{className:"col-span-2 h-8",label:"Select Frequency",options:Vs,value:m,onValueChange:x=>h(x)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"time",children:"Time"}),e.jsx(s.Input,{id:"time",type:"time",value:u,onChange:x=>p(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(s.Button,{onClick:async()=>{await n({email:o,frequency:m,time:u,subject:g}),p("00:00"),d(""),f("")},className:"h-8 p-2",disabled:l==="loading"||!o,children:[l==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),l==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),l==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(st,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:i})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),s.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(x=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[s.titleCase(x.frequency)," "]}),e.jsx(s.Label,{children:x.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(Us,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Sn,{className:"size-3.5"})}),e.jsx(Us,{tooltip:`${x.endUserEmail}`,children:e.jsx(Gn,{className:"size-3.5"})}),c===x.id?e.jsx(s.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(s.Trash2,{onClick:()=>r(x.id),className:"size-3.5 cursor-pointer"})]})]},x.id))})]})]})]})})]})})}const Us=({children:t,tooltip:a})=>e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:t}),e.jsx(s.TooltipContent,{children:a})]})});function ua(){const[t,a]=M.useState("idle"),[n,r]=M.useState(""),[l,i]=M.useState(null),c=s.useDashboardStore(C=>C.authToken),o=s.useDashboardStore(C=>C.dashboard.id),d=s.useDashboardStore(C=>C.dashboard.title),{endUserId:m}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),h="https://semaphor.cloud/api/v1/subscriptions/get",u={dashboardId:o,endUserId:m},{data:p,isLoading:g,isError:f,isFetching:x,refetch:S}=s.useQuery({queryKey:["subscriptions",o,m],queryFn:()=>s.getRequest(h,(c==null?void 0:c.accessToken)||"",u),enabled:!!(c!=null&&c.accessToken)&&!!o&&!!m});async function j({email:C,subject:O,frequency:D,time:N}){const{authToken:b,...k}=dt(),w=Intl.DateTimeFormat().resolvedOptions().timeZone,L={email:C,frequency:D,time:N,timezone:w,endUserId:m,endUserEmail:C,subject:O||d||"Scheduled Dashboard",dashboardId:o,dashboardParams:k};a("loading");const T="https://semaphor.cloud/api/v1/subscriptions/create";try{const R=await s.postRequestRegular(T,(b==null?void 0:b.accessToken)||"",{...L});a("success"),r(""),S(),setTimeout(()=>{a("idle")},2e3)}catch(R){console.error(R),a("error"),r(R.message)}}async function v(C){const O="https://semaphor.cloud/api/v1/subscriptions/delete";i(C);try{await s.postRequestRegular(O,(c==null?void 0:c.accessToken)||"",{id:C}),S(),setTimeout(()=>{i(null)},2e3)}catch(D){console.error(D),i(null),a("error"),r(D.message)}}return{data:p,isLoading:g,isFetching:x,isError:f,isDeleting:l,refetch:S,handleScheduleSubscription:j,handleDeleteSubscription:v,status:t,error:n}}function We(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();let n=null;a&&(a.endUserId&&a.endUserEmail&&a.tenantId?n={id:a.endUserId,name:a.endUserEmail?String(a.displayName):"",email:a.endUserEmail?String(a.endUserEmail):"",type:"tenant",tenantId:a.tenantId}:a.orgUserId&&a.orgUserEmail&&(n={id:a.orgUserId,name:a.orgUserEmail?String(a.displayName):"",email:a.orgUserEmail?String(a.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:l,isError:i}=s.useQuery({queryKey:["userInfo",n==null?void 0:n.id],queryFn:async()=>{if(!(n!=null&&n.id))return;const o=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${n.id}`,{headers:{Authorization:`Bearer ${(t==null?void 0:t.accessToken)||""}`,"Content-Type":"application/json"}});if(!o.ok)throw new Error("Failed to fetch user info");return(await o.json()).user},enabled:!!(t!=null&&t.accessToken)&&!!(n!=null&&n.id)});return{currentUser:n?{...n,...r||{}}:null,isLoading:l,isError:i}}function ht(){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,a)=>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"})})})]})]})},a))})]})})}function ma({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:i,onEditVisual:c,onUpdateVisual:o,onDeleteClick:d,onDuplicateVisual:m,onShareVisual:h,formatDate:u}){var D;const{selectVisual:p}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),[f,x]=M.useState(!1),[S,j]=M.useState(!1);M.useEffect(()=>{n?(x(!0),j(!0)):S&&(x(!1),j(!1))},[n,S]);const v=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(nt,{className:"h-3 w-3 text-purple-500"}):e.jsx(me,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(fe,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),O=()=>{p(t),c==null||c(t)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",g&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:O,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-slate-100 dark:bg-slate-800",children:C()})}),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(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:N=>o==null?void 0:o(t.id,{title:N}),isEditable:t.ownership.isOwner&&g,isPending:r,placeholder:"Untitled Visual",displayClassName:"line-clamp-1 max-w-[150px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:v()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:N=>o==null?void 0:o(t.id,{description:N}),isEditable:t.ownership.isOwner&&g,isPending:l,placeholder:"No description",displayClassName:"mt-0.5 max-w-[220px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsxs("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:N=>{N.stopPropagation(),i(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:f,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:N=>N.stopPropagation(),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(),i(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.preventDefault(),N.stopPropagation(),m(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),c==null||c(t)},children:[e.jsx(Kn,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),h(t)},children:[e.jsx(me,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),d(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"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:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(fe,{className:"h-3 w-3"}),e.jsx("span",{children:((D=t.ownership.createdBy)==null?void 0:D.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 xt({value:t,onChange:a,placeholder:n="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:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function Pe({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:l="",allowDropdown:i=!0}){var d;const c=((d=n.find(m=>m.value===t))==null?void 0:d.label)||t,o=n.filter(m=>m.value!==t);return i?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}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:i}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:o.map(m=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:m.value,disabled:r}),a(m.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]})},m.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function pt({selectedUsers:t,selectedUserObjects:a,onRemove:n,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(i=>n(i.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:a.map(i=>{const c=t.find(d=>d.id===i.id),o=l(i.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[i.name,e.jsx(Pe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(i.id,d),roleOptions:o}),e.jsx("button",{onClick:()=>n(i.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id)})}),e.jsx(s.Separator,{})]})}function ft({usersToRemove:t,allUsers:a,onRemove:n}){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=>n(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:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(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 gt({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),i=o=>{const d=a.find(m=>m.id===o);return(d==null?void 0:d.name)||"Unknown User"},c=o=>{const d=l.find(m=>m.value===o);return(d==null?void 0:d.label)||o};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(me,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(o=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:i(o.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(o.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(o.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>n(o.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id))})]})}function jt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,l=M.useRef(null);return M.useEffect(()=>{const i=c=>{const o=c.target;l.current&&l.current.contains(o)||o instanceof Element&&(o.closest("[data-radix-popper-content-wrapper]")||o.closest("[data-radix-select-content]")||o.closest("[data-radix-popover-content]")||o.closest("[data-radix-dropdown-menu-content]")||o.closest("[data-radix-tooltip-content]")||o.closest('[role="listbox"]')||o.closest('[role="option"]')||o.closest('[role="combobox"]'))||o instanceof Element&&o.hasAttribute("data-radix-")||t()};return n&&document.addEventListener(r,i),()=>{document.removeEventListener(r,i)}},[t,n,r]),l}function de(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function ha(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function yt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function xa(t,a,n){const r=yt(t),l=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(o=>o.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(o=>o.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(o=>o.tenantUserId===t.id)}function pa({user:t}){return yt(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 fa({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:l,handleUpdateAccess:i}){if(!(a!=null&&a.role))return null;const c=ha((r==null?void 0:r.type)||""),o=n.some(u=>u.id===t.id),d=n.find(u=>u.id===t.id),m=d?d.newRole:a==null?void 0:a.role,h=l(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Pe,{currentRole:m,onRoleChange:u=>{i(t.id,a.role,u)},roleOptions:h,disabled:!c,allowDropdown:c,className:o?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:de(m,h)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function ga({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&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"]}),a&&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"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Me,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function ja({isUserRemoving:t,isSelected:a,hasAccess:n,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"}),a&&!n&&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 ya({existingShares:t,allUsers:a,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,o=c.specificOrgUsers||[],d=c.specificTenantUsers||[],m=c.orgWide||[],h=c.orgUsersOnly||[],u=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:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((p,g)=>{var j,v;const f=((j=a.find(C=>C.id===p.orgUserId))==null?void 0:j.name)||"Unknown User",x=((v=a.find(C=>C.id===p.orgUserId))==null?void 0:v.type)||"",S=de(p.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:f}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:S})]},g)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.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((p,g)=>{var j,v;const f=((j=a.find(C=>C.id===p.tenantUserId))==null?void 0:j.name)||"Unknown User",x=((v=a.find(C=>C.id===p.tenantUserId))==null?void 0:v.type)||"",S=de(p.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:f}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:S})]},g)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),m.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:m.map((p,g)=>{const f=de(p.role,n(""));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:f})]},g)})})]}),h.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:h.map((p,g)=>{const f=de(p.role,n(""));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:f})]},g)})})]}),u.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:u.map((p,g)=>{const f=de(p.role,n(""));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:f})]},g)})})]}),!o.length&&!d.length&&!m.length&&!h.length&&!u.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],o=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[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,m)=>{var g,f;const h=((g=a.find(x=>x.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",u=((f=a.find(x=>x.id===d.tenantUserId))==null?void 0:f.type)||"",p=de(d.role,n(u));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:h}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:p})]},m)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:o.map((d,m)=>{const h=de(d.role,n(""));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:h})]},m)})})]}),!c.length&&!o.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const i=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:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((o,d)=>{var p,g;const m=((p=a.find(f=>f.id===o.tenantUserId))==null?void 0:p.name)||"Unknown User",h=((g=a.find(f=>f.id===o.tenantUserId))==null?void 0:g.type)||"",u=de(o.role,n(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:u})]},d)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.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((o,d)=>{const m=de(o.role,n(""));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})]},d)})})]}),!i.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function va({isInitialLoading:t,searchQuery:a,availableUsers:n}){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..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function ba({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:l,isSelected:i,selectedUser:c,roleOptions:o,currentUser:d,usersToUpdate:m,handleUserToggle:h,handleRemoveAccess:u,handleUpdateAccess:p,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":i?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!n:i,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?n?h(t.id):u(t.id):h(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(pa,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(Pe,{currentRole:a==null?void 0:a.role,onRoleChange:f=>p(t.id,a.role,f),roleOptions:o,disabled:!1,allowDropdown:!0}):e.jsx(fa,{user:t,userShare:a,usersToUpdate:m,currentUser:d,getRoleOptions:()=>o,handleUpdateAccess:p}),i&&!l&&e.jsx("div",{onClick:f=>f.stopPropagation(),children:e.jsx(Pe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:f=>g(t.id,f),roleOptions:o,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(ga,{hasAccess:r,isUserRemoving:n,isSelected:i,hasAccessFromAPI:l}),e.jsx(ja,{isUserRemoving:n,isSelected:i,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function vt({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:l=[],currentUser:i,handleUserToggle:c,handleUserRoleChange:o,handleRemoveAccess:d,handleUpdateAccess:m}){const h=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),f=s.useShareManagementActions(),x=c||(D=>{const N=h.some(k=>k.id===D),b=u.includes(D);N?f.removeSelectedUser(D):b?f.removeUserFromRemove(D):f.addSelectedUser({id:D,role:"VIEWER"})}),S=o||f.updateSelectedUserRole,j=d||f.addUserToRemove,v=m||((D,N,b)=>{f.addUserToUpdate({id:D,currentRole:N,newRole:b})}),C=l,O=u;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 (",(C??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{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(ya,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:i})})]})})]}),(C==null?void 0:C.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{h.length===C.length?f.setSelectedUsers([]):f.setSelectedUsers(C.map(D=>({id:D.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:h.length===C.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(va,{isInitialLoading:a,isSearching:n,searchQuery:g,availableUsers:C||[]}),!a&&!n&&(C==null?void 0:C.length)>0&&C.map(D=>{const N=t?xa(D,t,i):void 0,b=O.includes(D.id),k=!!N,w=k&&!b,L=h.some(A=>A.id===D.id),T=h.find(A=>A.id===D.id),R=r(D.type);return e.jsx(ba,{user:D,userShare:N,isUserRemoving:b,hasAccess:w,hasAccessFromAPI:k,isSelected:L,selectedUser:T,roleOptions:R,currentUser:i,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:j,handleUpdateAccess:v,handleUserRoleChange:S},D.id)})]})]})}function bt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const l=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(i=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:i.value,id:i.value,className:"peer sr-only",disabled:i.disabled}),e.jsxs(s.Label,{htmlFor:i.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 ${i.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[i.icon||e.jsx(fe,{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:i.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i.description})]})]})]},i.value))}),!l&&r.some(i=>i.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 ve=()=>[{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 Na({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:i=!1,isUpdating:c=!1,isRemoving:o=!1}){const d=s.useShareCurrentMode(),m=ve().filter(v=>v.value==="VIEWER"||v.value==="EDITOR"||v.value==="CONTRIBUTOR"),h=a.role!=="NONE"?a.role:"NONE",u=l?l.newRole:h,p=a.role!=="NONE"&&!i&&(!l||l.newRole===h),g=l!==null&&l.newRole!==h,f=i,x=h==="NONE"||!h,S=v=>{switch(v){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(ea,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},j=v=>{r(h,v)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!f&&!x?"border-orange-300 bg-orange-50":p?"border-green-300 bg-green-50":f||x?"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(me,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",p&&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"}),(f||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:f||x?"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:m.map(v=>e.jsxs(s.Button,{variant:u===v.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>j(v.value),disabled:n||c||o,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[S(v.value),e.jsx("span",{className:"font-medium",children:v.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:v.description})]},v.value))})]})})]})})}function Nt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:i,onRemoveAccess:c,allUsersToUpdate:o,allUsersToRemove:d}){const m=x=>x==="OWNER"?"CONTRIBUTOR":x,u=a?{role:m(a.role)}:{role:"NONE"},p=o?{currentRole:m(o.currentRole),newRole:m(o.newRole)}:null,g=(x,S)=>{i(x,S)},f=()=>{c()};return e.jsx(Na,{currentUser:t,currentShare:u,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:f,allUsersToUpdate:p,allUsersToRemove:d})}const Ca=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function Sa(t={}){var r,l,i;const{authToken:a}=s.useSemaphorContext(),n=s.useQuery({queryKey:["unified-users",t],queryFn:()=>Ca((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken),retry:(c,o)=>o instanceof Error&&o.message.includes("401")||o instanceof Error&&o.message.includes("403")?!1:c<2,retryDelay:c=>Math.min(1e3*2**c,3e4)});return{users:((r=n.data)==null?void 0:r.users)||[],userContext:(l=n.data)==null?void 0:l.userContext,total:((i=n.data)==null?void 0:i.total)||0,isLoading:n.isLoading,isError:n.isError,isFetching:n.isFetching,error:n.error,refetch:n.refetch}}function ge(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:i}=t,c=M.useMemo(()=>({search:a,active:!0,...l?{type:l}:{},...l==="tenant"&&i?{tenantId:i}:{}}),[a,l,i]),{users:o,isLoading:d,isError:m}=Sa(c),h=s.useResourceShares(r,n);return{allUsers:o,isLoadingUsers:d,isErrorLoadingUsers:m,existingShares:h.data,isLoadingShares:h.isLoading,isErrorLoadingShares:h.isError,isFetchingShares:h.isFetching}}function wa({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:i=!1,isRemoving:c=!1}){var Y,V;const o=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:m,setSearchQuery:h,debouncedSearchQuery:u}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),S=s.useShareOrgWideRole(),j=s.useShareManagementActions(),[v,C]=M.useState("specific_users"),O=()=>{if(o==="org")return"organization";if(o==="tenant")return"tenant"},D=()=>{if(o==="tenant"&&d)return d},{allUsers:N,existingShares:b,isLoadingUsers:k}=ge({debouncedSearchQuery:u,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:O(),tenantId:D()});M.useEffect(()=>{j.setCurrentContext("org-tab"),j.setCurrentMode(v==="all_users"?"allOrgUsers":"specificOrgUsers")},[j,v]);const w=q=>{var U,H;const $=q;if(C($),r==null||r($),j.setCurrentContext("org-tab"),$==="specific_users")j.setCurrentMode("specificOrgUsers");else if($==="all_users"){j.setCurrentMode("allOrgUsers");const W=(H=(U=b==null?void 0:b.shares)==null?void 0:U.orgUsersOnly)==null?void 0:H[0];W&&W.role!==void 0&&j.setOrgWideRole(W.role)}},L=N.filter(q=>q.name.toLowerCase().includes(m.toLowerCase())||q.email.toLowerCase().includes(m.toLowerCase())),T=N.filter(q=>p.some($=>$.id===q.id)),R=q=>{var W,G;const $=p.some(Z=>Z.id===q),U=g.includes(q),H=(G=(W=b==null?void 0:b.shares)==null?void 0:W.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===q);$?j.removeSelectedUser(q):U?j.removeUserFromRemove(q):H||j.addSelectedUser({id:q,role:"VIEWER"})},A=(q,$)=>{j.updateSelectedUserRole(q,$)},I=q=>{j.addUserToRemove(q),j.removeSelectedUser(q)},y=q=>{j.removeUserFromRemove(q)},E=q=>{j.removeUserFromUpdate(q)},F=(q,$)=>{j.setOrgWideRole($)},z=()=>{j.setOrgWideRole((_==null?void 0:_.role)||"NONE")},_=(V=(Y=b==null?void 0:b.shares)==null?void 0:Y.orgUsersOnly)==null?void 0:V[0];M.useEffect(()=>{v==="all_users"&&_&&_.role!==void 0&&j.setOrgWideRole(_.role)},[v,_,j]);const P=k,Q=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(bt,{shareType:v,onShareTypeChange:w,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(fe,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(me,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),v==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(xt,{value:m,onChange:h}),e.jsx(pt,{selectedUsers:p,selectedUserObjects:T,onRemove:R,onRoleChange:A,getRoleOptions:ve}),e.jsx(ft,{usersToRemove:g,allUsers:L,onRemove:y}),e.jsx(gt,{usersToUpdate:f,allUsers:L,onRemove:E,getRoleOptions:ve}),e.jsx(vt,{existingShares:b,isInitialLoading:P,isSearching:Q,resource:t,onShare:()=>{},getRoleOptions:ve,allUsers:L,currentUser:n,handleUserToggle:R,handleUserRoleChange:A,handleRemoveAccess:I,handleUpdateAccess:(q,$,U)=>{j.addUserToUpdate({id:q,currentRole:$,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Nt,{currentUser:n,currentShare:_,isSharing:l,isUpdating:i,isRemoving:c,onUpdateAccess:F,onRemoveAccess:z,allUsersToUpdate:x==="allOrgUsers"&&S!==((_==null?void 0:_.role)||"NONE")?{currentRole:(_==null?void 0:_.role)||"NONE",newRole:S}:null,allUsersToRemove:x==="allOrgUsers"&&(_==null?void 0:_.role)===void 0})})]}):null}function qs({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:i=!1,isRemoving:c=!1}){var W;const{searchQuery:o,debouncedSearchQuery:d,setSearchQuery:m}=s.useShareSearchWithDebounce(),h=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareCurrentMode(),f=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),S=s.useShareSelectedTenant(),j=s.useShareManagementActions(),{data:v,isLoading:C}=s.useTenants({enabled:(n==null?void 0:n.type)==="organization"}),[O,D]=M.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),j.setCurrentMode("specificTenantUsers")):(j.setCurrentContext("tenant-tab"),j.setCurrentMode("allTenants"))},[j,n==null?void 0:n.type]);const N=G=>{var se,ne,ee,ae;D(G);let Z;if(G==="specific_tenant_users"?Z="specific_users":G==="all_tenant_users"||G==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"&&(j.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&j.setSelectedTenant(n.tenantId))):(j.setCurrentContext("tenant-tab"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"?j.setCurrentMode("allTenantUsers"):G==="all_tenants"&&j.setCurrentMode("allTenants")),G==="all_tenant_users"){const J=(ne=(se=w==null?void 0:w.shares)==null?void 0:se.tenantWide)==null?void 0:ne[0];J&&J.role!==void 0&&j.setTenantWideRole(J.role)}else if(G==="all_tenants"){const J=(ae=(ee=w==null?void 0:w.shares)==null?void 0:ee.allTenantsOnly)==null?void 0:ae[0];J&&J.role!==void 0&&j.setAllTenantsRole(J.role)}},b=G=>{j.setSelectedTenant(G)},{allUsers:k,existingShares:w,isLoadingUsers:L,isErrorLoadingUsers:T,isLoadingShares:R,isErrorLoadingShares:A}=ge({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:S}),I=G=>{var ee,ae;const Z=h.some(J=>J.id===G),se=u.includes(G),ne=(ae=(ee=w==null?void 0:w.shares)==null?void 0:ee.specificTenantUsers)==null?void 0:ae.some(J=>J.tenantUserId===G);Z?j.removeSelectedUser(G):se?j.removeUserFromRemove(G):ne||j.addSelectedUser({id:G,role:"VIEWER"})},y=(G,Z)=>{j.updateSelectedUserRole(G,Z)},E=G=>{j.addUserToRemove(G),j.removeSelectedUser(G)},F=G=>{j.removeUserFromRemove(G)},z=G=>{j.removeUserFromUpdate(G)},_=(G,Z,se)=>{j.addUserToUpdate({id:G,currentRole:Z,newRole:se})},P=(G,Z)=>{O==="all_tenant_users"?j.setTenantWideRole(Z):O==="all_tenants"&&j.setAllTenantsRole(Z)},Q=()=>{O==="all_tenant_users"?j.setTenantWideRole("VIEWER"):O==="all_tenants"&&j.setAllTenantsRole("VIEWER")},V=(()=>{var G,Z,se,ne;return g==="allTenants"?(Z=(G=w==null?void 0:w.shares)==null?void 0:G.allTenantsOnly)==null?void 0:Z[0]:g==="allTenantUsers"?(ne=(se=w==null?void 0:w.shares)==null?void 0:se.tenantWide)==null?void 0:ne[0]:null})();M.useEffect(()=>{var G,Z,se,ne;if(O==="all_tenant_users"){const ee=(Z=(G=w==null?void 0:w.shares)==null?void 0:G.tenantWide)==null?void 0:Z[0];ee&&ee.role!==void 0&&j.setTenantWideRole(ee.role)}else if(O==="all_tenants"){const ee=(ne=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:ne[0];ee&&ee.role!==void 0&&j.setAllTenantsRole(ee.role)}},[O,w,j]);const q=k.filter(G=>h.some(Z=>Z.id===G.id)),$=L||R,U=T||A,H=()=>(n==null?void 0:n.type)==="tenant"||O==="all_tenants"?!0:S&&(O==="specific_tenant_users"||O==="all_tenant_users");return e.jsxs(e.Fragment,{children:[U&&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"})]})}),!U&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(bt,{shareType:O,onShareTypeChange:N,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(me,{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(fe,{className:"mb-3 h-6 w-6 text-orange-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(zs,{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(fe,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(O==="specific_tenant_users"||O==="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:S||"",onValueChange:b,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(W=v==null?void 0:v.tenants)==null?void 0:W.map(G=>e.jsx(s.SelectItem,{value:G.id,children:G.name},G.id))})]})]}),H()?e.jsx(e.Fragment,{children:O==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(xt,{value:o,onChange:m}),e.jsx(pt,{selectedUsers:h,selectedUserObjects:q,onRemove:G=>I(G),onRoleChange:y,getRoleOptions:ve}),e.jsx(ft,{usersToRemove:u,allUsers:k,onRemove:F}),e.jsx(gt,{usersToUpdate:p,allUsers:k,onRemove:z,getRoleOptions:ve}),e.jsx(vt,{existingShares:w,isInitialLoading:!!$,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:ve,allUsers:k,currentUser:n,handleUserToggle:I,handleUserRoleChange:y,handleRemoveAccess:E,handleUpdateAccess:_})]}):O==="all_tenant_users"||O==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Nt,{currentUser:n,currentShare:V,isSharing:l,isUpdating:i,isRemoving:c,onUpdateAccess:P,onRemoveAccess:Q,allUsersToUpdate:g==="allTenantUsers"&&((V==null?void 0:V.role)===void 0||f!==V.role)||g==="allTenants"&&((V==null?void 0:V.role)===void 0||x!==V.role)?{currentRole:(V==null?void 0:V.role)||"VIEWER",newRole:g==="allTenantUsers"?f:x}:null,allUsersToRemove:g==="allTenantUsers"&&(V==null?void 0:V.role)===void 0||g==="allTenants"&&(V==null?void 0:V.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(O==="specific_tenant_users"||O==="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(zs,{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"})]})})]})]})}const Ct=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),i=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),o=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),m=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:i,orgWideRole:c,allTenantsRole:o,tenantWideRole:d}),[t,a,n,r,l,i,c,o,d]),h=M.useMemo(()=>p=>s.validateShareData(p),[]),u=M.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!i)return!1}else if(a==="specificTenantUsers")return i?n.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||l.length>0:!0}return!1},[t,a,n,r,l,i]);return{buildShareData:m,validateShareData:h,isCurrentStateValid:u,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:i,orgWideRole:c,allTenantsRole:o,tenantWideRole:d}};function $s({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:l,onShare:i,onClose:c,shareTabType:o,currentAllUsersShare:d,onRemoveAccess:m}){const h=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const g=s.useShareSelectedTenant();s.useShareSelectedTab();const f=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),S=s.useShareTenantWideRole(),{buildShareData:j,validateShareData:v,isCurrentStateValid:C}=Ct(),O=n||r||l,D=()=>{var L,T,R,A;if(O)return"Updating...";if(o==="specific_users"){if(h.length===0&&u.length===0&&p.length===0)return"Select users to share with";const I=h.length+u.length+p.length;return I===0?"Select users to share with":h.length>0&&u.length>0?`Update access for ${I} user${I!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Share with ${h.length} user${h.length!==1?"s":""}`:p.length>0&&h.length===0&&u.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}else if(o==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const I=d.role;return f===I?"Remove Access":"Update Access"}else if(o==="all_tenants"){const I=(T=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:T[0];if(!I||I.role===void 0)return"Share with All Tenants";const y=I.role;return x===y?"Remove Access":"Update Access"}else if(o==="all_tenant_users"){const I=(A=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const y=I.role;return S===y?"Remove Access":"Update Access"}else if(o==="specific_tenant_users"){if(h.length===0&&u.length===0&&p.length===0)return"Select users to share with";const I=h.length+u.length+p.length;return I===0?"Select users to share with":h.length>0&&u.length>0?`Update access for ${I} user${I!==1?"s":""}`:u.length>0&&h.length===0&&p.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:h.length>0&&u.length===0&&p.length===0?`Share with ${h.length} user${h.length!==1?"s":""}`:p.length>0&&h.length===0&&u.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${I} user${I!==1?"s":""}`}return"Share"},N=()=>O||!t||o==="all_tenant_users"&&!g||o==="specific_tenant_users"&&!g?!0:!C,b=()=>{const L=j();L&&v(L)&&i(L)},k=()=>{var L,T,R,A;if(o==="all_users")if(!d||d.role===void 0){const I=j();I&&v(I)&&i(I)}else{const I=d.role;if(f===I)m==null||m();else{const E=j();if(E&&v(E)){const F={...E,updateAccess:!0};i(F)}}}else if(o==="all_tenants"){const I=(T=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:T[0];if(!I||I.role===void 0){const y=j();y&&v(y)&&i(y)}else{const y=I.role;if(x===y)m==null||m();else{const F=j();if(F&&v(F)){const z={...F,updateAccess:!0};i(z)}}}}else if(o==="all_tenant_users"){const I=(A=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0){const y=j();y&&v(y)&&i(y)}else{const y=I.role;if(S===y)m==null||m();else{const F=j();if(F&&v(F)){const z={...F,updateAccess:!0};i(z)}}}}},w=()=>{var L,T,R,A;if(o==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return f===I?"destructive":"default"}else if(o==="all_tenants"){const I=(T=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:T[0];if(!I||I.role===void 0)return"default";const y=I.role;return x===y?"destructive":"default"}else if(o==="all_tenant_users"){const I=(A=(R=a==null?void 0:a.shares)==null?void 0:R.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"default";const y=I.role;return S===y?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:O,children:"Close"}),(o==="specific_users"||o==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(h.length>0||u.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:b,disabled:!t||O,variant:"default",children:[O?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Me,{className:"mr-2 h-4 w-4"}),!O&&D()]})}),(o==="all_users"||o==="all_tenants"||o==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,disabled:N(),variant:w(),children:[O?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(me,{className:"mr-2 h-4 w-4"}),!O&&D()]})]})}function Ta({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:l,onClose:i,shareTabType:c,currentAllUsersShare:o}){const d=s.useShareSelectedUsers(),m=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const u=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:g,isCurrentStateValid:f}=Ct(),x=a||n||r,S=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&m.length===0&&h.length===0)return"Select users to share with";const D=d.length+m.length+h.length;return D===0?"Select users to share with":d.length>0&&m.length>0?`Update access for ${D} user${D!==1?"s":""}`:m.length>0&&d.length===0&&h.length===0?`Remove access for ${m.length} user${m.length!==1?"s":""}`:d.length>0&&m.length===0&&h.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:h.length>0&&d.length===0&&m.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${D} user${D!==1?"s":""}`}else if(c==="all_users"){if(!o||o.role==="NONE")return"Share with All Users";const D=o.role;return u===D?"Remove Access":"Update Access"}return"Share"},j=()=>x||!t?!0:!f,v=()=>{const D=p();D&&g(D)&&l(D)},C=()=>{if(!o||o.role==="NONE"){const D=p();D&&g(D)&&l(D)}else{const D=o.role;if(u===D){const b=p();if(b&&g(b)){const k={...b,removeAccess:!0};l(k)}}else{const b=p();if(b&&g(b)){const k={...b,updateAccess:!0};l(k)}}}},O=()=>!o||o.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:i,disabled:x,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||m.length>0||h.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||x,variant:"default",children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Me,{className:"mr-2 h-4 w-4"}),!x&&S()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:C,disabled:j(),variant:O(),children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Me,{className:"mr-2 h-4 w-4"}),!x&&S()]})]})}function St({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:l,onClose:i,onShare:c,onRemoveAccess:o}){var b,k,w,L;const{currentUser:d}=We(),[m,h]=M.useState("specific_users"),[u,p]=M.useState("specific_users"),g=s.useShareManagementActions(),f=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:S}=ge({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:j}=ge({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),v=(k=(b=S==null?void 0:S.shares)==null?void 0:b.tenantWide)==null?void 0:k[0],C=(L=(w=j==null?void 0:j.shares)==null?void 0:w.orgUsersOnly)==null?void 0:L[0],O=()=>{if(f==="org")return u;switch(x){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},D=M.useCallback(()=>{g.resetShareState(),i()},[g,i]),N=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:D,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(Me,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:N?"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."})]}),N?e.jsxs(s.Tabs,{value:f,onValueChange:T=>{const R=T;g.setSelectedTab(R),g.resetUserSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"})]}),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(wa,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:p,isSharing:n,isUpdating:l,isRemoving:r})})}),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:a,currentUser:d,onShareTabTypeChange:T=>h(T),isSharing:n,isUpdating:l,isRemoving:r})})})]}):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:a,currentUser:d,onShareTabTypeChange:T=>h(T),isSharing:n,isUpdating:l,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:N?f==="org"?e.jsx($s,{resource:t,existingShares:j,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:i,shareTabType:u,currentAllUsersShare:C,onRemoveAccess:o}):e.jsx($s,{resource:t,existingShares:S,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:i,shareTabType:O(),currentAllUsersShare:v,onRemoveAccess:o}):e.jsx(Ta,{resource:t,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:i,shareTabType:m,currentAllUsersShare:v,onRemoveAccess:o})})]})})}function ie(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function pe(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function wt(t,a){const{resourceType:n,resourceId:r,shareMutation:l,removeMutation:i,existingShares:c,resetUserSelections:o}=a;if(r)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=ie(n,r,[{scope:"org_users_only",role:t.orgWideRole}]);l(d,{onSuccess:()=>{o()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h}=t;if(d&&d.length>0){const u=ie(n,r,d.map(p=>({scope:"specific_org_user",orgUserId:p.id,role:p.role})));l(u,{onSuccess:()=>{o()}})}if(m&&m.length>0){const u=pe(n,r,m.map(p=>{var f,x;const g=(x=(f=c==null?void 0:c.shares)==null?void 0:f.specificOrgUsers)==null?void 0:x.find(S=>S.orgUserId===p);return{scope:"specific_org_user",orgUserId:p,role:(g==null?void 0:g.role)||"VIEWER"}}));i(u,{onSuccess:()=>{o()}})}h&&h.length>0&&h.forEach(u=>{const p=ie(n,r,[{scope:"specific_org_user",orgUserId:u.id,role:u.newRole}]);l(p,{onSuccess:()=>{o()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=ie(n,r,[{scope:"all_tenants_only",role:t.allTenantsRole}]);l(d,{onSuccess:()=>{o()}})}else if(t.mode==="allTenantUsers"){const d=ie(n,r,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);l(d,{onSuccess:()=>{o()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h,tenantId:u}=t;if(m&&m.length>0){const p=pe(n,r,m.map(g=>{var x,S;const f=(S=(x=c==null?void 0:c.shares)==null?void 0:x.specificTenantUsers)==null?void 0:S.find(j=>j.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,tenantId:u,role:(f==null?void 0:f.role)||"VIEWER"}}));i(p,{onSuccess:()=>{o()}})}if(h&&h.length>0&&h.forEach(p=>{const g=ie(n,r,[{scope:"specific_tenant_user",tenantUserId:p.id,tenantId:u,role:p.newRole}]);l(g,{onSuccess:()=>{o()}})}),d&&d.length>0){const p=ie(n,r,d.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,tenantId:u,role:g.role})));l(p,{onSuccess:()=>{o()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=pe(n,r,[{scope:"all_tenant_users",role:"VIEWER"}]);i(d,{onSuccess:()=>{o()}})}else if(t.updateAccess){const d=ie(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);l(d,{onSuccess:()=>{o()}})}else{const d=ie(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);l(d,{onSuccess:()=>{o()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h}=t;if(d&&d.length>0){const u=ie(n,r,d.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,role:p.role})));l(u,{onSuccess:()=>{o()}})}if(m&&m.length>0){const u=pe(n,r,m.map(p=>{var f,x;const g=(x=(f=c==null?void 0:c.shares)==null?void 0:f.specificTenantUsers)==null?void 0:x.find(S=>S.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,role:(g==null?void 0:g.role)||"VIEWER"}}));i(u,{onSuccess:()=>{o()}})}h&&h.length>0&&h.forEach(u=>{const p=ie(n,r,[{scope:"specific_tenant_user",tenantUserId:u.id,role:u.newRole}]);l(p,{onSuccess:()=>{o()}})})}break}}function Tt(t,a,n,r){var m,h,u,p,g,f;const{resourceType:l,resourceId:i,removeMutation:c,existingShares:o,resetUserSelections:d}=r;if(i)if(t.length>0){const x=pe(l,i,t.map(S=>{var v,C;const j=(C=(v=o==null?void 0:o.shares)==null?void 0:v.specificTenantUsers)==null?void 0:C.find(O=>O.tenantUserId===S);return{scope:"specific_tenant_user",tenantUserId:S,role:(j==null?void 0:j.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:S=>{console.error("Remove access failed:",S)}})}else{const x=a==="tenant"&&n==="allTenants",S=a==="tenant"&&n==="allTenantUsers";if(x){const j=(h=(m=o==null?void 0:o.shares)==null?void 0:m.allTenantsOnly)==null?void 0:h[0];if(j){const v=pe(l,i,[{scope:"all_tenants_only",role:j.role}]);c(v,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenants access failed:",C)}})}}else if(S){const j=(p=(u=o==null?void 0:o.shares)==null?void 0:u.tenantWide)==null?void 0:p[0];if(j){const v=pe(l,i,[{scope:"all_tenant_users",role:j.role}]);c(v,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenant-users access failed:",C)}})}}else{const j=(f=(g=o==null?void 0:o.shares)==null?void 0:g.orgUsersOnly)==null?void 0:f[0];if(j){const v=pe(l,i,[{scope:"org_users_only",role:j.role}]);c(v,{onSuccess:()=>{d()},onError:C=>{console.error("Remove org-wide access failed:",C)}})}}}}function ka(t,a,n){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),i=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:o}=ge({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),m=M.useCallback(u=>{if(!t)return;const p={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:o,resetUserSelections:d};wt(u,p)},[t,a,n,o,d]),h=M.useCallback(()=>{if(!t)return;const u={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:n,existingShares:o,resetUserSelections:d};Tt(l,i||"",c||"",u)},[t,a,n,o,d,l,i,c]);return{handleShareSubmit:m,handleRemoveAccess:h}}function Da(t,a,n){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),i=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:o}=ge({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),m=M.useCallback(u=>{if(!t)return;const p={resourceType:s.ResourceType.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:o,resetUserSelections:d};wt(u,p)},[t,a,n,o,d]),h=M.useCallback(()=>{if(!t)return;const u={resourceType:s.ResourceType.VISUAL,resourceId:t,removeMutation:n,existingShares:o,resetUserSelections:d};Tt(l,i||"",c||"",u)},[t,a,n,o,d,l,i,c]);return{handleShareSubmit:m,handleRemoveAccess:h}}function Ea(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),[l,i]=M.useState(""),[c,o]=M.useState(""),[d,m]=M.useState(!1),[h,u]=M.useState(null),[p,g]=M.useState(!1),[f,x]=M.useState(null),[S,j]=M.useState(null),{setIsDashboardEditing:v,setIsVisualEditing:C}=s.useDashboardActions(),{handleEditLibraryVisual:O,handleAddLibraryVisual:D}=s.useVisualUtils(),{resources:N,isLoading:b,isError:k,createResource:w,updateResource:L,deleteResource:T,duplicateResource:R,shareResource:A,isCreating:I,isDeleting:y,removeResourceShares:E,isSharing:F,isRemovingShares:z,isUpdatingShares:_}=s.useVisualManagement(()=>{g(!1),x(null)},()=>{r(!1),i(""),o("")}),{handleShareSubmit:P,handleRemoveAccess:Q}=Da((h==null?void 0:h.id)||null,A,E);We();const Y=N.filter(B=>{var K,re;return((K=B==null?void 0:B.title)==null?void 0:K.toLowerCase().includes(t.toLowerCase()))||((re=B==null?void 0:B.description)==null?void 0:re.toLowerCase().includes(t.toLowerCase()))}),V=B=>new Date(B).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{l.trim()&&w({title:l,description:c,isPrivate:!1})},$=B=>{x(B),g(!0)},U=()=>{f&&T(f.id)},{startUpdating:H,stopUpdating:W,isUpdating:G}=s.useResourceUpdateState(),Z=(B,K)=>{const re=K.title!==void 0?"title":"description";H(B,re),L({resourceId:B,data:K},{onSuccess:()=>{W(B,re)},onError:()=>{W(B,re)}})},se=B=>{j(B),R(B,{onSettled:()=>j(null)})},ne=B=>{O(B)},ee=B=>{D(B)},ae=B=>{const K=N.find(re=>re.id===B);K&&L({resourceId:B,data:{isPrivate:!K.isPrivate}})},J=B=>{u(B),m(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),ge({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),b?e.jsx(ht,{}):k?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:n?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:B=>i(B.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:B=>o(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:q,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||I,children:I?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),i(""),o("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:I,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),I?"Creating...":"Create New Visual"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:B=>a(B.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:Y.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(He,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):Y.map(B=>e.jsx(ma,{visual:B,onAddVisual:ee,onEditVisual:ne,onUpdateVisual:Z,onDeleteClick:$,onDuplicateVisual:se,onTogglePrivacy:ae,onShareVisual:J,isDeleting:y,isDuplicating:S===B.id,isTitleUpdating:G(B.id,"title"),isDescriptionUpdating:G(B.id,"description"),formatDate:V},B.id))})}),d&&h&&e.jsx(St,{resource:h,resourceType:s.ResourceType.VISUAL,onShare:P,isSharing:F,isRemoving:z,isUpdating:_,onClose:()=>{m(!1),u(null)},onRemoveAccess:Q}),e.jsx(s.AlertDialog,{open:p,onOpenChange:B=>{!B&&y||(g(B),B||x(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',f==null?void 0:f.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:y,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:B=>{B.preventDefault(),B.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,children:y?"Deleting...":"Delete"})]})]})})]})}function Ia({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:i,onUpdateDashboard:c,onDeleteClick:o,onDuplicateDashboard:d,onShareDashboard:m,formatDate:h,onDashboardItemClick:u}){var D;const{selectDashboard:p}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),[f,x]=M.useState(!1),[S,j]=M.useState(!1);M.useEffect(()=>{n?(x(!0),j(!0)):S&&(x(!1),j(!1))},[n,S]);const v=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(nt,{className:"h-3 w-3 text-purple-500"}):e.jsx(me,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(fe,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),O=()=>{p(t),i(t.id),u==null||u(t.id)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",g&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:O,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-slate-100 dark:bg-slate-800",children:C()})}),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(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:N=>c==null?void 0:c(t.id,{title:N}),isEditable:t.permissions.canEdit&&g,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"line-clamp-1 max-w-[220px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:v()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:N=>c==null?void 0:c(t.id,{description:N}),isEditable:t.permissions.canEdit&&g,isPending:l,placeholder:"No description",displayClassName:"mt-0.5 max-w-[250px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsx("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:e.jsxs(s.DropdownMenu,{modal:!1,open:f,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:N=>N.stopPropagation(),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.preventDefault(),N.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),m(t)},children:[e.jsx(me,{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:N=>{N.stopPropagation(),o(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"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:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(fe,{className:"h-3 w-3"}),e.jsx("span",{children:((D=t.ownership.createdBy)==null?void 0:D.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:h(t.lastModified)})]})]})]})]})})})]})]},t.id)}function Aa({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 Ma(t){const[a,n]=M.useState(""),[r,l]=M.useState(!1),[i,c]=M.useState(""),[o,d]=M.useState(""),[m,h]=M.useState(!1),[u,p]=M.useState(null),[g,f]=M.useState(!1),[x,S]=M.useState(null),[j,v]=M.useState(null),C=s.useManagementStore(J=>J.lastSelectedDashboard),O=s.useManagementStore(J=>J.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:D,isLoading:N,isError:b,createResource:k,updateResource:w,deleteResource:L,duplicateResource:T,isCreating:R,isDeleting:A,isSharing:I,isRemovingShares:y,isUpdatingShares:E,shareResource:F,removeResourceShares:z}=s.useDashboardManagement(()=>{f(!1),S(null),C&&O(C)},()=>{l(!1),c(""),d("")}),{handleShareSubmit:_,handleRemoveAccess:P}=ka((u==null?void 0:u.id)||null,F,z),{currentUser:Q}=We(),Y=D.filter(J=>{var B,K;return((B=J==null?void 0:J.title)==null?void 0:B.toLowerCase().includes(a.toLowerCase()))||((K=J==null?void 0:J.description)==null?void 0:K.toLowerCase().includes(a.toLowerCase()))}),V=J=>new Date(J).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{i.trim()&&k({title:i,description:o,isPrivate:!1})},$=J=>{var B;(B=t.onLoadDashboard)==null||B.call(t,J)},U=J=>{S(J),f(!0)},H=()=>{x&&L(x.id)},W=J=>{v(J),T(J,{onSettled:()=>v(null)})},{startUpdating:G,stopUpdating:Z,isUpdating:se}=s.useResourceUpdateState(),ne=(J,B)=>{const K=B.title!==void 0?"title":"description";G(J,K),w({resourceId:J,data:B},{onSuccess:()=>{Z(J,K)},onError:()=>{Z(J,K)}})},ee=J=>{const B=D.find(K=>K.id===J);B&&w({resourceId:J,data:{isPrivate:!B.isPrivate}})},ae=J=>{p(J),Q==null||Q.type,h(!0)};return ge({debouncedSearchQuery:"",resourceId:(u==null?void 0:u.id)||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),N?e.jsx(ht,{}):b?e.jsx(Aa,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:i,onChange:J=>c(J.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:o,onChange:J=>d(J.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:q,size:"sm",className:"h-7 text-xs",disabled:!i.trim()||R,children:R?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:R,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"h-8 w-full",size:"sm",disabled:R,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),R?"Creating...":"Create New Dashboard"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:a,onChange:J=>n(J.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:Y.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(Rn,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):Y.map(J=>e.jsx(Ia,{dashboard:J,isDeleting:A,isDuplicating:j===J.id,isTitleUpdating:se(J.id,"title"),isDescriptionUpdating:se(J.id,"description"),onLoadDashboard:$,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ne,onDeleteClick:U,onDuplicateDashboard:W,onTogglePrivacy:ee,onShareDashboard:ae,formatDate:V,onDashboardItemClick:t.onDashboardItemClick},J.id))})}),m&&u&&e.jsx(St,{resource:u,resourceType:s.ResourceType.DASHBOARD,onShare:_,isSharing:I,isRemoving:y,isUpdating:E,onClose:()=>{h(!1),p(null)},onRemoveAccess:P}),e.jsx(s.AlertDialog,{open:g,onOpenChange:J=>{!J&&A||(f(J),J||S(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 "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:J=>{J.preventDefault(),J.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function kt({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(g=>g.dashboard);const{setDashboard:l,addSheet:i}=s.useDashboardStore(g=>g.actions),{currentUser:c}=We(),o=c,[d,m]=s.useLocalStorageState("resource-management-active-tab","dashboards"),h=jt(a,{enabled:t}),u=g=>{},p=g=>{console.log("Editing dashboard:",g)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:h,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"-translate-x-full",n),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:o&&e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-muted bg-muted/30 px-2 py-1",children:[e.jsxs(s.Avatar,{className:"h-5 w-5",children:[e.jsx(s.AvatarImage,{alt:o.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:o.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:o.name})]})}),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:o.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:o.email}),o.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(o.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",o.id]})]})})]})})}),e.jsx(s.IconButton,{className:"h-6 p-1 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Hide Dashboard Management",children:e.jsx(s.X,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:d,onValueChange:m,className:"flex h-9 grow flex-col",children:[e.jsx("div",{className:"px-5",children:e.jsxs(s.TabsList,{className:"grid h-8 w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"h-6",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"h-6",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1",children:e.jsx(Ma,{onLoadDashboard:u,onEditDashboard:p,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Ea,{})})]})})]})})}function La(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(E=>E.theme);const n=s.useDashboardStore(E=>E.lenses),r=s.useDashboardStore(E=>E.selectedLensId),l=n==null?void 0:n.find(E=>E.id===r),i=s.useDashboardStore(E=>E.dashboard);s.useDashboardStore(E=>E.selectedSheetId);const c=s.useDashboardStore(E=>E.isDashboardEditing),o=s.useEditorStore(E=>E.card),d=s.useEditorStore(E=>E.selectedConnectionId),[m,h]=M.useState(!1),u=s.useDashboardStore(E=>E.isDashboardPanelOpen),p=s.useDashboardStore(E=>E.actions.setIsDashboardPanelOpen),g=s.useDashboardStore(E=>E.filterValues),f=s.useDashboardStore(E=>E.isVisualEditing),x=s.useDashboardStore(E=>E.showFilters);s.useDashboardStore(E=>E.showDashboardJSON);const S=s.useDashboardStore(E=>E.onSaveFunction),j=s.useDashboardStore(E=>E.actions.setShowFilters),{addFrame:v,setSelectedFrameId:C}=s.useDashboardStore(E=>E.actions),{getSelectedSheet:O,setIsDashboardEditing:D,setShowDashboardJSON:N}=s.useDashboardStore(E=>E.actions),b=O(),{tenantId:k,endUserId:w}=M.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),L=M.useMemo(()=>k||w,[k,w]),T=()=>{if(!c||!b)return;const E={dataSource:o.dataSource,mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},F={id:s.v4(),cards:[E],activeCardId:E.id};v(b.id,F),C(F.id)},R=()=>{D(!0)};async function A(){if(h(!0),!r||!l)return;const E=vs(i),F=JSON.stringify(E),z={...l,template:F,filterValues:g};await rs(z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),S==null||S(E),h(!1)}if(f)return null;const I=(l==null?void 0:l.name)||i.title,y=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[y&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(Pn,{className:"h-4 w-4"})}),!f&&e.jsx(s.Label,{children:I})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!f&&e.jsx(da,{}),!f&&e.jsx(mt,{}),c&&!f&&L&&e.jsx(ia,{}),!f&&L&&e.jsx(ca,{}),c&&!f&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:T,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!f&&e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2",onClick:R,size:"sm",children:e.jsx(s.Pencil,{className:"h-4 w-4"})}),c&&!f&&e.jsx(s.IconButton,{className:"h-7 p-2",onClick:()=>{D(!1),N(!1)},children:e.jsx(s.Cross2Icon,{className:"h-4 w-4"})}),c&&!f&&L&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",disabled:m,onClick:A,size:"sm",children:e.jsx(s.Save,{className:"h-4 w-4"})}),!x&&!f&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>j(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!f&&c&&!1,!f&&!1,!f&&e.jsx(kt,{isOpen:u,onClose:()=>p(!1)})]})]})}function Oa({name:t,items:a,value:n,onChange:r,isLoading:l,isError:i,refetch:c,className:o,icon:d,showNone:m=!1}){const h=ye.useRef(null),[u,p]=ye.useState(!1),[g,f]=ye.useState("100%"),x=m?[...a||[],{id:"none",name:"None"}]:a;ye.useLayoutEffect(()=>{h.current&&f(h.current.offsetWidth)},[]);function S(){var v;return l?"Loading...":i?"Error":n?(v=a==null?void 0:a.find(C=>C.id===n))==null?void 0:v.name:`Select ${t}`}function j(v,C){r(C),p(!1)}return e.jsxs(s.Popover,{open:u,onOpenChange:p,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:h,variant:"outline",role:"combobox","aria-expanded":u,className:s.cn("flex h-9 w-full justify-between",o),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:S()})]}),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(at,{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:x==null?void 0:x.map(v=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:v.name,onSelect:C=>j(C,v.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===v.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:v.name,children:v.name})]})},v.id))})]})]})})]})}function ke({title:t,items:a,value:n,isLoading:r,isError:l,refetch:i,onChange:c,showNone:o=!1,className:d,disabled:m=!1,type:h="combobox"}){const u=r?"Loading...":l?"Error":n;function p(){if(t==="Connection")return e.jsx(Qn,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Yn,{className:"size-4"});if(t==="Table")return e.jsx(Je,{className:"size-4"});if(t==="Model")return e.jsx(vn,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:m,value:u,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(at,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:i})]}),e.jsxs(e.Fragment,{children:[o&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((x,S)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},S))]}),(r||l)&&e.jsx(s.SelectItem,{value:u,children:u})]})})]})}function f(){return e.jsx(Oa,{icon:p(),items:a,value:u,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:i,name:t,showNone:o})}return e.jsx(s.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:h==="select"?g():f()})})}function Ra({column:t}){const[a,n]=M.useState(!1),r=s.useEditorStore(x=>x.selectedTableName),l=s.useEditorStore(x=>x.selectedSchemaName),i=s.useEditorStore(x=>x.selectedDatabaseName),c=s.useEditorStore(x=>x.selectedDatamodelId),o=s.useEditorStore(x=>x.sqlGen),{modelItems:d,connectionType:m}=s.useEditorAside(),h=s.useEditorStore(x=>x.actions.setSqlGen),u=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function g(x,S){var O;const j=s.createSqlGenConfig(x,o,S),v=(O=d==null?void 0:d.find(D=>D.id===c))==null?void 0:O.name;h(j);const C=s.getSql(j,s.fmt(l||""),s.fmt(r),v||"",m,i||"");C&&(u(C),p(!0)),n(!1)}function f(){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:a,onOpenChange:n,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:f()})]})}function bs({column:t}){return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger$1,{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(fs,{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(ot,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(bn,{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 Qe({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(bs,{column:t}),e.jsx("span",{children:t.column_name})]})}function Ba({id:t,children:a,type:n="column"}){const{attributes:r,listeners:l,setNodeRef:i,transform:c}=s.useDraggable({id:t,data:{type:n}}),o=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:i,style:o,...l,...r,children:a})}function Fa({onClick:t,column:a}){const n=s.useDndStore(h=>h.activeId),r=s.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.groupByColumns}),l=s.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.metricColumns}),i=s.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.filterColumns});function c(h){return o(h)||d(h)||m(h)}function o(h){return r==null?void 0:r.some(u=>u.name===h.column_name)}function d(h){return l==null?void 0:l.some(u=>u.name===h.column_name)}function m(h){return i==null?void 0:i.some(u=>u.name===h.column_name)}return e.jsxs("div",{onClick:()=>t(a),className:s.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(Qe,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(Qe,{column:a})}),e.jsx(Ba,{id:a.column_name,type:"column",children:e.jsx(Qe,{column:a})})]})}const Xe={id:"__placeholder__",role:"groupby",type:"string"},Ze={id:"__placeholder__",role:"groupby",type:"string"},es={id:"__placeholder__",role:"metric",type:"number"},ss={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},Dt={id:"__placeholder__"},be="droppable-group-by",Ne="droppable-metrics",Ce="droppable-pivot-by",_e="sortable-group-by",ls="sortable-metrics",Ve="sortable-pivot-by",os="droppable-filters",is="sortable-filters",Ns="sortable-order-by";function za(){const t=s.useDndStore(I=>I.insertIndex),a=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.groupByColumns)||[]}),n=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.metricColumns)||[]}),r=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.filterColumns)||[]}),l=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.orderBy)||[]}),i=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:o,setPreviewGroupByColumns:d,setPreviewMetricColumns:m,setPreviewFilterColumns:h,setPreviewPivotColumns:u}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:g,setFilterColumns:f,setOrderByColumns:x,setPivotByColumns:S}=s.useEditorActions(),{columns:j}=s.useDataColumns(),{formattedTableName:v}=s.useEditorAside(),C=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),O=I=>{var F;const{active:y,over:E}=I;if(((F=y.data.current)==null?void 0:F.type)==="column"&&E){const z=E.id,_=j.find(V=>V.column_name===y.id);if(!_)return;const P=s.isNumberDataType(_.data_type),Q=s.isTextDataType(_.data_type),Y=s.isDateDataType(_.data_type);if(Q||Y){if(a.some(q=>q.id===z)){const q=a.findIndex(U=>U.id===z);c(q);const $=a.filter(U=>U.id!==Xe.id);$.splice(q,0,Xe),d($)}else if(E.id===be){c(a.length);const q=[...a,Xe];d(q),m(n),h(r)}}if(Q||Y){if(i.some(q=>q.id===z)){const q=i.findIndex(U=>U.id===z);c(q);const $=i.filter(U=>U.id!==Ze.id);$.splice(q,0,Ze),u($)}else if(E.id===Ce){c(i.length);const q=[...i,Ze];u(q),d(a),m(n),h(r)}}if(P||Q){if(n.some(q=>q.id===z)){console.log("isOverMetricSortable",z);const q=n.findIndex(U=>U.id===z);c(q);const $=n.filter(U=>U.id!==es.id);$.splice(q,0,es),m($)}else if(E.id===Ne){c(n.length);const q=[...n,es];m(q),h(r),d(a),u(i)}}if(N(_)){if(r.some(q=>q.id===z)){const q=r.findIndex(U=>U.id===z);c(q);const $=r.filter(U=>U.id!==ss.id);$.splice(q,0,ss),h($)}else if(E.id===os){c(r.length);const q=[...r,ss];h(q),m(n),d(a),u(i)}}}else d(a),m(n),h(r),u(i)};function D(I){o(I.active.id),c(null),d(a),m(n),h(r),u(i)}function N(I){return!r.some(y=>y.name===I.column_name)}function b(I,y="SUM"){const{column_name:E,data_type:F}=I,z=[...n],_=t!==null?t:n.length,P={...I,id:ue(E),name:E,label:Le(E,y),type:F,role:"metric",aggregate:y};z.splice(_,0,P),g(z)}function k(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const E=[...i],F=t!==null?t:i.length;let z;y?z={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:De(I.column_name,"month"),granularity:"month"},E.splice(F,0,z),S(E)}function w(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const E=[...a],F=t!==null?t:a.length;let z;y?z={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:De(I.column_name,"month"),granularity:"month"},E.splice(F,0,z),p(E)}function L(I){const y=[...r],E=t!==null?t:r.length,F={...I,id:ue(I.column_name),name:I.column_name,type:I.data_type,sql:s.getDefaultFilterSql(I.data_type,v,s.fmt(I.column_name)),role:"filter"};y.splice(E,0,F),f(y)}function T(I){var z,_,P,Q,Y,V,q,$;const{active:y,over:E}=I,F=y.data.current;if((F==null?void 0:F.type)==="column"&&E){const U=j.find(Z=>Z.column_name===y.id);if(!U)return;const H=s.isNumberDataType(U.data_type),W=s.isTextDataType(U.data_type),G=s.isDateDataType(U.data_type);(W||G)&&(E.id===be||((z=E.data.current)==null?void 0:z.type)===_e)&&w(U),(W||G)&&(E.id===Ce||((_=E.data.current)==null?void 0:_.type)===Ve)?k(U):(H||W)&&(E.id===Ne||((P=E.data.current)==null?void 0:P.type)===ls)?(H&&b(U),W&&b(U,"COUNT")):N(U)&&(E.id===os||((Q=E.data.current)==null?void 0:Q.type)===is)&&L(U)}if(E&&((Y=E.data.current)==null?void 0:Y.type)===_e&&a.some(U=>U.id===y.id)){const U=a.findIndex(W=>W.id===y.id),H=a.findIndex(W=>W.id===E.id);if(U!==-1&&H!==-1&&U!==H){const W=[...a],[G]=W.splice(U,1);W.splice(H,0,G),p(W)}}if(E&&((V=E.data.current)==null?void 0:V.type)===Ve&&i.some(U=>U.id===y.id)){const U=i.findIndex(W=>W.id===y.id),H=i.findIndex(W=>W.id===E.id);if(U!==-1&&H!==-1&&U!==H){const W=[...i],[G]=W.splice(U,1);W.splice(H,0,G),S(W)}}if(E&&((q=E.data.current)==null?void 0:q.type)===ls&&n.some(U=>U.id===y.id)){const U=n.findIndex(W=>W.id===y.id),H=n.findIndex(W=>W.id===E.id);if(U!==-1&&H!==-1&&U!==H){const W=[...n],[G]=W.splice(U,1);W.splice(H,0,G),g(W)}}if(E&&(($=E.data.current)==null?void 0:$.type)===is&&r.some(U=>U.id===y.id)){const U=r.findIndex(W=>W.id===y.id),H=r.findIndex(W=>W.id===E.id);if(U!==-1&&H!==-1&&U!==H){const W=[...r],[G]=W.splice(U,1);W.splice(H,0,G),f(W)}}R(I),o(null),c(null),d(a),m(n),h(r),u(i)}function R(I){const{active:y,over:E}=I,F=y.data.current;if((F==null?void 0:F.type)===Ns&&E){const z=l.findIndex(P=>Ie(P.columnId)===y.id),_=l.findIndex(P=>Ie(P.columnId)===E.id);if(z!==-1&&_!==-1&&z!==_){const P=[...l],[Q]=P.splice(z,1);P.splice(_,0,Q),x(P)}}}function A(){o(null),c(null),d(a),m(n),h(r)}return{handleDragOver:O,handleDragEnd:T,handleDragStart:D,handleDragCancel:A,sensors:C}}function ue(t){return`${t}-${s.v4()}`}function Le(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ie(t){return`${Ns}-${t}`}function De(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Pa({schemaName:t,tableName:a,columns:n,status:r}){const l=s.useEditorStore(y=>y.sqlGen),i=s.useEditorStore(y=>y.isDevMode),c=s.useEditorStore(y=>y.selectedConnectionId),o=s.useEditorStore(y=>{var E,F;return(F=(E=y.card)==null?void 0:E.queryConfig)==null?void 0:F.metricColumns});s.useEditorStore(y=>{var E,F;return(F=(E=y.card)==null?void 0:E.queryConfig)==null?void 0:F.groupByColumns});const d=s.useEditorStore(y=>y.selectedDatabaseName),m=s.useEditorStore(y=>y.selectedSchemaName),h=s.useEditorStore(y=>y.selectedTableName),u=s.useEditorStore(y=>y.selectedDatamodelId),p=s.useDashboardStore(y=>y.dashboard.aiScopeTables),{addToAIScope:g,removeFromAIScope:f}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:S,setCardSql:j,setRunSql:v,setSqlGen:C,setIsShowingVisual:O}=s.useEditorActions(),{connectionType:D,modelItems:N,selectedDatamodelName:b}=s.useEditorAside();function k(y){var E;if(i){const F=s.createSqlGenConfig(y,l);C(F);const z=(E=N==null?void 0:N.find(P=>P.id===u))==null?void 0:E.name,_=s.getSql(F,s.fmt(t),s.fmt(a),z||"",D,d||"");_&&(j(_),v(!0))}if(!i){if(s.isTextDataType(y.data_type))if(o&&o.length>0){const F={...y,role:"groupby",id:ue(y.column_name),name:y.column_name,type:y.data_type};S(F)}else{const F={...y,role:"metric",id:ue(y.column_name),name:y.column_name,label:Le(y.column_name,"COUNT"),type:y.data_type,aggregate:"COUNT"};x(F)}if(s.isDateDataType(y.data_type)){const F={...y,role:"groupby",id:ue(y.column_name),name:y.column_name,type:y.data_type,label:De(y.column_name,"month"),granularity:"month"};S(F)}if(s.isNumberDataType(y.data_type)){const F={...y,role:"metric",id:ue(y.column_name),name:y.column_name,label:Le(y.column_name,"SUM"),type:y.data_type,aggregate:"SUM"};x(F)}}}function w(y){y===!0&&(h||b)&&c?(g({connectionId:c,connectionType:D==="S3"||D==="API"?"DuckDb":D||"",databaseName:d||"",schemaName:m||"",tableName:h||"",datamodelName:s.resolveDatamodelName(b),datamodelId:u||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(f({connectionId:c||"",connectionType:D||"",tableName:h||"",datamodelName:s.resolveDatamodelName(b),datamodelId:u||"",databaseName:d||"",schemaName:m||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function L(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:b,connectionType:D,databaseName:d||""});O(!1);const E=D==="MSSQL"?`SELECT top 10 * FROM ${y}`:`SELECT * FROM ${y} LIMIT 10`;j(E),v(!0)}function T(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:b,connectionType:D,databaseName:d||""});j(`SELECT COUNT(*) as count FROM ${y}`),v(!0)}function R(){return(p==null?void 0:p.find(y=>y.connectionId===c&&(y.tableName===h||y.datamodelName===b)))!==void 0}function A(y){return i?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>k(y),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(bs,{column:y}),e.jsx("span",{children:y.column_name})]}),e.jsx("div",{onClick:E=>E.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(y.data_type)&&e.jsx(Ra,{column:y})})]}):e.jsx(Fa,{onClick:k,column:y})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${R()?"Remove from":"Add to"} Assistant Scope`,pressed:R(),onPressedChange:w,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":R(),"text-muted-foreground":!R()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:L,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx($n,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:T,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(rt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((y,E)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},E))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[i&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:I()}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(y=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:A(y)},y.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Et({ColumnsComponent:t,type:a}){var je;const n=s.useEditorStore(te=>te.card),r=s.useEditorStore(te=>te.selectedConnectionId),l=s.useDashboardStore(te=>te.showFilters),i=s.useEditorStore(te=>te.selectedDatamodelId),c=s.useEditorStore(te=>te.selectedDatabaseName),o=s.useEditorStore(te=>te.selectedSchemaName),d=s.useEditorStore(te=>te.selectedTableName),m=s.useEditorStore(te=>te.isDevMode),{setSelectedTableName:h,setIsDevMode:u,setCardSql:p}=s.useEditorActions(),{connectionItems:g,modelItems:f,schemaItems:x,databaseItems:S,tableItems:j,columns:v,isConnectionsLoading:C,isModelsLoading:O,isConnectionsError:D,isModelsError:N,isDatabasesLoadingOrFetching:b,isDatabaseError:k,isSchemaLoadingOrFetching:w,isSchemaError:L,isColumnsError:T,isColumnsLoadingOrFetching:R,isTableLoadingOrFetching:A,isTableError:I,connectionType:y,isNonDbConnection:E,refetchDatabases:F,refetchModels:z,refetchSchemas:_,refetchTables:P,refetchColumns:Q,refetchConnections:Y,handleConnectionChange:V,handleDatabaseChange:q,handleSchemaChange:$,handleDatamodelChange:U,handleTableChange:H,tableName:W,schemaName:G}=s.useEditorAside(),{data:Z,refetch:se}=s.useDashboardCardQuery(n);function ne(){return t?t(G,W,v):e.jsx(Pa,{schemaName:G,tableName:W,columns:v,status:R?"Loading...":T?"Error":"Success"})}function ee(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function ae(te){te===!0?Z&&(p(Z.userSql),setTimeout(()=>{se()},100)):p(""),u(te)}function J(){if(!r||y==="S3"||y==="API")return null;if(!i||i==="none")return e.jsx(ke,{refetch:F,showNone:!0,onChange:q,isError:k,isLoading:b,items:S,value:c||"",title:"Database",type:"combobox"})}function B(){if(r&&!E&&(!c||c==="none")&&(!i||i==="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 K(){if(!r||y==="S3"||y==="API")return null;if(!c||c==="none")return e.jsx(ke,{refetch:z,showNone:!0,onChange:U,isError:N,isLoading:O,items:f,value:i||"",title:"Model",type:"combobox"})}function re(){return!r||y==="S3"||y==="API"||!c||c==="none"?null:e.jsx(ke,{refetch:_,onChange:$,isError:L,isLoading:w,items:x,value:o||"",title:"Schema",type:"combobox"})}function he(){function te(){let le=!1;return y==="API"?(le=!1,le):((y==="S3"||r&&c&&c!=="none"&&o)&&(le=!0),le)}return te()?e.jsx(ke,{refetch:P,onChange:H,isError:I,items:j,isLoading:A,value:d||"",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]":!l}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(ke,{refetch:Y,items:g,title:"Connection",value:r||"",onChange:V,isLoading:C,isError:D,type:"combobox",connectionTooltip:((je=g==null?void 0:g.find(te=>te.id===r))==null?void 0:je.type)||""}),J(),B(),K(),re(),he()]}),ne(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:m,onCheckedChange:ae,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:ee,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Jn,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function It({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[l,i]=M.useState(!1),c=M.useRef(null),o=M.useRef(!1);function d(){t&&!o.current&&navigator.clipboard.writeText(t)}function m(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),d())}function h(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const g=p.toString();navigator.clipboard.writeText(g),i(!0),o.current=!0,setTimeout(()=>{i(!1),o.current=!1},1e3)}else o.current=!1}function u(){i(!1),o.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,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 ${n}`,onClick:d,onKeyDown:m,onMouseUp:h,onMouseDown:u,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 At({sql:t,error:a,onDebugWithAssistant:n}){const r=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:l,setCardSql:i,setRunSql:c}=s.useEditorActions();function o(){l(!r),i(t),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(It,{error:a}),t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!r&&t&&e.jsxs(s.Button,{onClick:o,variant:"secondary",size:"sm",children:[e.jsx(An,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(s.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(zn,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Mt({sql:t,error:a,onDebugWithAssistant:n}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(st,{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-[600px]",children:e.jsx(At,{sql:t,error:a,onDebugWithAssistant:n})})]})}var Lt={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Gs=M.createContext&&M.createContext(Lt),_a=["attr","size","title"];function Va(t,a){if(t==null)return{};var n=Ua(t,a),r,l;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(l=0;l<i.length;l++)r=i[l],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}function Ua(t,a){if(t==null)return{};var n={};for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){if(a.indexOf(r)>=0)continue;n[r]=t[r]}return n}function Ue(){return Ue=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Ue.apply(this,arguments)}function Hs(t,a){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);a&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(t,l).enumerable})),n.push.apply(n,r)}return n}function qe(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?Hs(Object(n),!0).forEach(function(r){qa(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Hs(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function qa(t,a,n){return a=$a(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function $a(t){var a=Ga(t,"string");return typeof a=="symbol"?a:a+""}function Ga(t,a){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function Ot(t){return t&&t.map((a,n)=>M.createElement(a.tag,qe({key:n},a.attr),Ot(a.child)))}function Se(t){return a=>M.createElement(Ha,Ue({attr:qe({},t.attr)},a),Ot(t.child))}function Ha(t){var a=n=>{var{attr:r,size:l,title:i}=t,c=Va(t,_a),o=l||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),M.createElement("svg",Ue({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:qe(qe({color:t.color||n.color},n.style),t.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),i&&M.createElement("title",null,i),t.children)};return Gs!==void 0?M.createElement(Gs.Consumer,null,n=>a(n)):a(Lt)}function Ja(t){return Se({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 Rt(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(x=>x.theme),r=s.useEditorStore(x=>x.frame),l=s.useEditorStore(x=>x.card),i=s.useEditorStore(x=>x.activeTabCardId),c=s.Le(),{refetch:o}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:m}=s.useEditorActions(),h=M.useRef(),u=M.useRef({}),p=r.cards.find(x=>x.id===i),g=M.useCallback(()=>{let x="";return t==="python"&&(x=(p==null?void 0:p.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(p==null?void 0:p.sql)||""),x},[t,p]);M.useEffect(()=>{if(i&&l.id&&l.id!==i){if(h.current&&c){const x=h.current.getModel();x&&(u.current[l.id]=x);let S=u.current[i];if(!S){const j=g();S=c.editor.createModel(j,t),u.current[i]=S}h.current.setModel(S)}d(i,l),m(!0)}},[i,l,d,c,m,t,g]),M.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",S=n==="system"?x:n;c.editor.defineTheme("default",{base:S==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":S==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),M.useEffect(()=>{const x=h.current;x&&c&&l&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return o(),!1})},[c,o,l]);function f(x,S){if(h.current=x,!u.current[l.id]){const j=x.getModel(),v=g();u.current[l.id]=j||(S==null?void 0:S.editor.createModel(v,t))||x.getModel()}x.setModel(u.current[l.id])}return{handleEditorDidMount:f}}function Wa(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Rt("sql");function i(c){n(c),s.isObjectEmpty(a)||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:i,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Ya(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=Rt("python");function r(l){a(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:n})}function Ka({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 Qa(){const t=s.useQueryClient(),[a,n]=M.useState(!1),[r,l]=M.useState(!1);s.useEditorStore(P=>P.frame);const i=s.useEditorStore(P=>P.card);s.useEditorStore(P=>P.isShowingVisual),s.useEditorStore(P=>P.selectedConnectionId),s.useEditorStore(P=>P.tempQueryData),s.useEditorStore(P=>P.selectedDatabaseName),s.useEditorStore(P=>P.selectedDatamodelId),s.useEditorStore(P=>P.selectedSchemaName);const c=s.useEditorStore(P=>P.showAIDialog);s.useEditorStore(P=>P.selectedTableName);const o=s.useEditorStore(P=>{var Q;return(Q=P==null?void 0:P.card)==null?void 0:Q.sql}),d=s.useEditorStore(P=>{var Q;return(Q=P==null?void 0:P.card)==null?void 0:Q.python}),{sheetFilterValues:m}=s.useSheetFilterValues(),{setCardCustomCfg:h,setQueryResultColumns:u,setCardSql:p,setTempQueryData:g,setPythonStdOut:f,setCardPreferences:x,setCardType:S,setCardPython:j,runAssistant:v,setShowAIDialog:C}=s.useEditorActions();s.useEditorStore(P=>P.onSave),s.useEditorStore(P=>P.onClose),s.useEditorStore(P=>P.actions.setSqlGen);const O=s.useEditorStore(P=>P.runSql),D=s.useEditorStore(P=>P.actions.setRunSql),N=s.useEditorStore(P=>P.actions.setIsSqlRunning),{data:b,isLoading:k,isFetching:w,isSuccess:L,isError:T,error:R,queryKey:A,refetch:I,errorMessage:y}=s.useDashboardCardQuery(i);M.useEffect(()=>{if(b&&(b.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),f((b==null?void 0:b.output)||""),b.records.length>0)){const{dimensionKeys:P}=s.getKeys(b.records);u(P)}},[b,u,f]),M.useEffect(()=>{(k||w)&&N(!0),(T||L)&&N(!1),T&&(u([]),f(""))},[k,w,b,f,T,L,N,u,R]),M.useEffect(()=>{O&&(t.getQueryData(A)||I(),D(!1))},[O,I,D,A,t]);async function E(){const P=`Can you help me debug this query in the current table scope?
402
402
 
403
403
  Error:
404
404
 
@@ -406,15 +406,15 @@
406
406
 
407
407
  Query:
408
408
 
409
- ${i}
409
+ ${o}
410
410
 
411
411
  ${d?`Python:
412
412
  ${d}`:""}
413
- `;v(P)}function F(){return e.jsxs(e.Fragment,{children:[r&&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(Ka,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>l(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function z(){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(Wa,{})}),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(Ya,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function _(){return e.jsxs("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:k||w,onClick:()=>{I()},className:"h-8 shrink-0",size:"sm",children:[k||w?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(Mt,{sql:b==null?void 0:b.sql,error:y,onDebugWithAssistant:E}),e.jsx(s.EditorClearButton,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:P=>n(P),className:"",size:"sm",children:e.jsx(Ja,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{N(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.EditorCancelButton,{}),e.jsx(s.EditorAcceptButton,{})]})]})}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:[z(),F()]}),_()]})}function Xa({data:t}){var c;const[a,n]=M.useState([]),l=Object.keys(t[0]).map(i=>({accessorKey:i,header:({column:d})=>{const m=d.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>d.toggleSorting(d.getIsSorted()==="asc"),children:[i,m==="asc"?e.jsx(s.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):m==="desc"?e.jsx(s.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),o=s.useReactTable({data:t,columns:l,getCoreRowModel:s.getCoreRowModel(),getPaginationRowModel:s.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:s.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(s.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(s.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:o.getHeaderGroups().map(i=>e.jsx(s.TableRow,{className:"",children:i.headers.map(d=>e.jsx(s.TableHead,{className:"h-11 font-semibold text-foreground",children:d.isPlaceholder?null:s.flexRender(d.column.columnDef.header,d.getContext())},d.id))},i.id))}),e.jsx(s.TableBody,{children:(c=o.getRowModel().rows)!=null&&c.length?o.getRowModel().rows.map(i=>e.jsx(s.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":i.getIsSelected()&&"selected",children:i.getVisibleCells().map(d=>e.jsx(s.TableCell,{className:"py-2",children:s.flexRender(d.column.columnDef.cell,d.getContext())},d.id))},i.id)):e.jsx(s.TableRow,{children:e.jsx(s.TableCell,{colSpan:l.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Za({card:t}){var v,N,O,C,D,b,k,w,L,T,R;const[a,n]=M.useState(!1),[r,l]=M.useState([]),{authToken:o}=s.useSemaphorContext(),c=s.getTokenParams(o==null?void 0:o.accessToken),i=s.useDashboardStore(A=>A.themeStyle),d={colors:((N=(v=i==null?void 0:i.chart)==null?void 0:v.dataset)==null?void 0:N.backgroundColor)||[]};(O=t.customCardPreferences)!=null&&O.inputData;const{getCard:m}=s.useCustomVisual(((C=t.customCardPreferences)==null?void 0:C.url)||""),h=((D=t.customCardPreferences)==null?void 0:D.visualType)||"single",u=s.useEditorStore(A=>A.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:j}=s.useDashboardCardQuery(t),f=M.useCallback((A,I)=>{l(y=>({...y,[A]:I}))},[]);if(!((b=t.customCardPreferences)!=null&&b.componentName))return null;const x=m((k=t.customCardPreferences)==null?void 0:k.componentName);function S(A){n(A)}const g=Object.keys(((w=t.customCardPreferences)==null?void 0:w.dataInputCardIds)||{}).map(A=>{var E,F,z;const I=(F=(E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)==null?void 0:F[A].cardId,y=(z=u==null?void 0:u.cards)==null?void 0:z.find(_=>_.id===I);return y||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(M.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[x&&h==="single"&&e.jsx(x,{editing:!0,params:c,theme:d,settings:(L=t.customCardPreferences)==null?void 0:L.settings,onDataChange:f,data:(j==null?void 0:j.records)||[]}),x&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((T=t.customCardPreferences)==null?void 0:T.dataInputCardIds)||{}).map(A=>{var E,F,z;const I=(F=(E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)==null?void 0:F[A].cardId,y=(z=u==null?void 0:u.cards)==null?void 0:z.find(_=>_.id===I);if(y)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:S,onDataChange:f,dataInputIndex:A,card:y},y.id+A)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:d,onDataChange:f,settings:g.map(A=>{var I;return(I=A==null?void 0:A.customCardPreferences)==null?void 0:I.settings}),data:g.map(A=>A!=null&&A.id?r==null?void 0:r[A.id]:[])})})]})]},(R=t.customCardPreferences)==null?void 0:R.componentName)})}function Bt({className:t,...a}){var v;const n=s.useEditorStore(N=>N.card),r=s.isExplorerCard(n),l=((v=n.customCardPreferences)==null?void 0:v.showCardHeader)??!0,o=s.useEditorStore(N=>N.frame),c=s.useDashboardStore(N=>N.dashboard.filters);s.useEditorStore(N=>N.actions.setRunSql);const{updateFilter:i}=s.useDashboardActions(),d=c==null?void 0:c.find(N=>N.id===o.filterId),{data:m,isLoading:h,isFetching:u,errorMessage:p}=s.useDashboardCardQuery(n),{setCard:j}=s.useEditorActions(),{data:f}=s.useTopoJson(n),x=M.useMemo(()=>!n.id||!(m!=null&&m.records)?null:s.createChartConfig({card:n,data:m==null?void 0:m.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:f}),[n.id,m==null?void 0:m.records,n.type,n.queryConfig,n.customCfg,n.preferences,f]);function S(N){return e.jsx(Za,{card:N})}function g(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!u)return p?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(!n.id)return null;if(n.type==="custom")return S(n);if(!["table","custom"].includes(n.type)&&x)return e.jsx(e.Fragment,{children:h||u?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:x})});if(n.type==="table"&&(m!=null&&m.records)&&(m==null?void 0:m.records.length)>0)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:n,data:m==null?void 0:m.records})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(s.Editable,{enabled:!0,text:n.title,onSave:N=>j({...n,title:N}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(s.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(s.Editable,{enabled:!0,text:n.description||"",onSave:N=>j({...n,description:N}),children:e.jsx(s.CardDescription,{children:n.description||"Add description"})},n.description)]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:d.title||d.column,onSave:N=>i({...d,title:N}),children:e.jsx(s.Label,{children:d.title})}),e.jsx(s.FilterComponent,{filter:d})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:g()})]})}const ts=({language:t,value:a,onChange:n,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:a,onChange:n}),er=()=>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."})]})]}),sr=({customCode:t,cardCustomCfgString:a,mergedConfig:n,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(ts,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ts,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ts,{language:"javascript",value:t,onChange:l})})]}),tr=({error:t,hasCardCustomConfig:a,onReset:n,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:!a,onClick:n,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 nr(){const[t,a]=M.useState(!1),[n,r]=M.useState(""),[l,o]=M.useState(""),[c,i]=M.useState(""),[d,m]=M.useState(""),h=s.useEditorStore(C=>C.card),u=s.useEditorStore(C=>C.card.customCfg),p=u?JSON.stringify(u,null,2):"",{data:j}=s.useDashboardCardQuery(h),{data:f}=s.useTopoJson(h),{setCardCustomCfg:x,setCustomVisualCode:S}=s.useEditorActions(),g=C=>{var D,b;return JSON.stringify({...C,data:{...C.data,datasets:(b=(D=C.data)==null?void 0:D.datasets)==null?void 0:b.map(k=>({...k,data:[]}))}},null,2)},v=()=>{var D,b;if(!((D=j==null?void 0:j.records)!=null&&D.length))return;const C=s.createChartConfig({card:h,data:j.records,cardType:h.type,queryConfig:h.queryConfig,preferences:h.preferences,topoJson:f});if(C){r(g(C)),i(((b=h.preferences)==null?void 0:b.customVisualCode)||"");const k=s.merge(C,u);o(g(k))}},N=()=>{try{if(c&&S(c),l){const C=JSON.parse(l),D=s.getObjectDiff(JSON.parse(n),C);x(D),m("")}}catch{m("Invalid JSON configuration")}},O=Object.keys(u||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:v,className:O?"":"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(er,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(Bt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(sr,{customCode:c,cardCustomCfgString:p,mergedConfig:l,onConfigChange:C=>o(C??""),onCodeChange:C=>i(C??"")})]}),e.jsx(tr,{error:d,hasCardCustomConfig:!!u,onReset:()=>{o(n),x(null)},onApply:N,onClose:()=>a(!1)})]})]})}function Ye(t){const[a,n]=M.useState(null);return a}function Cs(){const{authToken:t}=s.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:l}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:l}}function ar({onChartTypeChange:t}){const[a,n]=M.useState([]),{setCardCustomCfg:r,setCardPreferences:l,setCardType:o,setCustomCardPreferences:c}=s.useEditorActions(),{data:i}=Cs();function d(m,h){r(null),l({}),o(m),h&&c({type:"component",visualType:"single",url:h.url,componentName:h.name,icon:h.icon}),t==null||t()}return M.useEffect(()=>{(async()=>{var h;if(i){const p=(await Promise.all((h=i==null?void 0:i.plugins)==null?void 0:h.map(async j=>(await s.loadManifest(j.value)).visuals.map(S=>({name:S.name,icon:S.icon,url:j.value}))))).flat();n(p)}})()},[i]),a.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:a.map((m,h)=>e.jsx(rr,{text:m.name,onClick:()=>d("custom",m),icon:m.icon},m.url+m.name+h))})]})}const rr=({text:t,icon:a,onClick:n})=>{const r=Ye(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:n,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function Ss(t){return Se({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(t)}function lr(t){return Se({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(t)}function ws(t){return Se({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(t)}function Ts(t){return Se({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(t)}function ks(t){return Se({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(t)}function Ds(t){return Se({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(t)}function Ft({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(h=>h.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(h,u){o(null),r({}),n(h),["custom","text","map"].includes(h)&&(l(!0),i(void 0)),t==null||t()}const m=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:m,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(Je,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx($e,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(Ge,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(ms,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(ks,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(xs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(ws,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(He,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(ps,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(Ts,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(js,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(Ss,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(ys,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(hs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(Ds,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(Zs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(gs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Ae,{className:s.cn("size-5",a)})})]})}function or({chartType:t,className:a,customIcon:n,componentName:r}){const l=Ye();switch(t){case"bar":return e.jsx($e,{className:a});case"line":return e.jsx(Ge,{className:a});case"pie":return e.jsx(He,{className:a});case"radar":return e.jsx(js,{className:a});case"scatter":return e.jsx(xs,{className:a});case"bubble":return e.jsx(ws,{className:a});case"doughnut":return e.jsx(ps,{className:a});case"stackedBar":return e.jsx(ms,{className:a});case"stackedLine":return e.jsx(ks,{className:a});case"polarArea":return e.jsx(Ss,{className:a});case"funnel":return e.jsx(Ts,{className:a});case"tornado":case"pyramid":return e.jsx(ys,{className:a});case"range":return e.jsx(hs,{className:a});case"kpi":return e.jsx(Ds,{className:a});case"text":return e.jsx(it,{className:a});case"map":return e.jsx(gs,{className:a});case"custom":return n&&l?e.jsx(l,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ae,{className:a});default:return e.jsx(Je,{className:a})}}function zt({variant:t="ghost"}){var o,c;const[a,n]=M.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(or,{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:"w-72 p-1",children:[e.jsx(Ft,{onChartTypeChange:()=>n(!1)}),e.jsx(ar,{onChartTypeChange:()=>n(!1)})]})]})}const Oe="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function Js(t,a){var r,l,o;const n=s.getNumberAxis(t,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((o=(l=(r=t==null?void 0:t.chartOptions)==null?void 0:r.scales)==null?void 0:l[n])==null?void 0:o.type)||"linear"}function ir(){var E,F,z,_,P,Q;const[t,a]=M.useState(!1),n=s.useEditorStore(Y=>{var V;return(V=Y.card)==null?void 0:V.preferences}),r=s.useEditorStore(Y=>{var V;return(V=Y.card)==null?void 0:V.type}),l=s.getNumberAxis(n,{}),[o,c]=M.useState(Js(n,r)),[i,d]=M.useState(((z=(F=(E=n==null?void 0:n.chartOptions)==null?void 0:E.scales)==null?void 0:F[l])==null?void 0:z.min)||""),[m,h]=M.useState(((Q=(P=(_=n==null?void 0:n.chartOptions)==null?void 0:_.scales)==null?void 0:P[l])==null?void 0:Q.max)||""),[u,p]=M.useState(i||m?"custom":"auto"),[j,f]=M.useState(""),[x,S]=M.useState(0),[g,v]=M.useState(""),[N,O]=M.useState(""),[C,D]=M.useState(""),b=s.useEditorStore(Y=>Y.actions.setCardPreferences),{updateCardInFrame:k}=s.useEditorActions(),w=s.useEditorStore(Y=>Y.card),L=["pie","doughnut","polarArea","funnel"].includes(r);M.useEffect(()=>{var Y,V,q,$,U,H,W,G,Z,se,ne,ee,ae,J;c(Js(n,r)),d(((q=(V=(Y=n==null?void 0:n.chartOptions)==null?void 0:Y.scales)==null?void 0:V[l])==null?void 0:q.min)===0?0:""),h(((H=(U=($=n==null?void 0:n.chartOptions)==null?void 0:$.scales)==null?void 0:U[l])==null?void 0:H.max)||""),f(((se=(Z=(G=(W=n==null?void 0:n.chartOptions)==null?void 0:W.scales)==null?void 0:G[l])==null?void 0:Z.ticks)==null?void 0:se.stepSize)||""),S(((ne=n==null?void 0:n.numberAxisFormat)==null?void 0:ne.decimalPlaces)||0),v(((ee=n==null?void 0:n.numberAxisFormat)==null?void 0:ee.suffix)||""),O(((ae=n==null?void 0:n.numberAxisFormat)==null?void 0:ae.currency)||""),D(((J=n==null?void 0:n.numberAxisFormat)==null?void 0:J.locale)||"")},[t,n,l,r]);function T(Y,V){return V===""||/^[0-9\b]+$/.test(V)?Number(V):Number(Y)}function R(){const Y=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(V=>V.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(s.Select,{value:N||"none",onValueChange:V=>O(V==="none"?"":V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 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"}),Y.map(V=>e.jsx(s.SelectItem,{value:V,children:V},V))]})})]}),e.jsxs(s.Select,{value:C,onValueChange:V=>D(V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 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:"Locale"}),s.LOCALE_CURRENCY_PAIRS.map(V=>e.jsx(s.SelectItem,{value:V.locale,children:V.locale},V.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(s.Input,{value:x,onChange:V=>S(Number(V.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Oe}`})]})]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(s.Select,{disabled:L,value:o,onValueChange:Y=>c(Y),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{id:"type",children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Option"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(s.SelectItem,{value:"category",children:"Category"})]})})]})]}),o=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(s.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(s.RadioGroup,{disabled:L,id:"scale-option",value:u,onValueChange:Y=>p(Y),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),u==="custom"&&o=="linear"&&I()]})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"range",children:"Range"}),e.jsx(s.Input,{id:"min",value:i,onChange:Y=>d(V=>T(V,Y.target.value)),className:`col-span-1 h-8 w-full ${Oe}`}),e.jsx(s.Input,{value:m,onChange:Y=>h(V=>T(V,Y.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Oe}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(s.Input,{value:j,onChange:Y=>f(V=>T(V,Y.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Oe}`})]})]})}function y(){var $;let Y={};u==="custom"&&(Y={min:i,max:m,ticks:{stepSize:j}});const V={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...($=n==null?void 0:n.chartOptions)==null?void 0:$.scales,[l]:{type:o,...o==="linear"?Y:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:g,currency:N,locale:C}};console.log(V),b(V);const q={...w,preferences:V};k(q)}return e.jsxs(s.Popover,{onOpenChange:Y=>a(Y),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Format Number",children:e.jsx(En,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"max-w-65 z-[51]",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[R(),A(),e.jsx(s.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(s.Button,{onClick:y,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function cr(){const t=s.useEditorStore(i=>{var d,m,h,u;return(u=(h=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:h.legend)==null?void 0:u.position}),a=s.useEditorStore(i=>{var d,m,h,u;return(u=(h=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:h.legend)==null?void 0:u.align}),n=s.useEditorStore(i=>{var d,m,h,u;return(u=(h=(m=(d=i.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:h.legend)==null?void 0:u.display}),{setLegendOptions:r}=s.useEditorActions(),l=i=>{r({display:i,position:t,align:a})},o=i=>{r({display:n,position:i,align:a})},c=i=>{r({display:n,position:t,align:i})};return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Legend Settings",children:e.jsx(_n,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"z-[51] w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(s.SmallSwitch,{checked:n,onCheckedChange:l,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Top",onClick:()=>o("top"),children:e.jsx(s.ArrowUp,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Left",onClick:()=>o("left"),children:e.jsx(xn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Bottom",onClick:()=>o("bottom"),children:e.jsx(s.ArrowDown,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Right",onClick:()=>o("right"),children:e.jsx(pn,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Start",onClick:()=>c("start"),children:e.jsx(cn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(on,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(dn,{className:"size-4"})})]})]})]})]})]})})]})}function dr(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),a=s.useEditorStore(o=>o.card.type),{setChartOrientation:n}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(_s,{className:"size-4"}):e.jsx(Ps,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(_s,{className:"size-4"}):e.jsx(Ps,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?l():r()})}function Pt(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>c.isShowingVisual),n=s.useEditorStore(c=>{var i,d;return(d=(i=c.card)==null?void 0:i.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(n),{setChartGrid:l}=s.useEditorActions();function o(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;l(c[d])}return a?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(dr,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsxs(e.Fragment,{children:[e.jsx(ir,{}),e.jsx(cr,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:o,children:[(r==="xy"||!r)&&e.jsx(Fn,{className:"size-4"}),r==="x"&&e.jsx(Tn,{className:"size-4"}),r==="y"&&e.jsx(Xn,{className:"size-4"}),r==="none"&&e.jsx(na,{className:"size-4"})]})]}):null}function ur(){const t=s.useEditorStore(f=>f.frame),a=s.useEditorStore(f=>f.card),{setFrame:n,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(f,x)=>{f.dataTransfer.setData("tabIndex",x.toString())},i=f=>{f.preventDefault()},d=(f,x)=>{const S=f.dataTransfer.getData("tabIndex");if(S===x.toString())return;const g=Array.from(t.cards),[v]=g.splice(parseInt(S),1);g.splice(x,0,v),n({...t,cards:g})};function m(f){const x=t.cards.filter(v=>v.id!==f),S=x[0],g={...t,cards:x,activeCardId:S.id};n(g),r(S.id),l(S)}function h(f,x){const S={...t,cards:[...t.cards,x],activeCardId:f.id};n(S),r(x.id)}function u(){const f={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};h(a,f)}function p(f){const x={dataSource:f.dataSource,connectionId:f.connectionId,lastSelectedDatabase:f.lastSelectedDatabase,lastSelectedSchema:f.lastSelectedSchema,lastSelectedTable:f.lastSelectedTable,lastSelectedDatamodelId:f.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};h(f,x)}function j(f,x){return f.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||f.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const S=x.displayTab===void 0?!1:!x.displayTab;l({...x,displayTab:S}),o({...x,displayTab:S})},children:x.displayTab===!0||x.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(In,{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((f,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:S=>c(S,x),onDragOver:i,onDrop:S=>d(S,x),className:"",value:f.id,children:[j(t,f),e.jsx(s.Editable,{enabled:t.activeCardId===f.id,text:f.tabTitle||f.title,onSave:S=>{l({...a,tabTitle:S}),o({...a,tabTitle:S})},children:f.tabTitle||f.title},f.id),t.activeCardId===f.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>m(f.id)})]},f.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>p(a),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:u,children:e.jsx(Dn,{className:"h-4 w-4"})})]})})}function _t(){const t=s.useEditorStore(x=>x.frame),a=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:m,isLoading:h,isFetching:u}=s.useDashboardCardQuery(a);function p(x){const S=t.cards.find(g=>g.id===x);if(S!=null&&S.sql){r||i(!0),o(x);return}if(S!=null&&S.queryConfig){r&&i(!1),j(x),o(x);return}r||j(x),o(x)}function j(x){const S={...t,cards:t.cards.map(v=>v.id===a.id?a:v),activeCardId:x};l(S);const g=S.cards.find(v=>v.id===x);g.sql&&d(!0),c(g)}function f(){return a.type==="kpi"?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.KPICard,{card:a,data:m==null?void 0:m.records,isPending:h})})}):a.type==="text"?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:n,card:a,data:m==null?void 0:m.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(Bt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:p,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(x=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:x.id,children:f()},x.id)),e.jsx(ur,{})]})}function Re({children:t}){s.useEditorStore(v=>v.frame);const a=s.useEditorStore(v=>v.card),n=s.useEditorStore(v=>v.isDevMode),r=s.useEditorStore(v=>v.isShowingVisual),l=s.useDashboardStore(v=>v.isVisualEditing),o=s.useEditorStore(v=>v.pythonStdOut);s.useEditorStore(v=>v.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:m,setIsDevMode:h}=s.useEditorActions(),{data:u,isLoading:p,isFetching:j,errorMessage:f}=s.useDashboardCardQuery(a);function x(){const v=JSON.stringify(u==null?void 0:u.records,null,2),N=new Blob([v],{type:"application/json"}),O=URL.createObjectURL(N),C=document.createElement("a");C.href=O,C.download=`${a.title}.json`,C.click()}function S(){const N=[Object.keys(u==null?void 0:u.records.reduce((b,k)=>({...b,...k}),{})).join(","),...((u==null?void 0:u.records)||[]).map(b=>Object.values(b).join(","))].join(`
414
- `),O=new Blob([N],{type:"text/csv"}),C=URL.createObjectURL(O),D=document.createElement("a");D.href=C,D.download=`${a.title}.csv`,D.click()}function g(){const v=`Can you get the documentation for ${a.type} chart?`;m(v)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(p||j)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),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(zt,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:g,children:e.jsx(yn,{className:"size-4"})}),!["table","custom"].includes(a.type)&&l&&e.jsx(nr,{})]}),!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:S,children:e.jsx(lr,{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:x,children:e.jsx(Mn,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(u==null?void 0:u.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&&e.jsx(hr,{})]}),r?e.jsx(_t,{}):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(mr,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(u==null?void 0:u.records)&&(u==null?void 0:u.records.length)>0&&e.jsx(Xa,{data:(u==null?void 0:u.records)||[]}),f&&e.jsx(It,{error:f})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function mr(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function hr(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.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:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function xr(){var x,S;const t=s.useEditorStore(g=>g.card.customCardPreferences),{data:a}=Cs(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(g=>g.card),l=s.useEditorStore(g=>g.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)||""),m=(x=d==null?void 0:d.visuals)==null?void 0:x.find(g=>g.name===(t==null?void 0:t.componentName));function h(g,v){if(!t)return;const O={...(t==null?void 0:t.dataInputCardIds)||{},[g]:{cardId:v,hookRef:null}};c({...t,dataInputCardIds:O})}function u(g){var N,O;const v=(N=l==null?void 0:l.cards)==null?void 0:N.filter(C=>{var D;return((D=C==null?void 0:C.customCardPreferences)==null?void 0:D.visualType)!=="multiple"}).map(C=>({value:C.id,label:C.tabTitle||C.title}));return e.jsx("div",{className:"space-y-2",children:(O=g==null?void 0:g.dataInputs)==null?void 0:O.map((C,D)=>{var b,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(ce,{className:"col-span-6 h-8 w-full justify-between",label:"",options:v||[],value:((k=(b=t==null?void 0:t.dataInputCardIds)==null?void 0:b[D])==null?void 0:k.cardId)||"",onValueChange:w=>h(D,w)})]},D+Math.random())})})}function p(g,v,N=[],O=""){var C,D;return t?g==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((C=t==null?void 0:t.settings)==null?void 0:C[v])||O,onChange:b=>{c({...t,settings:{...t==null?void 0:t.settings,[v]:b.target.value}})}},v):g==="select"?e.jsx(ce,{className:"h-8 w-full",label:"",options:N,value:((D=t==null?void 0:t.settings)==null?void 0:D[v])||O,onValueChange:b=>{c({...t,settings:{...t==null?void 0:t.settings,[v]:b}})}}):null:null}function j(g){const v=Object.entries((g==null?void 0:g.settings)||{});return e.jsx("div",{className:"space-y-3",children:v.map(([N,O])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:O.title}),p(O.ui,N,O.options,O.defaultValue)]},N))})}function f(g){t&&c({...t,visualType:g,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(ce,{icon:e.jsx(jn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:g=>c({...t||{url:"",componentName:""},url:g})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:f,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(ce,{icon:e.jsx(kn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(g=>g.type===o).map(g=>({value:g.name,label:g.name})))||[],value:t.componentName,onValueChange:g=>{console.log("changing value",g),c({...t,componentName:g})}})})]})})]}),((S=r==null?void 0:r.customCardPreferences)==null?void 0:S.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[m&&m.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:u(m)})]}),m&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:j(m)})})]})]})]})}function we(){const[t,a]=M.useState([]),n=s.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(m=>m.actions),o=s.useEditorStore(m=>m.queryResultColumns);s.useEditorStore(m=>{var h;return(h=m.card.preferences)==null?void 0:h.filterOnClickColumnIndex}),M.useEffect(()=>{o&&a(new Array(o.length).fill(!1))},[o]);function c(m,h){var u,p;h?n!=null&&n.onClickFilter&&((u=n==null?void 0:n.onClickFilter)==null?void 0:u.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:m,expression:""}]}):l({...n,onClickFilter:[{columnIndex:m,expression:""}]}):(l({...n,onClickFilter:(p=n==null?void 0:n.onClickFilter)==null?void 0:p.filter(j=>j.columnIndex!==m)}),a(j=>{const f=[...j];return f[m]=!1,f}))}function i(m,h){var p;const u=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.map(j=>j.columnIndex===m?{...j,expression:h.target.value}:j);l({...n,onClickFilter:u})}function d(m){var h,u,p,j;if(t!=null&&t[m]||(u=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(f=>f.columnIndex===m))!=null&&u.expression)return e.jsx(s.Input,{value:(j=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(f=>f.columnIndex===m))==null?void 0:j.expression,onChange:f=>i(m,f),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.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(s.Label,{children:"On Click"}),o==null?void 0:o.map((m,h)=>{var u,p;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:!!((u=n==null?void 0:n.onClickFilter)!=null&&u.find(j=>j.columnIndex===h)),onCheckedChange:j=>c(h,j)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(j=>j.columnIndex===h))&&e.jsx(s.Pencil,{onClick:()=>{a(j=>{const f=[...j];return f[h]=!j[h],f})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(h)]})},m)})]})}function pr({idx:t}){var i;const a=s.useEditorStore(d=>{var m;return(m=d.card)==null?void 0:m.preferences}),n=s.useEditorStore(d=>{var m;return(m=d.card.preferences)==null?void 0:m.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=a==null?void 0:a.chartOptions)==null?void 0:i.indexAxis,o=n==null?void 0:n.find(d=>d.idx===t);function c(d,m){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const h={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...a,datasetOptions:[...n||[],{idx:m,datalabels:h}]});else{const u={...o};u.datalabels=h;const p=n==null?void 0:n.map(j=>j.idx===m?u:j);r({...a,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(lt,{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(Vn,{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(qn,{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(Un,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function fr(){const t=s.useEditorStore(o=>o.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Es({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Vt(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var m,h,u;return(u=(h=(m=d==null?void 0:d.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:u.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=fr();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:Ut(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,m)=>e.jsx(qt,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:m},d))})]})]})}function Ut(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function qt({col:t,idx:a,className:n,iconClassName:r,children:l}){const o=s.useEditorStore(h=>{var u;return(u=h.card)==null?void 0:u.preferences}),c=s.useEditorStore(h=>{var u,p;return(p=(u=h.card)==null?void 0:u.preferences)==null?void 0:p.datasetOptions}),i=c==null?void 0:c.find(h=>h.idx===a),{setCardPreferences:d}=s.useEditorStore(h=>h.actions);function m(h){if(!i)d({...o,datasetOptions:[...c||[],{idx:a,type:h==="area"?"line":h,fill:h==="area"?"origin":""}]});else{const u={...i};u.type=h==="area"?"line":h,u.fill=h==="area"?"origin":"";const p=c==null?void 0:c.map(j=>j.idx===a?u:j);d({...o,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(Es,{className:"max-w-[100px]",title:t,children:Ut(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($e,{onClick:()=>m("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Ge,{onClick:()=>m("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(et,{onClick:()=>m("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(pr,{idx:a})]})]})}function $t(){const t=s.useEditorStore(j=>j.selectedConnectionId),a=s.useEditorStore(j=>j.selectedDatamodelId),n=s.useEditorStore(j=>j.selectedDatabaseName),r=s.useEditorStore(j=>j.selectedSchemaName),l=s.useEditorStore(j=>j.selectedTableName),o=s.useDashboardStore(j=>j.dashboard.filters)||[],c=s.useDashboardStore(j=>j.actions.addFilter),i=s.useDashboardStore(j=>j.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:m,tableName:h,connectionType:u}=s.useEditorAside();function p(j,f="dashboard"){var b;const x=s.fmt(j.column_name),S=s.fmt(n||""),g=s.fmt(r||""),v=s.fmt(h);let N=s.getQualifiedTableName({schemaName:g,tableName:v,connectionType:u,databaseName:S}),O=`${N}.${x}`;const C=(b=m==null?void 0:m.find(k=>k.id===a))==null?void 0:b.name;a&&a!=="none"&&(O=`${s.DATAMODEL_NAMESPCACE}.${C}.${x}`,N=`${s.DATAMODEL_NAMESPCACE}.${C}`);const D=o==null?void 0:o.find(k=>k.column===O&&k.table===v&&(k.database===S||k.database===n));if(D)d(D.id),i(D.id);else{const k=s.v4();return h==="api"&&t?(c({location:f,id:k,column:O,title:j.column_name,dataType:j.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(j.data_type,N,x)}),k):(c({id:k,location:f,column:O,title:j.column_name,dataType:j.data_type,table:l||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(j.data_type,N,x)}),k)}}return{assignFilter:p}}function Ee(){const t=s.useDashboardStore(i=>i.dashboard.filters),a=s.useEditorStore(i=>i.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=$t();function o(i){const d=l(i,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(gr,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function gr({columns:t,onSelect:a}){var c;const[n,r]=ye.useState(!1),[l,o]=ye.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,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 m=d===l?"":d;o(m),r(!1),m&&a(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 jr({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:a=>a.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:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}function Ke(){const t=s.useEditorStore(i=>i.card.type),a=s.useEditorStore(i=>i.isDevMode),n=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var h;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},m={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(h=n==null?void 0:n.chartOptions)==null?void 0:h.plugins,...d}}};r(m)}function o(){var i,d,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((m=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:m.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,m;return e.jsx("div",{children:e.jsxs(s.Select,{value:((m=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:m.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:a?o():c()})}function yr({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="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"}),n==="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:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"px-2",children:e.jsx(Ke,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}const vr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},br={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Nr(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Cr(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ke,{}),e.jsx(we,{}),e.jsx(Ee,{})]})]})}function Cr(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(vr,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(br,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 Sr(){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(s.FormatNumberSetting,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function ns({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,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:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const wr=[{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"}],Tr=["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"],kr=Tr.map(t=>({label:t,value:t}));function Dr(){var d,m,h,u,p,j,f,x,S,g,v,N,O,C,D,b,k,w;const t=s.useEditorStore(L=>L.card),a=(m=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:m.topoJsonUrl,[n,r]=M.useState(((u=(h=t==null?void 0:t.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:u.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(L=>({label:L,value:L}))||[],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(ns,{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(ns,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(ce,{className:"h-9",options:i,onValueChange:L=>{console.log("value",L),l({...t.preferences,mapVisualOptions:{topoJsonUrl:L}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:L=>{r(L.target.value)},onBlur:()=>{var L;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(L=t.preferences)==null?void 0:L.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(ce,{className:"h-9",options:c,value:((j=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:j.objectKey)||"",label:"Map Object",onValueChange:L=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,objectKey:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(ce,{className:"h-9",options:wr,value:((x=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:L=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projection:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(ce,{className:"h-9",options:kr,value:((g=(S=t.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:g.colorScale)||"",label:"Select Color Scale",onValueChange:L=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,colorScale:L}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(ns,{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:((N=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:N.projectionScale)||1,onChange:L=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionScale:Number(L.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((D=(C=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:C.projectionOffset)==null?void 0:D[0])||0,onChange:L=>{var T,R,A,I;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[Number(L.target.value),((I=(A=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(k=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:w[1])||0,onChange:L=>{var T,R,A,I;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[((I=(A=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[0])||0,Number(L.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(we,{})]})}function Er(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...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:n,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 Be({cardType:t,docContent:a,suffix:n="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)} ${n}`}),e.jsx(s.AccordionContent,{children:a||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."]})]})})]}),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:[t!=="text"&&e.jsx(Ke,{}),t==="text"&&e.jsx(Er,{})]})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}function Ir(){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:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(ce,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(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:[n(),e.jsx(Vt,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}function Ar({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),n=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{n({...a,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:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})}),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"})]})]})}const Mr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT 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."]})]}),Lr=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."]})]}),Or=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Rr(){const t=s.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Ir,{});case"tornado":case"pyramid":return e.jsx(Be,{docContent:Mr,cardType:n});case"kpi":return e.jsx(Sr,{});case"line":case"bar":return e.jsx(jr,{cardType:n});case"range":return e.jsx(Be,{docContent:Lr,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Be,{cardType:n});case"bubble":case"scatter":return e.jsx(yr,{cardType:n});case"table":return e.jsx(Ar,{cardType:n});case"text":return e.jsx(Be,{docContent:Or,cardType:n,suffix:"Visual"});case"map":return e.jsx(Dr,{});case"custom":return e.jsx(xr,{});default:return e.jsx(Nr,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Gt({label:t,column:a,functions:n,onFunctionChange:r}){let l=n[0];"aggregate"in a?l=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(l=n.find(c=>c.value===a.granularity)||n[0]);function o(c){r(c)}return e.jsx(ce,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:n,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const Br=[{label:"Sum",value:"SUM",logo:e.jsx(rt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(fs,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(On,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(hn,{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 Fr({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Br;s.isTextDataType(t.type)&&(n=n.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(n=n.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:Le(t.name,l)};a(t.id,o)}return e.jsx(Gt,{column:t,functions:n,onFunctionChange:l=>r(l),label:"Aggregation"})}const zr=[{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 Pr({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const l={...t,granularity:r,label:De(t.name,r)};a(t.id,l)}return e.jsx(Gt,{column:t,functions:zr,onFunctionChange:r=>n(r),label:"Granularity"})}function _r({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),l=M.useMemo(()=>{let i=[];(n===be||n===Ne||n===Ce)&&(i=r);const d=i==null?void 0:i.filter(m=>m.column_name!==t.name);return d==null?void 0:d.map(m=>({id:m.column_name,value:m.column_name}))},[r,n,t.name]),o=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(m=>{var h;return m.column_name===((h=i[0])==null?void 0:h.id)});d&&a(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 Ht({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var m,h;return(h=(m=d.card)==null?void 0:m.config)==null?void 0:h.metricColumns}),r=(n==null?void 0:n.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(qt,{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(Ke,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&i()]})}function Vr({column:t,type:a,onRemoveColumn:n,droppableId:r}){const[l,o]=M.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:m,listeners:h,setNodeRef:u,transform:p,transition:j,isDragging:f}=s.useSortable({id:t.id,data:{type:a}}),x=p?{opacity:f?.5:void 0,transform:s.CSS.Translate.toString(p),transition:j}:void 0,S=s.isTextDataType(t.type);function g(D){const b=s.isNumberDataType(D.data_type),k=s.isTextDataType(D.data_type),w=s.isDateDataType(D.data_type),L=b?"number":k?"string":w?"date":"string";if(r===be){if(k){const T={id:t.id,name:D.column_name,type:L,role:"groupby"};c(t.id,T)}if(w){const T={id:t.id,name:D.column_name,type:L,role:"groupby",label:De(D.column_name,"month"),granularity:"month"};c(t.id,T)}}if(r===Ce){if(k){const T={id:t.id,name:D.column_name,type:L,role:"groupby"};d(t.id,T)}if(w){const T={id:t.id,name:D.column_name,type:L,label:De(D.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,T)}}if(r===Ne){const T={id:t.id,name:D.column_name,type:L,role:"metric",label:Le(D.column_name,"SUM"),aggregate:b?"SUM":"COUNT"};i(t.id,T)}}function v(){if(r===Ne)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(Ht,{column:t})})}function N(){const D=s.isDateDataType(t.type);if(r===Ne)return e.jsx(Fr,{column:t});if((r===be||r===Ce)&&D)return e.jsx(Pr,{column:t})}function O(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===be||r===Ce)&&S}),children:e.jsx(_r,{col:t,onChange:g,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(sa,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(tt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...h,...m,ref:u,style:x,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(),N(),O()]}),l&&v()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>n(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function as({id:t,label:a,columns:n,previewColumns:r,sortableType:l,onRemoveColumn:o}){var x,S;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),m=s.useDndStore(g=>g.activeId),h=s.useEditorStore(g=>{var v;return(v=g.card)==null?void 0:v.type}),u=i||((S=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:S.type)===l,p=m?r:n,j=l===_e?"Rows":l===Ve?"Pivot Columns":"Columns";function f(){if(!p||p.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:n==null?void 0:n.map(g=>g.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",u&&"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:a}),h!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:j})]}),f(),e.jsx("div",{className:"space-y-2",children:p==null?void 0:p.map(g=>g.id===Dt.id?e.jsx(Ur,{},g.id):e.jsx(Vr,{droppableId:t,type:l,column:g,onRemoveColumn:o},g.id))})]})})}function Ur(){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:a,type:n}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:d}=s.useSortable({id:a,data:{type:n}}),m=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:m,children:t})}function qr(){const t=s.useEditorStore(g=>{var v;return(v=g.card.queryConfig)==null?void 0:v.orderBy})||[],a=s.useEditorStore(g=>{var v;return(v=g.card.queryConfig)==null?void 0:v.groupByColumns})||[],n=s.useEditorStore(g=>{var v;return(v=g.card.queryConfig)==null?void 0:v.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(gn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(mn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(fn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=e.jsx(un,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=c==null?void 0:c.filter(g=>!t.some(v=>v.columnId===g.id)).map(g=>({id:g.id,value:g.label||g.name}));function p(g,v){const N=j(g);return N?N.role==="metric"?v==="asc"?m:h:v==="asc"?i:d:null}function j(g){return c.find(v=>v.id===g)}function f(g){const v=t.find(N=>N.columnId===g);if(v){const N={...v,direction:v.direction==="asc"?"desc":"asc"};o(N)}}const x=g=>{r({columnId:g.id,direction:"asc"})};function S(g){const v=t.find(N=>N.columnId===g);v&&l(v)}return e.jsx(s.SortableContext,{items:t.map(g=>Ie(g.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"}),u.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:u,selectedOptions:[],onChange:g=>x(g[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(g=>{var v,N;return e.jsx(Jt,{id:Ie(g.columnId),type:Ns,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(tt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Es,{className:"w-[175px] text-sm",children:((v=j(g.columnId))==null?void 0:v.label)||((N=j(g.columnId))==null?void 0:N.name)})]}),e.jsx("button",{title:g.direction==="asc"?"Ascending":"Descending",onClick:()=>f(g.columnId),className:"rounded-sm p-0",children:p(g.columnId,g.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>S(g.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"})})})]})},g.columnId)},Ie(g.columnId))})]})})}function $r(){const t=s.useEditorStore(S=>{var g;return((g=S.card.queryConfig)==null?void 0:g.groupByColumns)||[]}),a=s.useEditorStore(S=>S.card.type),n=s.useDndStore(S=>S.previewGroupByColumns),r=s.useEditorStore(S=>{var g;return((g=S.card.queryConfig)==null?void 0:g.metricColumns)||[]}),l=s.useDndStore(S=>S.previewMetricColumns),o=s.useEditorStore(S=>{var g;return((g=S.card.queryConfig)==null?void 0:g.pivotColumns)||[]}),c=s.useDndStore(S=>S.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:m}=s.useEditorActions();function h(S){i(S)}function u(S){d(S)}function p(S){m(S)}let j="Group By",f="Metrics",x="Stack By";return a==="table"&&(j="Rows",f="Metrics",x="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(as,{onRemoveColumn:h,sortableType:_e,id:be,label:j,columns:t,previewColumns:n}),e.jsx(as,{onRemoveColumn:p,sortableType:Ve,id:Ce,label:x,columns:o,previewColumns:c}),e.jsx(as,{onRemoveColumn:u,sortableType:ls,id:Ne,label:f,columns:r,previewColumns:l}),e.jsx(qr,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Is({children:t,column:a,id:n,sortableType:r,className:l}){const[o,c]=M.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),m=s.useEditorStore(u=>{var p,j;return(j=(p=u.card.queryConfig)==null?void 0:p.filters)==null?void 0:j.some(f=>f.filterColumnName===a.name)});function h(u){i(u)}return e.jsx(Jt,{id:n,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:a.name}),m&&e.jsx("button",{onClick:()=>d(a),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:()=>h(a),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 Gr({column:t,sortableType:a}){const n=s.useDashboardStore(N=>N.themeStyle),r=s.useEditorStore(N=>{var O,C;return(C=(O=N.card)==null?void 0:O.queryConfig)==null?void 0:C.filters}),l=s.useEditorStore(N=>{var O,C;return(C=(O=N.card.queryConfig)==null?void 0:O.filterColumns)==null?void 0:C.find(D=>D.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=M.useMemo(()=>{var N;return(N=r==null?void 0:r.find(O=>O.filterColumnName===t.name))==null?void 0:N.filterValue},[r,t.name]),m=M.useMemo(()=>Array.isArray(d)?d.map(N=>({id:N,value:N})):[],[d]),{updateEditorFilterValue:h}=s.useEditorActions(),u={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:p,isLoading:j,isFetching:f,isError:x}=s.useFilterQuery(u),S=M.useMemo(()=>{var O;return u.column?(O=p==null?void 0:p.records)==null?void 0:O.map(C=>{let D=u.column.split(".").slice(-1)[0].replace(/"/g,"");return C[D]===void 0&&(D=D.toLowerCase()),{id:C[D],value:C[D]}}):[]},[p,u.column]);function g(N){const O=N.map(C=>C.id);h(t.name,O)}function v(){return j||f?e.jsx(s.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):x?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(Hr,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:S,onChange:g,selectedOptions:m,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Is,{className:"w-60",id:t.id,sortableType:a,column:t,children:v()})}function Hr({columnName:t}){const{setEditorFilterMode:a}=s.useEditorActions(),n=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(){(n==null?void 0:n.mode)==="exclude"?a(t,"include"):a(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((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function Jr({column:t,sortableType:a}){const[n,r]=M.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:m,isError:h,data:u}=s.useFilterQuery(i),p=u==null?void 0:u.records,{dateRange:j,setDateRange:f,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:S}=s.useEditorActions();function g(O){var D,b;const C={gte:(D=O==null?void 0:O.from)==null?void 0:D.toISOString(),lte:(b=O==null?void 0:O.to)==null?void 0:b.toISOString()};S(t.name,C)}function v(){S(t.name,null,!0),f(x)}function N(){return d||m?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):h?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):p?e.jsx(s.DateRangePopover,{title:i.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:j,setDateRange:f,onApply:g,onClear:v}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Is,{className:"w-72",id:t.id,sortableType:a,column:t,children:N()})}function Wr({id:t,label:a,columns:n,previewColumns:r,sortableType:l}){var f,x;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(S=>S.activeId),m={},h=c||((x=(f=i==null?void 0:i.data)==null?void 0:f.current)==null?void 0:x.type)===l;function u(){if(!j||j.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function p(S){const g=s.isDateDataType(S.type);return S.id===Dt.id?e.jsx(Is,{id:S.id,sortableType:l,column:S,children:e.jsx(Yr,{})},S.id):g?e.jsx(Jr,{droppableId:t,sortableType:l,column:S},S.id):e.jsx(Gr,{droppableId:t,sortableType:l,column:S},S.id)}const j=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(S=>S.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",h&&"border border-muted-foreground/20"),ref:o,style:m,children:[e.jsx(s.Label,{className:"text-sm",children:a}),u(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:j==null?void 0:j.map(S=>p(S))})]})})}function Yr(){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 Kr(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),a=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:n}=s.useEditorActions();function r(l){n(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(Wr,{onRemoveColumn:r,sortableType:is,id:os,label:"Filters",columns:t,previewColumns:a})})}function Qr(){const t=s.useEditorStore(o=>o.card),a=s.useEditorStore(o=>o.showAIDialog),{setShowAIDialog:n}=s.useEditorActions(),{data:r,errorMessage:l}=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(s.EditorClearButton,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(Wn,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(Mt,{sql:r==null?void 0:r.sql,error:l})]}),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(s.EditorCancelButton,{}),e.jsx(s.EditorAcceptButton,{variant:"default"})]})]})}function Xr(){const t=M.useRef(null),a=M.useRef(null),n=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);M.useEffect(()=>{var i,d,m,h;r?((i=t.current)==null||i.resize(0),(d=a.current)==null||d.resize(0)):((m=t.current)==null||m.resize(25),(h=a.current)==null||h.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(Qa,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Rr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Re,{})})]}):e.jsx(Re,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx($r,{})})}),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(Qr,{}),e.jsx(Kr,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Re,{})})]})})]}):e.jsx(Re,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function Zr(t){const a=s.useAIInteractionStore(B=>B.currentAIContext),[n,r]=M.useState(""),[l,o]=M.useState(null),{authToken:c}=s.useSemaphorContext(),i=s.useEditorStore(B=>{var K;return(K=B==null?void 0:B.card)==null?void 0:K.sql}),d=s.useEditorStore(B=>B.isDevMode),m=s.useEditorStore(B=>{var K;return(K=B==null?void 0:B.card)==null?void 0:K.python}),{setCardPython:h,setCardSql:u,setRunSql:p,switchCardType:j,setQueryConfig:f}=s.useEditorActions(),x=s.useEditorStore(B=>B.currentAssitantScope)||[],S=s.useEditorStore(B=>B.userInputForAI),g=s.useEditorStore(B=>B.triggerAIRun),v=s.useEditorStore(B=>B.card),N=s.useEditorStore(B=>B.selectedDatabaseName),O=s.useEditorStore(B=>B.selectedTableName),C=s.useEditorStore(B=>B.selectedConnectionId),D=s.useEditorStore(B=>B.selectedSchemaName),b=s.useDashboardStore(B=>B.dashboard.aiScopeTables),{errorMessage:k,refetch:w,data:L}=s.useDashboardCardQuery(v),{setTriggerAIRun:T,setCurrentAssitantScope:R,setCardConfig:A}=s.useEditorActions(),{selectedDatamodelName:I,connectionType:y,selectedDatamodelId:E}=s.useEditorAside(),{messages:F,setMessages:z,reload:_,error:P,append:Q,input:Y,setInput:V,status:q,handleInputChange:$,handleSubmit:U,stop:H}=s.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${c==null?void 0:c.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:a},maxSteps:10,onError:B=>{console.log("on error",B)},onToolCall:W,onFinish(B,K){G(K.usage),r(""),K.finishReason==="stop"&&r("")}});M.useEffect(()=>{g&&S&&(Q({role:"user",content:S}),T(!1))},[g,S,Q,T]);async function W({toolCall:B}){var K,re,he,je;if(["createChartFromSql","createForecast"].includes(B.toolName)){const te=B.args.sql,le=B.args.python,oe=B.args.chartType;return j(oe),u(te),h(le),p(!0),{status:"success",message:"Let the user know that chart is created"}}else if(B.toolName==="getTableColumns")r("Getting table columns...");else{if(B.toolName==="getUserSql")return i?{status:"success",sql:i,python:m||""}:{status:"error",message:"No SQL found"};if(B.toolName==="getCurrentTableScope")return r("Getting table scope..."),ee(),{status:"success",tables:x};if(B.toolName==="generateQueryConfig"){r("Generating query config...");const te=B.args.chartType,le=B.args.queryConfig;B.args.cardConfig,j(te),A(le),u(void 0),h(void 0);const oe=await w();return(K=oe==null?void 0:oe.data)!=null&&K.error?{status:"error",queryConfig:le,message:(re=oe==null?void 0:oe.data)==null?void 0:re.error.message}:(he=oe==null?void 0:oe.data)!=null&&he.records?{status:"success",queryConfig:le,message:"The data has been visualized"}:{status:"success",queryConfig:le,message:"The data has been visualized",records:(je=oe==null?void 0:oe.data)==null?void 0:je.records}}else r("Analyzing...")}}function G(B){o(K=>K?{promptTokens:K.promptTokens+B.promptTokens,completionTokens:K.completionTokens+B.completionTokens,totalTokens:K.totalTokens+B.totalTokens}:B)}function Z(B){const K=s.removeFromScopeArray(x,B);se(K)}function se(B){const K=s.sanitizeAIScope(B);R(K),z(re=>[...re,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(K)}`}])}function ne(){const B={databaseName:N||"",schemaName:D||"",tableName:O||"",datamodelId:E||"",datamodelName:s.resolveDatamodelName(I),connectionId:C||"",connectionType:y||""},K=s.dedup([...x,B]);se(K)}function ee(){const B={databaseName:N||"",schemaName:D||"",tableName:O||"",datamodelName:s.resolveDatamodelName(I),connectionId:C||"",connectionType:y||"",datamodelId:E||""};if(!s.isInAiScopeArray([...b||[],...x],B)||x.length===0){const re=s.dedup([...b||[],...x,B]).filter(he=>he.connectionId===B.connectionId);se(re)}}const ae=!["ready","error"].includes(q),J=s.getErrorMessage(P);return{messages:F,setMessages:z,reload:_,append:Q,input:Y,setInput:V,isLoading:ae,handleSetAIScope:ee,handleAddCurrentTableToScope:ne,removeFromCurrentSelections:Z,currentAssitantScope:x,setCurrentAssitantScope:R,handleInputChange:$,handleSubmit:U,stop:H,chatStatus:q,toolStatus:n,llmUsage:l,onFinish:t,errorMessage:J}}const el=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Ws(){const t=M.useRef(null),a=M.useRef(null),[n,r]=M.useState(!1),[l,o]=M.useState(s.isDevEnv),[c,i]=M.useState(!1),[d,m]=M.useState(!1),h=s.useCurrentAIContext(),{setCurrentAIContext:u}=s.useAIActions(),p=s.useDashboardStore(H=>H.dashboard.aiContext),j=s.useEditorStore(H=>H.card.dataSource),f=s.useEditorStore(H=>H.actions.setCardSql),x=s.useEditorStore(H=>H.actions.setRunSql),S=s.useEditorStore(H=>H.showAIDialog),g=s.useDashboardStore(H=>H.handleOpenAssistantProfile),{setShowAIDialog:v,setCardPython:N}=s.useEditorActions(),{setDataSource:O}=s.useEditorActions(),{assistantProfile:C}=s.useAssistantProfile(),{messages:D,setMessages:b,reload:k,append:w,input:L,setInput:T,isLoading:R,handleInputChange:A,handleSubmit:I,stop:y,chatStatus:E,llmUsage:F,errorMessage:z}=Zr();s.useAssistantScroll({scrollContainerRef:t,inputRef:a,messages:D}),M.useEffect(()=>{var H;S&&((H=a.current)==null||H.focus(),u({selectedEntities:(j==null?void 0:j.selectedEntities)||[]}))},[S,j,u]);function _(H,W){W==="sql"?(f(H),x(!0)):W==="python"&&(N(H),x(!0))}function P(){var H;(H=p==null?void 0:p.selectedEntities)==null||H[0],m(!0)}function Q(){h.selectedEntities.length===0&&u({selectedEntities:(p==null?void 0:p.selectedEntities)||[]})}function Y(H){Q();const W={role:"user",content:H.title+" "+H.subtitle};w(W)}function V(H){Q(),w({role:"user",content:H})}function q(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:i,children:"System Message"})]})]})}function $(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const U=(L==null?void 0:L.length)===0&&(D==null?void 0:D.filter(H=>H.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[$(),g&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:g,children:(C==null?void 0:C.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[q(),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:P,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{b([]),k()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-8 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{v(!1)},children:e.jsx(s.EyeOff,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:t,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(s.PrintMessages,{messages:D,showTools:l,handleRun:_,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:D,chatStatus:E,errorMessage:z})]})}),e.jsxs("div",{className:"mb-3",children:[U&&!C&&e.jsx(s.Placeholders,{onClick:Y,placeholders:el}),e.jsx("div",{children:U&&C&&e.jsx(s.SeedQuestions,{seedQuestions:C.seedQuestions||[],handleSeedQuestionClick:V})})]}),e.jsx(s.ChatInputWithContext,{ref:a,setInput:T,stop:y,input:L,handleInputChange:A,handleSubmit:H=>{Q(),I(H)},isLoading:R,onFocus:()=>{}}),F&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",F.promptTokens," prompt tokens,"," ",F.completionTokens," completion tokens,"," ",F.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(j==null?void 0:j.selectedEntities)||[],open:d,onOpenChange:m,dataSource:j||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function Wt(t,a){return`${t}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Yt(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function sl(t,a){const n=s.getDataType(t.dataType);return n==="number"?"metrics":n==="date"||n==="string"?"groupBy":"metrics"}function cs(t,a){const n=Wt(a,t),r=s.getDataType(t.dataType),l=r==="date",o={id:n,name:t.name,dataType:t.dataType,label:s.toLabel(t.name),qualifiedEntityName:t.qualifiedEntityName,entityId:t.entityId,entityName:t.entityName,entityType:t.entityType};if(a==="metrics"){const c=r==="number"?"SUM":"COUNT",i=Yt(t.label,c);return{...o,role:"metric",label:i,aggregate:c}}return a==="groupBy"?{...o,role:"groupby",...l&&{granularity:"month",dateFormat:"YYYY-MM"}}:a==="pivotBy"?{...o,role:"pivotby"}:a==="sortBy"?{...o,role:"sortby",label:t.label,direction:"asc"}:null}function Kt(t,a,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:t===a||t===n.baseEntity.name||a===n.baseEntity.name?!0:n.joins.some(l=>{const o=s.getQualifiedEntityName(l.source),c=s.getQualifiedEntityName(l.target);return o===t&&c===a||o===a&&c===t})}function tl(t,a,n){if(a.length===0)return{isValid:!0};const r=a[0].qualifiedEntityName;if(!r)return{isValid:!0};if(r!==t.qualifiedEntityName&&t.qualifiedEntityName)if(n){if(!Kt(r,t.qualifiedEntityName,n))return{isValid:!1,showError:!0}}else return{isValid:!1,showError:!0};return{isValid:!0}}function ds(){s.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})}function us(t,a){return a.some(n=>n.name===t.name&&n.qualifiedEntityName===t.qualifiedEntityName)}const As=t=>{var T;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:m}=s.useEditorActions(),h=s.useEditorStore(R=>R.card.type),u=t==null?void 0:t.id,p=M.useCallback(R=>{if(!(t!=null&&t.config))return[];switch(R){case"groupBy":return(t.config.groupByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,dateFormat:A.dateFormat,customFormat:A.customFormat,granularity:A.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,direction:A.direction}));case"source":return[];default:return[]}},[t]),j=M.useCallback((R,A)=>{if(u)switch(R){case"groupBy":{a(u,{groupByColumns:A});break}case"metrics":{a(u,{metricColumns:A});break}case"pivotBy":{a(u,{pivotByColumns:A});break}case"sortBy":{a(u,{sortByColumns:A});break}}},[u,a]),f=M.useCallback((R,A,I)=>{if(!u)return;const E=p(R)[A];if(E)switch(R){case"groupBy":n(u,E.id,{label:I});break;case"metrics":r(u,E.id,{label:I});break;case"pivotBy":l(u,E.id,{label:I});break;case"sortBy":o(u,E.id,{label:I});break}},[u,p,n,r,l,o]),x=M.useCallback((R,A)=>{if(!u)return;const y=p("metrics")[R];y&&r(u,y.id,{aggregate:A,label:Yt(y.name,A)})},[u,p,r]),S=M.useCallback((R,A,I)=>{if(!u)return;const E=p("groupBy")[R];if(!E)return;const F={dateFormat:A};A==="custom"&&I?F.customFormat=I:F.customFormat=void 0,n(u,E.id,F)},[u,p,n]),g=M.useCallback((R,A)=>{if(!u)return;const y=p("groupBy")[R];y&&n(u,y.id,{granularity:A})},[u,p,n]),v=M.useCallback((R,A)=>{if(!u)return;const y=p("metrics")[R];y&&r(u,y.id,{aliasTemplate:A})},[u,p,r]),N=M.useCallback((R,A)=>{if(console.log("handleValueAliasesChange",R,A),!u)return;console.log("handleValueAliasesChange",R,A);const y=p("metrics")[R];y&&(console.log("handleValueAliasesChange",A),r(u,y.id,{valueAliases:A}))},[u,p,r]),O=M.useCallback(R=>{u&&a(u,{comparisonType:R})},[u,a]),C=M.useCallback(R=>{u&&a(u,{showTrendline:R})},[u,a]),D=M.useCallback(R=>{u&&a(u,{trendlineWindow:R})},[u,a]),b=M.useCallback(R=>{u&&a(u,{trendlineGranularity:R})},[u,a]),k=M.useCallback(R=>{u&&a(u,{targetValue:R})},[u,a]),w=M.useCallback(R=>{var _;if(!u)return;const A=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],I=(_=t==null?void 0:t.config)==null?void 0:_.joinPlan,y=tl(R,A,I);if(!y.isValid){y.showError&&ds();return}const E=sl(R),F=p(E);if(us(R,F))return;const z=cs(R,E);z&&j(E,[...F,z])},[u,(T=t==null?void 0:t.config)==null?void 0:T.joinPlan,p,j]),L=M.useCallback((R,A)=>{if(!u)return;const y=p(R)[A];if(y){if(R!=="sortBy"){const E=p("sortBy"),F=E.filter(z=>!(z.name===y.name&&z.qualifiedEntityName===y.qualifiedEntityName));F.length!==E.length&&a(u,{sortByColumns:F})}switch(R){case"groupBy":c(u,y.id);break;case"metrics":i(u,y.id);break;case"pivotBy":d(u,y.id);break;case"sortBy":m(u,y.id);break}}},[u,p,c,i,d,m,a]);return{getFieldsForContainer:p,setFieldsForContainer:j,updateLabel:f,handleAggregationChange:x,handleDateFormatChange:S,handleGranularityChange:g,handleAliasTemplateChange:v,handleValueAliasesChange:N,removeField:L,handleFieldClick:w,handleKpiComparisonTypeChange:O,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:b,handleKpiTargetValueChange:k,cardType:h}};function nl({field:t}){const{attributes:a,listeners:n,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,d]=M.useState(!1),m=s.useEditorStore(x=>x.card),{handleFieldClick:h}=As(m),u={transform:s.CSS.Transform.toString(l),transition:o},p=s.getDataType(t.dataType),f=(x=>{const S=(x||"").toLowerCase();switch(s.getDataType(S)){case"number":return fs;case"date":return s.Calendar;case"boolean":return ot;case"json":return wn;case"geo":return Hn;default:return it}})(t.dataType);return e.jsxs("div",{ref:r,style:u,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:border-blue-200 hover:bg-blue-50 dark:hover:border-blue-800 dark:hover:bg-blue-950"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 p-2",onClick:()=>h(t),children:[e.jsx("div",{className:"flex-shrink-0 hover:cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"invisible size-3.5 text-gray-400 group-hover/container:visible"})}),e.jsx(f,{className:s.cn("size-3.5 flex-shrink-0 text-gray-500",p==="string"?"text-blue-500":"",p==="number"?"text-green-500":"",p==="date"?"text-purple-500":"",p==="boolean"?"text-orange-500":"")}),e.jsx(s.TooltipProvider$1,{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/90 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:t.label||t.name}),t.description&&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:t.description})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"mr-2 text-muted-foreground",children:"Name:"}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.name})]}),e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"mr-2 text-muted-foreground",children:"Type:"}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.dataType})]}),t.qualifiedEntityName&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[t.entityType?t.entityType.charAt(0).toUpperCase()+t.entityType.slice(1):"Entity",":"]}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.qualifiedEntityName})]})]})]})})]})})]}),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(lt,{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(aa,{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 al(){const[t,a]=M.useState(""),[n,r]=M.useState("all"),l=s.useEditorStore(N=>N.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),m=o.filter(N=>N.name.toLowerCase().includes(t.toLowerCase())||N.dataType.toLowerCase().includes(t.toLowerCase())||N.qualifiedEntityName&&N.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),h=N=>{if(N.dataType==="number"||N.dataType==="integer"||N.dataType==="float"||N.dataType==="decimal"||N.dataType==="currency")return"metrics";const O=s.getDataType(N.dataType);return["date","string","boolean"].includes(O)?"dimensions":O==="number"?"metrics":"dimensions"},p=(n==="all"?m:m.filter(N=>h(N)===n)).reduce((N,O)=>{const C=O.qualifiedEntityName||"Other Fields";return N[C]||(N[C]={label:s.toLabel(O.entityName),fields:[]}),N[C].fields.push(O),N},{}),f=Object.keys(p),x=m.filter(N=>h(N)==="dimensions").length,S=m.filter(N=>h(N)==="metrics").length,g=m.filter(N=>h(N)==="calculated").length,v=m.length>0;return i?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):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.jsx("div",{className:"mb-4",children:e.jsx(s.Input$1,{type:"text",placeholder:"Search fields...",value:t,onChange:N=>a(N.target.value)})}),v&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:N=>r(N),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: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:x})]}),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:S})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Nn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:f,className:"space-y-2",children:Object.entries(p).map(([N,O])=>{const C=c.find(D=>D.entityName===N)||{entityName:N,label:O.label};return e.jsxs(s.AccordionItem,{value:N,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-3 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"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:O.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:O.fields.map(D=>e.jsx(nl,{field:D},D.id))})})]},N)})}),Object.keys(p).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(p).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 rl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(al,{})," "]})}function ll({initialJoinPlan:t,availableDataSources:a}){const[n,r]=M.useState(t),[l,o]=M.useState(new Set),c=()=>{const D=n.joins.length>0?Math.max(...n.joins.map(k=>k.sequence))+1:1,b={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:D,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,b]}),o(new Set([...l,b.id]))},i=D=>{r({...n,joins:n.joins.filter(b=>b.id!==D)}),o(new Set([...l].filter(b=>b!==D)))},d=(D,b)=>{var T,R;const k=n.joins.find(A=>A.id===D);if(!k)return;const w={...k,...b},L=n.joins.map(A=>A.id===D?w:A);if((T=w.source)!=null&&T.name&&((R=w.target)!=null&&R.name)&&w.joinKeyGroups[0].keys.length===0){const A=a.find(F=>{var z;return F.name===((z=w.source)==null?void 0:z.name)}),I=a.find(F=>{var z;return F.name===((z=w.target)==null?void 0:z.name)}),y={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="},E=[...w.joinKeyGroups];E[0]={...E[0],keys:[y]},w.joinKeyGroups=E,L[L.findIndex(F=>F.id===D)]=w}r({...n,joins:L})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:D=>{const b=n.joins.findIndex(k=>k.id===D);if(b>0){const k=[...n.joins],w={...k[b]},L={...k[b-1]};k[b]=L,k[b-1]=w,k.forEach((R,A)=>{R.sequence=A+1});const T={...n,joins:k};r(T)}},moveJoinDown:D=>{const b=n.joins.findIndex(k=>k.id===D);if(b<n.joins.length-1){const k=[...n.joins],w={...k[b]},L={...k[b+1]};k[b]=L,k[b+1]=w,k.forEach((R,A)=>{R.sequence=A+1});const T={...n,joins:k};r(T)}},toggleJoinExpansion:D=>{const b=new Set(l);b.has(D)?b.delete(D):b.add(D),o(b)},getAvailableSourceEntities:D=>{if(n.joins.length===0)return a;const b=n.joins.findIndex(w=>w.id===D);if(b===0)return a;const k=new Set;return n.baseEntity.name&&k.add(n.baseEntity.name),n.joins.slice(0,b).forEach(w=>{k.add(w.source.name),k.add(w.target.name)}),a.filter(w=>k.has(w.name))},getAvailableTargetEntities:D=>a.filter(b=>b.name!==D),addJoinKeyGroup:D=>{const b=n.joins.find(w=>w.id===D);if(!b)return;const k=[...b.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(D,{joinKeyGroups:k})},updateGroupOperator:(D,b,k)=>{const w=n.joins.find(T=>T.id===D);if(!w)return;const L=[...w.joinKeyGroups];L[b]={...L[b],operator:k},d(D,{joinKeyGroups:L})},removeJoinKeyGroup:(D,b)=>{const k=n.joins.find(L=>L.id===D);if(!k)return;const w=[...k.joinKeyGroups];w.splice(b,1),d(D,{joinKeyGroups:w})},addJoinKey:(D,b)=>{const k=n.joins.find(A=>A.id===D);if(!k)return;const w=a.find(A=>A.name===k.source.name),L=a.find(A=>A.name===k.target.name),T=[...k.joinKeyGroups],R={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(L==null?void 0:L.name)||"",entityName:(L==null?void 0:L.name)||"",entityType:(L==null?void 0:L.type)||"table"},operator:"="};T[b]={...T[b],keys:[...T[b].keys,R]},d(D,{joinKeyGroups:T})},updateJoinKey:(D,b,k,w,L)=>{const T=n.joins.find(E=>E.id===D);if(!T)return;const R=a.find(E=>E.name===T.source.name),A=a.find(E=>E.name===T.target.name),I=[...T.joinKeyGroups],y=I[b].keys[k];w==="sourceColumnName"&&R?I[b].keys[k]={...y,source:{...y.source,name:L}}:w==="targetColumnName"&&A?I[b].keys[k]={...y,target:{...y.target,name:L}}:w==="operator"&&(I[b].keys[k]={...y,operator:L}),d(D,{joinKeyGroups:I})},removeJoinKey:(D,b,k)=>{const w=n.joins.find(T=>T.id===D);if(!w)return;const L=[...w.joinKeyGroups];L[b].keys.splice(k,1),d(D,{joinKeyGroups:L})},generateSQLPreview:()=>{const D=[...n.joins].sort((w,L)=>w.sequence-L.sequence),b=n.baseEntity;if(!b.name)return"SELECT * FROM table -- Please select a base entity";let k=`SELECT *
415
- FROM ${b.name}`;return D.forEach(w=>{const L=a.find(A=>A.name===w.target.name);if(!L)return;const T=w.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const I=A.keys.filter(y=>{var E,F,z,_;return((E=y.source)==null?void 0:E.name)&&((F=y.target)==null?void 0:F.name)&&((z=y.source)==null?void 0:z.entityName)&&((_=y.target)==null?void 0:_.entityName)}).map(y=>`${y.source.entityName}.${y.source.name} ${y.operator} ${y.target.entityName}.${y.target.name}`);return I.length>1?`(${I.join(` ${A.operator} `)})`:I[0]}).filter(Boolean),R=T.length>1?T.join(" OR "):T[0]||"condition_here";k+=`
413
+ `;v(P)}function F(){return e.jsxs(e.Fragment,{children:[r&&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(Ka,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>l(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function z(){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(Wa,{})}),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(Ya,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function _(){return e.jsxs("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:k||w,onClick:()=>{I()},className:"h-8 shrink-0",size:"sm",children:[k||w?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(Mt,{sql:b==null?void 0:b.sql,error:y,onDebugWithAssistant:E}),e.jsx(s.EditorClearButton,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:P=>n(P),className:"",size:"sm",children:e.jsx(Ja,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{C(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.EditorCancelButton,{}),e.jsx(s.EditorAcceptButton,{})]})]})}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:[z(),F()]}),_()]})}function Xa({data:t}){var c;const[a,n]=M.useState([]),l=Object.keys(t[0]).map(o=>({accessorKey:o,header:({column:d})=>{const m=d.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>d.toggleSorting(d.getIsSorted()==="asc"),children:[o,m==="asc"?e.jsx(s.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):m==="desc"?e.jsx(s.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),i=s.useReactTable({data:t,columns:l,getCoreRowModel:s.getCoreRowModel(),getPaginationRowModel:s.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:s.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(s.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(s.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:i.getHeaderGroups().map(o=>e.jsx(s.TableRow,{className:"",children:o.headers.map(d=>e.jsx(s.TableHead,{className:"h-11 font-semibold text-foreground",children:d.isPlaceholder?null:s.flexRender(d.column.columnDef.header,d.getContext())},d.id))},o.id))}),e.jsx(s.TableBody,{children:(c=i.getRowModel().rows)!=null&&c.length?i.getRowModel().rows.map(o=>e.jsx(s.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":o.getIsSelected()&&"selected",children:o.getVisibleCells().map(d=>e.jsx(s.TableCell,{className:"py-2",children:s.flexRender(d.column.columnDef.cell,d.getContext())},d.id))},o.id)):e.jsx(s.TableRow,{children:e.jsx(s.TableCell,{colSpan:l.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Za({card:t}){var v,C,O,D,N,b,k,w,L,T,R;const[a,n]=M.useState(!1),[r,l]=M.useState([]),{authToken:i}=s.useSemaphorContext(),c=s.getTokenParams(i==null?void 0:i.accessToken),o=s.useDashboardStore(A=>A.themeStyle),d={colors:((C=(v=o==null?void 0:o.chart)==null?void 0:v.dataset)==null?void 0:C.backgroundColor)||[]};(O=t.customCardPreferences)!=null&&O.inputData;const{getCard:m}=s.useCustomVisual(((D=t.customCardPreferences)==null?void 0:D.url)||""),h=((N=t.customCardPreferences)==null?void 0:N.visualType)||"single",u=s.useEditorStore(A=>A.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:g}=s.useDashboardCardQuery(t),f=M.useCallback((A,I)=>{l(y=>({...y,[A]:I}))},[]);if(!((b=t.customCardPreferences)!=null&&b.componentName))return null;const x=m((k=t.customCardPreferences)==null?void 0:k.componentName);function S(A){n(A)}const j=Object.keys(((w=t.customCardPreferences)==null?void 0:w.dataInputCardIds)||{}).map(A=>{var E,F,z;const I=(F=(E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)==null?void 0:F[A].cardId,y=(z=u==null?void 0:u.cards)==null?void 0:z.find(_=>_.id===I);return y||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(M.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[x&&h==="single"&&e.jsx(x,{editing:!0,params:c,theme:d,settings:(L=t.customCardPreferences)==null?void 0:L.settings,onDataChange:f,data:(g==null?void 0:g.records)||[]}),x&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((T=t.customCardPreferences)==null?void 0:T.dataInputCardIds)||{}).map(A=>{var E,F,z;const I=(F=(E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)==null?void 0:F[A].cardId,y=(z=u==null?void 0:u.cards)==null?void 0:z.find(_=>_.id===I);if(y)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:S,onDataChange:f,dataInputIndex:A,card:y},y.id+A)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:d,onDataChange:f,settings:j.map(A=>{var I;return(I=A==null?void 0:A.customCardPreferences)==null?void 0:I.settings}),data:j.map(A=>A!=null&&A.id?r==null?void 0:r[A.id]:[])})})]})]},(R=t.customCardPreferences)==null?void 0:R.componentName)})}function Bt({className:t,...a}){var v;const n=s.useEditorStore(C=>C.card),r=s.isExplorerCard(n),l=((v=n.customCardPreferences)==null?void 0:v.showCardHeader)??!0,i=s.useEditorStore(C=>C.frame),c=s.useDashboardStore(C=>C.dashboard.filters);s.useEditorStore(C=>C.actions.setRunSql);const{updateFilter:o}=s.useDashboardActions(),d=c==null?void 0:c.find(C=>C.id===i.filterId),{data:m,isLoading:h,isFetching:u,errorMessage:p}=s.useDashboardCardQuery(n),{setCard:g}=s.useEditorActions(),{data:f}=s.useTopoJson(n),x=M.useMemo(()=>!n.id||!(m!=null&&m.records)?null:s.createChartConfig({card:n,data:m==null?void 0:m.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:f}),[n.id,m==null?void 0:m.records,n.type,n.queryConfig,n.customCfg,n.preferences,f]);function S(C){return e.jsx(Za,{card:C})}function j(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!u)return p?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(!n.id)return null;if(n.type==="custom")return S(n);if(!["table","custom"].includes(n.type)&&x)return e.jsx(e.Fragment,{children:h||u?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:x})});if(n.type==="table"&&(m!=null&&m.records)&&(m==null?void 0:m.records.length)>0)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:n,data:m==null?void 0:m.records})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(s.Editable,{enabled:!0,text:n.title,onSave:C=>g({...n,title:C}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(s.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(s.Editable,{enabled:!0,text:n.description||"",onSave:C=>g({...n,description:C}),children:e.jsx(s.CardDescription,{children:n.description||"Add description"})},n.description)]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Editable,{enabled:!0,className:"my-1",text:d.title||d.column,onSave:C=>o({...d,title:C}),children:e.jsx(s.Label,{children:d.title})}),e.jsx(s.FilterComponent,{filter:d})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:j()})]})}const ts=({language:t,value:a,onChange:n,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:a,onChange:n}),er=()=>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."})]})]}),sr=({customCode:t,cardCustomCfgString:a,mergedConfig:n,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(ts,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ts,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ts,{language:"javascript",value:t,onChange:l})})]}),tr=({error:t,hasCardCustomConfig:a,onReset:n,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:!a,onClick:n,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 nr(){const[t,a]=M.useState(!1),[n,r]=M.useState(""),[l,i]=M.useState(""),[c,o]=M.useState(""),[d,m]=M.useState(""),h=s.useEditorStore(D=>D.card),u=s.useEditorStore(D=>D.card.customCfg),p=u?JSON.stringify(u,null,2):"",{data:g}=s.useDashboardCardQuery(h),{data:f}=s.useTopoJson(h),{setCardCustomCfg:x,setCustomVisualCode:S}=s.useEditorActions(),j=D=>{var N,b;return JSON.stringify({...D,data:{...D.data,datasets:(b=(N=D.data)==null?void 0:N.datasets)==null?void 0:b.map(k=>({...k,data:[]}))}},null,2)},v=()=>{var N,b;if(!((N=g==null?void 0:g.records)!=null&&N.length))return;const D=s.createChartConfig({card:h,data:g.records,cardType:h.type,queryConfig:h.queryConfig,preferences:h.preferences,topoJson:f});if(D){r(j(D)),o(((b=h.preferences)==null?void 0:b.customVisualCode)||"");const k=s.merge(D,u);i(j(k))}},C=()=>{try{if(c&&S(c),l){const D=JSON.parse(l),N=s.getObjectDiff(JSON.parse(n),D);x(N),m("")}}catch{m("Invalid JSON configuration")}},O=Object.keys(u||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:v,className:O?"":"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(er,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(Bt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(sr,{customCode:c,cardCustomCfgString:p,mergedConfig:l,onConfigChange:D=>i(D??""),onCodeChange:D=>o(D??"")})]}),e.jsx(tr,{error:d,hasCardCustomConfig:!!u,onReset:()=>{i(n),x(null)},onApply:C,onClose:()=>a(!1)})]})]})}function Ye(t){const[a,n]=M.useState(null);return a}function Cs(){const{authToken:t}=s.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:l}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:l}}function ar({onChartTypeChange:t}){const[a,n]=M.useState([]),{setCardCustomCfg:r,setCardPreferences:l,setCardType:i,setCustomCardPreferences:c}=s.useEditorActions(),{data:o}=Cs();function d(m,h){r(null),l({}),i(m),h&&c({type:"component",visualType:"single",url:h.url,componentName:h.name,icon:h.icon}),t==null||t()}return M.useEffect(()=>{(async()=>{var h;if(o){const p=(await Promise.all((h=o==null?void 0:o.plugins)==null?void 0:h.map(async g=>(await s.loadManifest(g.value)).visuals.map(S=>({name:S.name,icon:S.icon,url:g.value}))))).flat();n(p)}})()},[o]),a.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:a.map((m,h)=>e.jsx(rr,{text:m.name,onClick:()=>d("custom",m),icon:m.icon},m.url+m.name+h))})]})}const rr=({text:t,icon:a,onClick:n})=>{const r=Ye(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:n,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function Ss(t){return Se({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(t)}function lr(t){return Se({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(t)}function ws(t){return Se({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(t)}function Ts(t){return Se({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(t)}function ks(t){return Se({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(t)}function Ds(t){return Se({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(t)}function Ft({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(h=>h.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:o}=s.useEditorActions();function d(h,u){i(null),r({}),n(h),["custom","text","map"].includes(h)&&(l(!0),o(void 0)),t==null||t()}const m=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:m,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(Je,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx($e,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(Ge,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(ms,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(ks,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(xs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(ws,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(He,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(ps,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(Ts,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(js,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(Ss,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(ys,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(hs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(Ds,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(Zs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(gs,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:m,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Ae,{className:s.cn("size-5",a)})})]})}function or({chartType:t,className:a,customIcon:n,componentName:r}){const l=Ye();switch(t){case"bar":return e.jsx($e,{className:a});case"line":return e.jsx(Ge,{className:a});case"pie":return e.jsx(He,{className:a});case"radar":return e.jsx(js,{className:a});case"scatter":return e.jsx(xs,{className:a});case"bubble":return e.jsx(ws,{className:a});case"doughnut":return e.jsx(ps,{className:a});case"stackedBar":return e.jsx(ms,{className:a});case"stackedLine":return e.jsx(ks,{className:a});case"polarArea":return e.jsx(Ss,{className:a});case"funnel":return e.jsx(Ts,{className:a});case"tornado":case"pyramid":return e.jsx(ys,{className:a});case"range":return e.jsx(hs,{className:a});case"kpi":return e.jsx(Ds,{className:a});case"text":return e.jsx(it,{className:a});case"map":return e.jsx(gs,{className:a});case"custom":return n&&l?e.jsx(l,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ae,{className:a});default:return e.jsx(Je,{className:a})}}function zt({variant:t="ghost"}){var i,c;const[a,n]=M.useState(!1),r=s.useEditorStore(o=>o.card),l=r.type;return s.useDashboardStore(o=>o.isVisualEditing),e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(or,{className:"size-4",chartType:l,customIcon:(i=r.customCardPreferences)==null?void 0:i.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:o=>o.preventDefault(),className:"w-72 p-1",children:[e.jsx(Ft,{onChartTypeChange:()=>n(!1)}),e.jsx(ar,{onChartTypeChange:()=>n(!1)})]})]})}const Oe="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function Js(t,a){var r,l,i;const n=s.getNumberAxis(t,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((i=(l=(r=t==null?void 0:t.chartOptions)==null?void 0:r.scales)==null?void 0:l[n])==null?void 0:i.type)||"linear"}function ir(){var E,F,z,_,P,Q;const[t,a]=M.useState(!1),n=s.useEditorStore(Y=>{var V;return(V=Y.card)==null?void 0:V.preferences}),r=s.useEditorStore(Y=>{var V;return(V=Y.card)==null?void 0:V.type}),l=s.getNumberAxis(n,{}),[i,c]=M.useState(Js(n,r)),[o,d]=M.useState(((z=(F=(E=n==null?void 0:n.chartOptions)==null?void 0:E.scales)==null?void 0:F[l])==null?void 0:z.min)||""),[m,h]=M.useState(((Q=(P=(_=n==null?void 0:n.chartOptions)==null?void 0:_.scales)==null?void 0:P[l])==null?void 0:Q.max)||""),[u,p]=M.useState(o||m?"custom":"auto"),[g,f]=M.useState(""),[x,S]=M.useState(0),[j,v]=M.useState(""),[C,O]=M.useState(""),[D,N]=M.useState(""),b=s.useEditorStore(Y=>Y.actions.setCardPreferences),{updateCardInFrame:k}=s.useEditorActions(),w=s.useEditorStore(Y=>Y.card),L=["pie","doughnut","polarArea","funnel"].includes(r);M.useEffect(()=>{var Y,V,q,$,U,H,W,G,Z,se,ne,ee,ae,J;c(Js(n,r)),d(((q=(V=(Y=n==null?void 0:n.chartOptions)==null?void 0:Y.scales)==null?void 0:V[l])==null?void 0:q.min)===0?0:""),h(((H=(U=($=n==null?void 0:n.chartOptions)==null?void 0:$.scales)==null?void 0:U[l])==null?void 0:H.max)||""),f(((se=(Z=(G=(W=n==null?void 0:n.chartOptions)==null?void 0:W.scales)==null?void 0:G[l])==null?void 0:Z.ticks)==null?void 0:se.stepSize)||""),S(((ne=n==null?void 0:n.numberAxisFormat)==null?void 0:ne.decimalPlaces)||0),v(((ee=n==null?void 0:n.numberAxisFormat)==null?void 0:ee.suffix)||""),O(((ae=n==null?void 0:n.numberAxisFormat)==null?void 0:ae.currency)||""),N(((J=n==null?void 0:n.numberAxisFormat)==null?void 0:J.locale)||"")},[t,n,l,r]);function T(Y,V){return V===""||/^[0-9\b]+$/.test(V)?Number(V):Number(Y)}function R(){const Y=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(V=>V.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(s.Select,{value:C||"none",onValueChange:V=>O(V==="none"?"":V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 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"}),Y.map(V=>e.jsx(s.SelectItem,{value:V,children:V},V))]})})]}),e.jsxs(s.Select,{value:D,onValueChange:V=>N(V),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 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:"Locale"}),s.LOCALE_CURRENCY_PAIRS.map(V=>e.jsx(s.SelectItem,{value:V.locale,children:V.locale},V.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(s.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(s.Input,{value:x,onChange:V=>S(Number(V.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Oe}`})]})]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(s.Select,{disabled:L,value:i,onValueChange:Y=>c(Y),children:[e.jsx(s.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{id:"type",children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Option"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(s.SelectItem,{value:"category",children:"Category"})]})})]})]}),i=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(s.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(s.RadioGroup,{disabled:L,id:"scale-option",value:u,onValueChange:Y=>p(Y),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),u==="custom"&&i=="linear"&&I()]})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"range",children:"Range"}),e.jsx(s.Input,{id:"min",value:o,onChange:Y=>d(V=>T(V,Y.target.value)),className:`col-span-1 h-8 w-full ${Oe}`}),e.jsx(s.Input,{value:m,onChange:Y=>h(V=>T(V,Y.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Oe}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(s.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(s.Input,{value:g,onChange:Y=>f(V=>T(V,Y.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Oe}`})]})]})}function y(){var $;let Y={};u==="custom"&&(Y={min:o,max:m,ticks:{stepSize:g}});const V={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...($=n==null?void 0:n.chartOptions)==null?void 0:$.scales,[l]:{type:i,...i==="linear"?Y:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:j,currency:C,locale:D}};console.log(V),b(V);const q={...w,preferences:V};k(q)}return e.jsxs(s.Popover,{onOpenChange:Y=>a(Y),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Format Number",children:e.jsx(En,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"max-w-65 z-[51]",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[R(),A(),e.jsx(s.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(s.Button,{onClick:y,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function cr(){const t=s.useEditorStore(o=>{var d,m,h,u;return(u=(h=(m=(d=o.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:h.legend)==null?void 0:u.position}),a=s.useEditorStore(o=>{var d,m,h,u;return(u=(h=(m=(d=o.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:h.legend)==null?void 0:u.align}),n=s.useEditorStore(o=>{var d,m,h,u;return(u=(h=(m=(d=o.card.preferences)==null?void 0:d.chartOptions)==null?void 0:m.plugins)==null?void 0:h.legend)==null?void 0:u.display}),{setLegendOptions:r}=s.useEditorActions(),l=o=>{r({display:o,position:t,align:a})},i=o=>{r({display:n,position:o,align:a})},c=o=>{r({display:n,position:t,align:o})};return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Legend Settings",children:e.jsx(_n,{className:"size-4"})})}),e.jsx(s.PopoverContentCustom,{align:"end",className:"z-[51] w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(s.SmallSwitch,{checked:n,onCheckedChange:l,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Top",onClick:()=>i("top"),children:e.jsx(s.ArrowUp,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Left",onClick:()=>i("left"),children:e.jsx(xn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Bottom",onClick:()=>i("bottom"),children:e.jsx(s.ArrowDown,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Right",onClick:()=>i("right"),children:e.jsx(pn,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(s.IconButton,{tooltip:"Start",onClick:()=>c("start"),children:e.jsx(cn,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(on,{className:"size-4"})}),e.jsx(s.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(dn,{className:"size-4"})})]})]})]})]})]})})]})}function dr(){const t=s.useEditorStore(i=>{var c,o;return(o=(c=i.card.preferences)==null?void 0:c.chartOptions)==null?void 0:o.indexAxis}),a=s.useEditorStore(i=>i.card.type),{setChartOrientation:n}=s.useEditorStore(i=>i.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(_s,{className:"size-4"}):e.jsx(Ps,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(_s,{className:"size-4"}):e.jsx(Ps,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?l():r()})}function Pt(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>c.isShowingVisual),n=s.useEditorStore(c=>{var o,d;return(d=(o=c.card)==null?void 0:o.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(n),{setChartGrid:l}=s.useEditorActions();function i(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;l(c[d])}return a?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(dr,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsxs(e.Fragment,{children:[e.jsx(ir,{}),e.jsx(cr,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:i,children:[(r==="xy"||!r)&&e.jsx(Fn,{className:"size-4"}),r==="x"&&e.jsx(Tn,{className:"size-4"}),r==="y"&&e.jsx(Xn,{className:"size-4"}),r==="none"&&e.jsx(na,{className:"size-4"})]})]}):null}function ur(){const t=s.useEditorStore(f=>f.frame),a=s.useEditorStore(f=>f.card),{setFrame:n,setActiveTabCardId:r,setCard:l,updateCardInFrame:i}=s.useEditorActions(),c=(f,x)=>{f.dataTransfer.setData("tabIndex",x.toString())},o=f=>{f.preventDefault()},d=(f,x)=>{const S=f.dataTransfer.getData("tabIndex");if(S===x.toString())return;const j=Array.from(t.cards),[v]=j.splice(parseInt(S),1);j.splice(x,0,v),n({...t,cards:j})};function m(f){const x=t.cards.filter(v=>v.id!==f),S=x[0],j={...t,cards:x,activeCardId:S.id};n(j),r(S.id),l(S)}function h(f,x){const S={...t,cards:[...t.cards,x],activeCardId:f.id};n(S),r(x.id)}function u(){const f={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};h(a,f)}function p(f){const x={dataSource:f.dataSource,connectionId:f.connectionId,lastSelectedDatabase:f.lastSelectedDatabase,lastSelectedSchema:f.lastSelectedSchema,lastSelectedTable:f.lastSelectedTable,lastSelectedDatamodelId:f.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};h(f,x)}function g(f,x){return f.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||f.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const S=x.displayTab===void 0?!1:!x.displayTab;l({...x,displayTab:S}),i({...x,displayTab:S})},children:x.displayTab===!0||x.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(In,{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((f,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:S=>c(S,x),onDragOver:o,onDrop:S=>d(S,x),className:"",value:f.id,children:[g(t,f),e.jsx(s.Editable,{enabled:t.activeCardId===f.id,text:f.tabTitle||f.title,onSave:S=>{l({...a,tabTitle:S}),i({...a,tabTitle:S})},children:f.tabTitle||f.title},f.id),t.activeCardId===f.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>m(f.id)})]},f.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>p(a),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:u,children:e.jsx(Dn,{className:"h-4 w-4"})})]})})}function _t(){const t=s.useEditorStore(x=>x.frame),a=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:l,setActiveTabCardId:i,setCard:c,setIsDevMode:o,setRunSql:d}=s.useEditorActions(),{data:m,isLoading:h,isFetching:u}=s.useDashboardCardQuery(a);function p(x){const S=t.cards.find(j=>j.id===x);if(S!=null&&S.sql){r||o(!0),i(x);return}if(S!=null&&S.queryConfig){r&&o(!1),g(x),i(x);return}r||g(x),i(x)}function g(x){const S={...t,cards:t.cards.map(v=>v.id===a.id?a:v),activeCardId:x};l(S);const j=S.cards.find(v=>v.id===x);j.sql&&d(!0),c(j)}function f(){return a.type==="kpi"?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.KPICard,{card:a,data:m==null?void 0:m.records,isPending:h})})}):a.type==="text"?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:n,card:a,data:m==null?void 0:m.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackEditorCard,children:e.jsx(Bt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:p,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(x=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:x.id,children:f()},x.id)),e.jsx(ur,{})]})}function Re({children:t}){s.useEditorStore(v=>v.frame);const a=s.useEditorStore(v=>v.card),n=s.useEditorStore(v=>v.isDevMode),r=s.useEditorStore(v=>v.isShowingVisual),l=s.useDashboardStore(v=>v.isVisualEditing),i=s.useEditorStore(v=>v.pythonStdOut);s.useEditorStore(v=>v.actions.setRunSql);const{setFrame:c,setCard:o,setActiveTabCardId:d,runAssistant:m,setIsDevMode:h}=s.useEditorActions(),{data:u,isLoading:p,isFetching:g,errorMessage:f}=s.useDashboardCardQuery(a);function x(){const v=JSON.stringify(u==null?void 0:u.records,null,2),C=new Blob([v],{type:"application/json"}),O=URL.createObjectURL(C),D=document.createElement("a");D.href=O,D.download=`${a.title}.json`,D.click()}function S(){const C=[Object.keys(u==null?void 0:u.records.reduce((b,k)=>({...b,...k}),{})).join(","),...((u==null?void 0:u.records)||[]).map(b=>Object.values(b).join(","))].join(`
414
+ `),O=new Blob([C],{type:"text/csv"}),D=URL.createObjectURL(O),N=document.createElement("a");N.href=D,N.download=`${a.title}.csv`,N.click()}function j(){const v=`Can you get the documentation for ${a.type} chart?`;m(v)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(p||g)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),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(zt,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:j,children:e.jsx(yn,{className:"size-4"})}),!["table","custom"].includes(a.type)&&l&&e.jsx(nr,{})]}),!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:S,children:e.jsx(lr,{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:x,children:e.jsx(Mn,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(u==null?void 0:u.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&&e.jsx(hr,{})]}),r?e.jsx(_t,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&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:i&&e.jsx(mr,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(u==null?void 0:u.records)&&(u==null?void 0:u.records.length)>0&&e.jsx(Xa,{data:(u==null?void 0:u.records)||[]}),f&&e.jsx(It,{error:f})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function mr(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function hr(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.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:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function xr(){var x,S;const t=s.useEditorStore(j=>j.card.customCardPreferences),{data:a}=Cs(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(j=>j.card),l=s.useEditorStore(j=>j.frame),i=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:o,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),m=(x=d==null?void 0:d.visuals)==null?void 0:x.find(j=>j.name===(t==null?void 0:t.componentName));function h(j,v){if(!t)return;const O={...(t==null?void 0:t.dataInputCardIds)||{},[j]:{cardId:v,hookRef:null}};c({...t,dataInputCardIds:O})}function u(j){var C,O;const v=(C=l==null?void 0:l.cards)==null?void 0:C.filter(D=>{var N;return((N=D==null?void 0:D.customCardPreferences)==null?void 0:N.visualType)!=="multiple"}).map(D=>({value:D.id,label:D.tabTitle||D.title}));return e.jsx("div",{className:"space-y-2",children:(O=j==null?void 0:j.dataInputs)==null?void 0:O.map((D,N)=>{var b,k;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:D}),e.jsx(ce,{className:"col-span-6 h-8 w-full justify-between",label:"",options:v||[],value:((k=(b=t==null?void 0:t.dataInputCardIds)==null?void 0:b[N])==null?void 0:k.cardId)||"",onValueChange:w=>h(N,w)})]},N+Math.random())})})}function p(j,v,C=[],O=""){var D,N;return t?j==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((D=t==null?void 0:t.settings)==null?void 0:D[v])||O,onChange:b=>{c({...t,settings:{...t==null?void 0:t.settings,[v]:b.target.value}})}},v):j==="select"?e.jsx(ce,{className:"h-8 w-full",label:"",options:C,value:((N=t==null?void 0:t.settings)==null?void 0:N[v])||O,onValueChange:b=>{c({...t,settings:{...t==null?void 0:t.settings,[v]:b}})}}):null:null}function g(j){const v=Object.entries((j==null?void 0:j.settings)||{});return e.jsx("div",{className:"space-y-3",children:v.map(([C,O])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:O.title}),p(O.ui,C,O.options,O.defaultValue)]},C))})}function f(j){t&&c({...t,visualType:j,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(ce,{icon:e.jsx(jn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:j=>c({...t||{url:"",componentName:""},url:j})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:i,onValueChange:f,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:o&&e.jsx(ce,{icon:e.jsx(kn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.filter(j=>j.type===i).map(j=>({value:j.name,label:j.name})))||[],value:t.componentName,onValueChange:j=>{console.log("changing value",j),c({...t,componentName:j})}})})]})})]}),((S=r==null?void 0:r.customCardPreferences)==null?void 0:S.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[m&&m.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:u(m)})]}),m&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(m)})})]})]})]})}function we(){const[t,a]=M.useState([]),n=s.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(m=>m.actions),i=s.useEditorStore(m=>m.queryResultColumns);s.useEditorStore(m=>{var h;return(h=m.card.preferences)==null?void 0:h.filterOnClickColumnIndex}),M.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function c(m,h){var u,p;h?n!=null&&n.onClickFilter&&((u=n==null?void 0:n.onClickFilter)==null?void 0:u.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:m,expression:""}]}):l({...n,onClickFilter:[{columnIndex:m,expression:""}]}):(l({...n,onClickFilter:(p=n==null?void 0:n.onClickFilter)==null?void 0:p.filter(g=>g.columnIndex!==m)}),a(g=>{const f=[...g];return f[m]=!1,f}))}function o(m,h){var p;const u=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.map(g=>g.columnIndex===m?{...g,expression:h.target.value}:g);l({...n,onClickFilter:u})}function d(m){var h,u,p,g;if(t!=null&&t[m]||(u=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(f=>f.columnIndex===m))!=null&&u.expression)return e.jsx(s.Input,{value:(g=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(f=>f.columnIndex===m))==null?void 0:g.expression,onChange:f=>o(m,f),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.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(s.Label,{children:"On Click"}),i==null?void 0:i.map((m,h)=>{var u,p;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:!!((u=n==null?void 0:n.onClickFilter)!=null&&u.find(g=>g.columnIndex===h)),onCheckedChange:g=>c(h,g)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===h))&&e.jsx(s.Pencil,{onClick:()=>{a(g=>{const f=[...g];return f[h]=!g[h],f})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(h)]})},m)})]})}function pr({idx:t}){var o;const a=s.useEditorStore(d=>{var m;return(m=d.card)==null?void 0:m.preferences}),n=s.useEditorStore(d=>{var m;return(m=d.card.preferences)==null?void 0:m.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(o=a==null?void 0:a.chartOptions)==null?void 0:o.indexAxis,i=n==null?void 0:n.find(d=>d.idx===t);function c(d,m){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const h={display:d!=="none",align:d,anchor:d,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:m,datalabels:h}]});else{const u={...i};u.datalabels=h;const p=n==null?void 0:n.map(g=>g.idx===m?u:g);r({...a,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(lt,{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(Vn,{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(qn,{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(Un,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function fr(){const t=s.useEditorStore(i=>i.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!s.METADATA_KEYS.includes(i));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const i=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(i);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Es({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Vt(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var m,h,u;return(u=(h=(m=d==null?void 0:d.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:u.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:i,transformedMetricKeys:c,keys:o}=fr();return o.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:i.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:Ut(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,m)=>e.jsx(qt,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:m},d))})]})]})}function Ut(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function qt({col:t,idx:a,className:n,iconClassName:r,children:l}){const i=s.useEditorStore(h=>{var u;return(u=h.card)==null?void 0:u.preferences}),c=s.useEditorStore(h=>{var u,p;return(p=(u=h.card)==null?void 0:u.preferences)==null?void 0:p.datasetOptions}),o=c==null?void 0:c.find(h=>h.idx===a),{setCardPreferences:d}=s.useEditorStore(h=>h.actions);function m(h){if(!o)d({...i,datasetOptions:[...c||[],{idx:a,type:h==="area"?"line":h,fill:h==="area"?"origin":""}]});else{const u={...o};u.type=h==="area"?"line":h,u.fill=h==="area"?"origin":"";const p=c==null?void 0:c.map(g=>g.idx===a?u:g);d({...i,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(Es,{className:"max-w-[100px]",title:t,children:Ut(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($e,{onClick:()=>m("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Ge,{onClick:()=>m("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(et,{onClick:()=>m("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(pr,{idx:a})]})]})}function $t(){const t=s.useEditorStore(g=>g.selectedConnectionId),a=s.useEditorStore(g=>g.selectedDatamodelId),n=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),l=s.useEditorStore(g=>g.selectedTableName),i=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),o=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:m,tableName:h,connectionType:u}=s.useEditorAside();function p(g,f="dashboard"){var b;const x=s.fmt(g.column_name),S=s.fmt(n||""),j=s.fmt(r||""),v=s.fmt(h);let C=s.getQualifiedTableName({schemaName:j,tableName:v,connectionType:u,databaseName:S}),O=`${C}.${x}`;const D=(b=m==null?void 0:m.find(k=>k.id===a))==null?void 0:b.name;a&&a!=="none"&&(O=`${s.DATAMODEL_NAMESPCACE}.${D}.${x}`,C=`${s.DATAMODEL_NAMESPCACE}.${D}`);const N=i==null?void 0:i.find(k=>k.column===O&&k.table===v&&(k.database===S||k.database===n));if(N)d(N.id),o(N.id);else{const k=s.v4();return h==="api"&&t?(c({location:f,id:k,column:O,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,C,x)}),k):(c({id:k,location:f,column:O,title:g.column_name,dataType:g.data_type,table:l||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,C,x)}),k)}}return{assignFilter:p}}function Ee(){const t=s.useDashboardStore(o=>o.dashboard.filters),a=s.useEditorStore(o=>o.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=$t();function i(o){const d=l(o,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(o=>o.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(gr,{onSelect:i,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function gr({columns:t,onSelect:a}){var c;const[n,r]=ye.useState(!1),[l,i]=ye.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(c=t.find(o=>o.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(o=>e.jsxs(s.CommandItem,{value:o.column_name,onSelect:d=>{const m=d===l?"":d;i(m),r(!1),m&&a(o)},children:[o.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===o.column_name?"opacity-100":"opacity-0")})]},o.column_name))})]})]})})]})}function jr({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:a=>a.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:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}function Ke(){const t=s.useEditorStore(o=>o.card.type),a=s.useEditorStore(o=>o.isDevMode),n=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:r}=s.useEditorStore(o=>o.actions);function l(o){var h;const d={datalabels:{display:o!=="none",align:o,anchor:o,clamp:!0}},m={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(h=n==null?void 0:n.chartOptions)==null?void 0:h.plugins,...d}}};r(m)}function i(){var o,d,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((m=(d=(o=n==null?void 0:n.chartOptions)==null?void 0:o.plugins)==null?void 0:d.datalabels)==null?void 0:m.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 o,d,m;return e.jsx("div",{children:e.jsxs(s.Select,{value:((m=(d=(o=n==null?void 0:n.chartOptions)==null?void 0:o.plugins)==null?void 0:d.datalabels)==null?void 0:m.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:a?i():c()})}function yr({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="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"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:i=>i.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:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"px-2",children:e.jsx(Ke,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}const vr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},br={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Nr(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Cr(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ke,{}),e.jsx(we,{}),e.jsx(Ee,{})]})]})}function Cr(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(vr,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(br,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 Sr(){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(s.FormatNumberSetting,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function ns({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,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:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const wr=[{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"}],Tr=["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"],kr=Tr.map(t=>({label:t,value:t}));function Dr(){var d,m,h,u,p,g,f,x,S,j,v,C,O,D,N,b,k,w;const t=s.useEditorStore(L=>L.card),a=(m=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:m.topoJsonUrl,[n,r]=M.useState(((u=(h=t==null?void 0:t.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:u.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:i}=s.useTopoJson(t),c=Object.keys((i==null?void 0:i.objects)||{}).map(L=>({label:L,value:L}))||[],o=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(ns,{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(ns,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(ce,{className:"h-9",options:o,onValueChange:L=>{console.log("value",L),l({...t.preferences,mapVisualOptions:{topoJsonUrl:L}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:L=>{r(L.target.value)},onBlur:()=>{var L;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(L=t.preferences)==null?void 0:L.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(ce,{className:"h-9",options:c,value:((g=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:L=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,objectKey:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(ce,{className:"h-9",options:wr,value:((x=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:L=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projection:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(ce,{className:"h-9",options:kr,value:((j=(S=t.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:j.colorScale)||"",label:"Select Color Scale",onValueChange:L=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,colorScale:L}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(ns,{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:((C=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:C.projectionScale)||1,onChange:L=>{var T;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionScale:Number(L.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((N=(D=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:N[0])||0,onChange:L=>{var T,R,A,I;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[Number(L.target.value),((I=(A=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(k=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:w[1])||0,onChange:L=>{var T,R,A,I;l({...t.preferences,mapVisualOptions:{...(T=t.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[((I=(A=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[0])||0,Number(L.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(we,{})]})}function Er(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...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:n,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 Be({cardType:t,docContent:a,suffix:n="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)} ${n}`}),e.jsx(s.AccordionContent,{children:a||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."]})]})})]}),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:[t!=="text"&&e.jsx(Ke,{}),t==="text"&&e.jsx(Er,{})]})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}function Ir(){const t=s.useEditorStore(r=>{var l,i;return(i=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:i.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(ce,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(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:[n(),e.jsx(Vt,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})]})})}function Ar({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var i;return(i=l.card)==null?void 0:i.preferences}),n=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{n({...a,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:"Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(we,{}),e.jsx(Ee,{})]})]})}),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"})]})]})}const Mr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT 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."]})]}),Lr=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."]})]}),Or=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Rr(){const t=s.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Ir,{});case"tornado":case"pyramid":return e.jsx(Be,{docContent:Mr,cardType:n});case"kpi":return e.jsx(Sr,{});case"line":case"bar":return e.jsx(jr,{cardType:n});case"range":return e.jsx(Be,{docContent:Lr,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Be,{cardType:n});case"bubble":case"scatter":return e.jsx(yr,{cardType:n});case"table":return e.jsx(Ar,{cardType:n});case"text":return e.jsx(Be,{docContent:Or,cardType:n,suffix:"Visual"});case"map":return e.jsx(Dr,{});case"custom":return e.jsx(xr,{});default:return e.jsx(Nr,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Gt({label:t,column:a,functions:n,onFunctionChange:r}){let l=n[0];"aggregate"in a?l=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(l=n.find(c=>c.value===a.granularity)||n[0]);function i(c){r(c)}return e.jsx(ce,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:n,value:l.value,onValueChange:c=>i(c),label:t,showPlaceholderLabel:!1})}const Br=[{label:"Sum",value:"SUM",logo:e.jsx(rt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(fs,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(On,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(hn,{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 Fr({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Br;s.isTextDataType(t.type)&&(n=n.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(n=n.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const i={...t,aggregate:l,label:Le(t.name,l)};a(t.id,i)}return e.jsx(Gt,{column:t,functions:n,onFunctionChange:l=>r(l),label:"Aggregation"})}const zr=[{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 Pr({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const l={...t,granularity:r,label:De(t.name,r)};a(t.id,l)}return e.jsx(Gt,{column:t,functions:zr,onFunctionChange:r=>n(r),label:"Granularity"})}function _r({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),l=M.useMemo(()=>{let o=[];(n===be||n===Ne||n===Ce)&&(o=r);const d=o==null?void 0:o.filter(m=>m.column_name!==t.name);return d==null?void 0:d.map(m=>({id:m.column_name,value:m.column_name}))},[r,n,t.name]),i=[{id:t.name,value:t.name}];function c(o){const d=r==null?void 0:r.find(m=>{var h;return m.column_name===((h=o[0])==null?void 0:h.id)});d&&a(d)}return l!=null&&l.length?e.jsx(s.ComboBox2,{multiple:!1,options:l,selectedOptions:i,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 Ht({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var m,h;return(h=(m=d.card)==null?void 0:m.config)==null?void 0:h.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),i=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(qt,{idx:i,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function o(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Ke,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&o()]})}function Vr({column:t,type:a,onRemoveColumn:n,droppableId:r}){const[l,i]=M.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:o,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:m,listeners:h,setNodeRef:u,transform:p,transition:g,isDragging:f}=s.useSortable({id:t.id,data:{type:a}}),x=p?{opacity:f?.5:void 0,transform:s.CSS.Translate.toString(p),transition:g}:void 0,S=s.isTextDataType(t.type);function j(N){const b=s.isNumberDataType(N.data_type),k=s.isTextDataType(N.data_type),w=s.isDateDataType(N.data_type),L=b?"number":k?"string":w?"date":"string";if(r===be){if(k){const T={id:t.id,name:N.column_name,type:L,role:"groupby"};c(t.id,T)}if(w){const T={id:t.id,name:N.column_name,type:L,role:"groupby",label:De(N.column_name,"month"),granularity:"month"};c(t.id,T)}}if(r===Ce){if(k){const T={id:t.id,name:N.column_name,type:L,role:"groupby"};d(t.id,T)}if(w){const T={id:t.id,name:N.column_name,type:L,label:De(N.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,T)}}if(r===Ne){const T={id:t.id,name:N.column_name,type:L,role:"metric",label:Le(N.column_name,"SUM"),aggregate:b?"SUM":"COUNT"};o(t.id,T)}}function v(){if(r===Ne)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(Ht,{column:t})})}function C(){const N=s.isDateDataType(t.type);if(r===Ne)return e.jsx(Fr,{column:t});if((r===be||r===Ce)&&N)return e.jsx(Pr,{column:t})}function O(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===be||r===Ce)&&S}),children:e.jsx(_r,{col:t,onChange:j,droppableId:r})})}function D(){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:()=>i(!l),children:l?e.jsx(sa,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(tt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...h,...m,ref:u,style:x,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:[D(),C(),O()]}),l&&v()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>n(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function as({id:t,label:a,columns:n,previewColumns:r,sortableType:l,onRemoveColumn:i}){var x,S;const{setNodeRef:c,isOver:o,over:d}=s.useDroppable({id:t}),m=s.useDndStore(j=>j.activeId),h=s.useEditorStore(j=>{var v;return(v=j.card)==null?void 0:v.type}),u=o||((S=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:S.type)===l,p=m?r:n,g=l===_e?"Rows":l===Ve?"Pivot Columns":"Columns";function f(){if(!p||p.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:n==null?void 0:n.map(j=>j.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",u&&"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:a}),h!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),f(),e.jsx("div",{className:"space-y-2",children:p==null?void 0:p.map(j=>j.id===Dt.id?e.jsx(Ur,{},j.id):e.jsx(Vr,{droppableId:t,type:l,column:j,onRemoveColumn:i},j.id))})]})})}function Ur(){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:a,type:n}){const{attributes:r,listeners:l,setNodeRef:i,transform:c,transition:o,isDragging:d}=s.useSortable({id:a,data:{type:n}}),m=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:o}:void 0;return e.jsx("div",{...l,...r,ref:i,style:m,children:t})}function qr(){const t=s.useEditorStore(j=>{var v;return(v=j.card.queryConfig)==null?void 0:v.orderBy})||[],a=s.useEditorStore(j=>{var v;return(v=j.card.queryConfig)==null?void 0:v.groupByColumns})||[],n=s.useEditorStore(j=>{var v;return(v=j.card.queryConfig)==null?void 0:v.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:i}=s.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const o=e.jsx(gn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(mn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(fn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=e.jsx(un,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=c==null?void 0:c.filter(j=>!t.some(v=>v.columnId===j.id)).map(j=>({id:j.id,value:j.label||j.name}));function p(j,v){const C=g(j);return C?C.role==="metric"?v==="asc"?m:h:v==="asc"?o:d:null}function g(j){return c.find(v=>v.id===j)}function f(j){const v=t.find(C=>C.columnId===j);if(v){const C={...v,direction:v.direction==="asc"?"desc":"asc"};i(C)}}const x=j=>{r({columnId:j.id,direction:"asc"})};function S(j){const v=t.find(C=>C.columnId===j);v&&l(v)}return e.jsx(s.SortableContext,{items:t.map(j=>Ie(j.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"}),u.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:u,selectedOptions:[],onChange:j=>x(j[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(j=>{var v,C;return e.jsx(Jt,{id:Ie(j.columnId),type:Ns,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(tt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Es,{className:"w-[175px] text-sm",children:((v=g(j.columnId))==null?void 0:v.label)||((C=g(j.columnId))==null?void 0:C.name)})]}),e.jsx("button",{title:j.direction==="asc"?"Ascending":"Descending",onClick:()=>f(j.columnId),className:"rounded-sm p-0",children:p(j.columnId,j.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>S(j.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"})})})]})},j.columnId)},Ie(j.columnId))})]})})}function $r(){const t=s.useEditorStore(S=>{var j;return((j=S.card.queryConfig)==null?void 0:j.groupByColumns)||[]}),a=s.useEditorStore(S=>S.card.type),n=s.useDndStore(S=>S.previewGroupByColumns),r=s.useEditorStore(S=>{var j;return((j=S.card.queryConfig)==null?void 0:j.metricColumns)||[]}),l=s.useDndStore(S=>S.previewMetricColumns),i=s.useEditorStore(S=>{var j;return((j=S.card.queryConfig)==null?void 0:j.pivotColumns)||[]}),c=s.useDndStore(S=>S.previewPivotColumns),{removeColumnFromGroupBy:o,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:m}=s.useEditorActions();function h(S){o(S)}function u(S){d(S)}function p(S){m(S)}let g="Group By",f="Metrics",x="Stack By";return a==="table"&&(g="Rows",f="Metrics",x="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(as,{onRemoveColumn:h,sortableType:_e,id:be,label:g,columns:t,previewColumns:n}),e.jsx(as,{onRemoveColumn:p,sortableType:Ve,id:Ce,label:x,columns:i,previewColumns:c}),e.jsx(as,{onRemoveColumn:u,sortableType:ls,id:Ne,label:f,columns:r,previewColumns:l}),e.jsx(qr,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Is({children:t,column:a,id:n,sortableType:r,className:l}){const[i,c]=M.useState(!1),{removeEditorFilter:o,clearEditorFilter:d}=s.useEditorActions(),m=s.useEditorStore(u=>{var p,g;return(g=(p=u.card.queryConfig)==null?void 0:p.filters)==null?void 0:g.some(f=>f.filterColumnName===a.name)});function h(u){o(u)}return e.jsx(Jt,{id:n,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":i}),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:a.name}),m&&e.jsx("button",{onClick:()=>d(a),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:()=>h(a),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",!i&&"rounded-b-md",i&&"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 Gr({column:t,sortableType:a}){const n=s.useDashboardStore(C=>C.themeStyle),r=s.useEditorStore(C=>{var O,D;return(D=(O=C.card)==null?void 0:O.queryConfig)==null?void 0:D.filters}),l=s.useEditorStore(C=>{var O,D;return(D=(O=C.card.queryConfig)==null?void 0:O.filterColumns)==null?void 0:D.find(N=>N.name===t.name)}),{selectedConnectionId:i,selectedDatabaseName:c,selectedTableName:o}=s.useEditorAside(),d=M.useMemo(()=>{var C;return(C=r==null?void 0:r.find(O=>O.filterColumnName===t.name))==null?void 0:C.filterValue},[r,t.name]),m=M.useMemo(()=>Array.isArray(d)?d.map(C=>({id:C,value:C})):[],[d]),{updateEditorFilterValue:h}=s.useEditorActions(),u={column:t.name,sql:t.sql,id:t.name,connectionId:i,dataType:t.type},{data:p,isLoading:g,isFetching:f,isError:x}=s.useFilterQuery(u),S=M.useMemo(()=>{var O;return u.column?(O=p==null?void 0:p.records)==null?void 0:O.map(D=>{let N=u.column.split(".").slice(-1)[0].replace(/"/g,"");return D[N]===void 0&&(N=N.toLowerCase()),{id:D[N],value:D[N]}}):[]},[p,u.column]);function j(C){const O=C.map(D=>D.id);h(t.name,O)}function v(){return g||f?e.jsx(s.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):x?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(Hr,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:S,onChange:j,selectedOptions:m,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Is,{className:"w-60",id:t.id,sortableType:a,column:t,children:v()})}function Hr({columnName:t}){const{setEditorFilterMode:a}=s.useEditorActions(),n=s.useEditorStore(l=>{var i,c;return(c=(i=l.card.queryConfig)==null?void 0:i.filterColumns)==null?void 0:c.find(o=>o.name===t)});function r(){(n==null?void 0:n.mode)==="exclude"?a(t,"include"):a(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((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function Jr({column:t,sortableType:a}){const[n,r]=M.useState(!1),{selectedConnectionId:l,selectedDatabaseName:i,selectedTableName:c}=s.useEditorAside(),o={column:t.name,sql:t.sql,id:t.name,connectionId:l,title:"",dataType:t.type},{isLoading:d,isFetching:m,isError:h,data:u}=s.useFilterQuery(o),p=u==null?void 0:u.records,{dateRange:g,setDateRange:f,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:S}=s.useEditorActions();function j(O){var N,b;const D={gte:(N=O==null?void 0:O.from)==null?void 0:N.toISOString(),lte:(b=O==null?void 0:O.to)==null?void 0:b.toISOString()};S(t.name,D)}function v(){S(t.name,null,!0),f(x)}function C(){return d||m?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):h?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):p?e.jsx(s.DateRangePopover,{title:o.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:f,onApply:j,onClear:v}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Is,{className:"w-72",id:t.id,sortableType:a,column:t,children:C()})}function Wr({id:t,label:a,columns:n,previewColumns:r,sortableType:l}){var f,x;const{setNodeRef:i,isOver:c,over:o}=s.useDroppable({id:t}),d=s.useDndStore(S=>S.activeId),m={},h=c||((x=(f=o==null?void 0:o.data)==null?void 0:f.current)==null?void 0:x.type)===l;function u(){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 p(S){const j=s.isDateDataType(S.type);return S.id===Dt.id?e.jsx(Is,{id:S.id,sortableType:l,column:S,children:e.jsx(Yr,{})},S.id):j?e.jsx(Jr,{droppableId:t,sortableType:l,column:S},S.id):e.jsx(Gr,{droppableId:t,sortableType:l,column:S},S.id)}const g=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(S=>S.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",h&&"border border-muted-foreground/20"),ref:i,style:m,children:[e.jsx(s.Label,{className:"text-sm",children:a}),u(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(S=>p(S))})]})})}function Yr(){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 Kr(){const t=s.useEditorStore(l=>{var i;return((i=l.card.queryConfig)==null?void 0:i.filterColumns)||[]}),a=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:n}=s.useEditorActions();function r(l){n(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(Wr,{onRemoveColumn:r,sortableType:is,id:os,label:"Filters",columns:t,previewColumns:a})})}function Qr(){const t=s.useEditorStore(i=>i.card),a=s.useEditorStore(i=>i.showAIDialog),{setShowAIDialog:n}=s.useEditorActions(),{data:r,errorMessage:l}=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(s.EditorClearButton,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(Wn,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(Mt,{sql:r==null?void 0:r.sql,error:l})]}),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(s.EditorCancelButton,{}),e.jsx(s.EditorAcceptButton,{variant:"default"})]})]})}function Xr(){const t=M.useRef(null),a=M.useRef(null),n=s.useEditorStore(o=>o.isShowingVisual),r=s.useEditorStore(o=>o.showAIDialog),l=s.useEditorStore(o=>o.isDevMode);M.useEffect(()=>{var o,d,m,h;r?((o=t.current)==null||o.resize(0),(d=a.current)==null||d.resize(0)):((m=t.current)==null||m.resize(25),(h=a.current)==null||h.resize(25))},[r]);function i(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Qa,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Rr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Re,{})})]}):e.jsx(Re,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx($r,{})})}),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(Qr,{}),e.jsx(Kr,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Re,{})})]})})]}):e.jsx(Re,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?i():c()})}function Zr(t){const a=s.useAIInteractionStore(B=>B.currentAIContext),[n,r]=M.useState(""),[l,i]=M.useState(null),{authToken:c}=s.useSemaphorContext(),o=s.useEditorStore(B=>{var K;return(K=B==null?void 0:B.card)==null?void 0:K.sql}),d=s.useEditorStore(B=>B.isDevMode),m=s.useEditorStore(B=>{var K;return(K=B==null?void 0:B.card)==null?void 0:K.python}),{setCardPython:h,setCardSql:u,setRunSql:p,switchCardType:g,setQueryConfig:f}=s.useEditorActions(),x=s.useEditorStore(B=>B.currentAssitantScope)||[],S=s.useEditorStore(B=>B.userInputForAI),j=s.useEditorStore(B=>B.triggerAIRun),v=s.useEditorStore(B=>B.card),C=s.useEditorStore(B=>B.selectedDatabaseName),O=s.useEditorStore(B=>B.selectedTableName),D=s.useEditorStore(B=>B.selectedConnectionId),N=s.useEditorStore(B=>B.selectedSchemaName),b=s.useDashboardStore(B=>B.dashboard.aiScopeTables),{errorMessage:k,refetch:w,data:L}=s.useDashboardCardQuery(v),{setTriggerAIRun:T,setCurrentAssitantScope:R,setCardConfig:A}=s.useEditorActions(),{selectedDatamodelName:I,connectionType:y,selectedDatamodelId:E}=s.useEditorAside(),{messages:F,setMessages:z,reload:_,error:P,append:Q,input:Y,setInput:V,status:q,handleInputChange:$,handleSubmit:U,stop:H}=s.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${c==null?void 0:c.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:d,aiContext:a},maxSteps:10,onError:B=>{console.log("on error",B)},onToolCall:W,onFinish(B,K){G(K.usage),r(""),K.finishReason==="stop"&&r("")}});M.useEffect(()=>{j&&S&&(Q({role:"user",content:S}),T(!1))},[j,S,Q,T]);async function W({toolCall:B}){var K,re,he,je;if(["createChartFromSql","createForecast"].includes(B.toolName)){const te=B.args.sql,le=B.args.python,oe=B.args.chartType;return g(oe),u(te),h(le),p(!0),{status:"success",message:"Let the user know that chart is created"}}else if(B.toolName==="getTableColumns")r("Getting table columns...");else{if(B.toolName==="getUserSql")return o?{status:"success",sql:o,python:m||""}:{status:"error",message:"No SQL found"};if(B.toolName==="getCurrentTableScope")return r("Getting table scope..."),ee(),{status:"success",tables:x};if(B.toolName==="generateQueryConfig"){r("Generating query config...");const te=B.args.chartType,le=B.args.queryConfig;B.args.cardConfig,g(te),A(le),u(void 0),h(void 0);const oe=await w();return(K=oe==null?void 0:oe.data)!=null&&K.error?{status:"error",queryConfig:le,message:(re=oe==null?void 0:oe.data)==null?void 0:re.error.message}:(he=oe==null?void 0:oe.data)!=null&&he.records?{status:"success",queryConfig:le,message:"The data has been visualized"}:{status:"success",queryConfig:le,message:"The data has been visualized",records:(je=oe==null?void 0:oe.data)==null?void 0:je.records}}else r("Analyzing...")}}function G(B){i(K=>K?{promptTokens:K.promptTokens+B.promptTokens,completionTokens:K.completionTokens+B.completionTokens,totalTokens:K.totalTokens+B.totalTokens}:B)}function Z(B){const K=s.removeFromScopeArray(x,B);se(K)}function se(B){const K=s.sanitizeAIScope(B);R(K),z(re=>[...re,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(K)}`}])}function ne(){const B={databaseName:C||"",schemaName:N||"",tableName:O||"",datamodelId:E||"",datamodelName:s.resolveDatamodelName(I),connectionId:D||"",connectionType:y||""},K=s.dedup([...x,B]);se(K)}function ee(){const B={databaseName:C||"",schemaName:N||"",tableName:O||"",datamodelName:s.resolveDatamodelName(I),connectionId:D||"",connectionType:y||"",datamodelId:E||""};if(!s.isInAiScopeArray([...b||[],...x],B)||x.length===0){const re=s.dedup([...b||[],...x,B]).filter(he=>he.connectionId===B.connectionId);se(re)}}const ae=!["ready","error"].includes(q),J=s.getErrorMessage(P);return{messages:F,setMessages:z,reload:_,append:Q,input:Y,setInput:V,isLoading:ae,handleSetAIScope:ee,handleAddCurrentTableToScope:ne,removeFromCurrentSelections:Z,currentAssitantScope:x,setCurrentAssitantScope:R,handleInputChange:$,handleSubmit:U,stop:H,chatStatus:q,toolStatus:n,llmUsage:l,onFinish:t,errorMessage:J}}const el=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Ws(){const t=M.useRef(null),a=M.useRef(null),[n,r]=M.useState(!1),[l,i]=M.useState(s.isDevEnv),[c,o]=M.useState(!1),[d,m]=M.useState(!1),h=s.useCurrentAIContext(),{setCurrentAIContext:u}=s.useAIActions(),p=s.useDashboardStore(H=>H.dashboard.aiContext),g=s.useEditorStore(H=>H.card.dataSource),f=s.useEditorStore(H=>H.actions.setCardSql),x=s.useEditorStore(H=>H.actions.setRunSql),S=s.useEditorStore(H=>H.showAIDialog),j=s.useDashboardStore(H=>H.handleOpenAssistantProfile),{setShowAIDialog:v,setCardPython:C}=s.useEditorActions(),{setDataSource:O}=s.useEditorActions(),{assistantProfile:D}=s.useAssistantProfile(),{messages:N,setMessages:b,reload:k,append:w,input:L,setInput:T,isLoading:R,handleInputChange:A,handleSubmit:I,stop:y,chatStatus:E,llmUsage:F,errorMessage:z}=Zr();s.useAssistantScroll({scrollContainerRef:t,inputRef:a,messages:N}),M.useEffect(()=>{var H;S&&((H=a.current)==null||H.focus(),u({selectedEntities:(g==null?void 0:g.selectedEntities)||[]}))},[S,g,u]);function _(H,W){W==="sql"?(f(H),x(!0)):W==="python"&&(C(H),x(!0))}function P(){var H;(H=p==null?void 0:p.selectedEntities)==null||H[0],m(!0)}function Q(){h.selectedEntities.length===0&&u({selectedEntities:(p==null?void 0:p.selectedEntities)||[]})}function Y(H){Q();const W={role:"user",content:H.title+" "+H.subtitle};w(W)}function V(H){Q(),w({role:"user",content:H})}function q(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:o,children:"System Message"})]})]})}function $(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const U=(L==null?void 0:L.length)===0&&(N==null?void 0:N.filter(H=>H.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[$(),j&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:j,children:(D==null?void 0:D.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[q(),e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:P,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{b([]),k()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-8 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{v(!1)},children:e.jsx(s.EyeOff,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:t,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(s.PrintMessages,{messages:N,showTools:l,handleRun:_,showSystemMessage:c}),e.jsx(s.ChatStatus,{messages:N,chatStatus:E,errorMessage:z})]})}),e.jsxs("div",{className:"mb-3",children:[U&&!D&&e.jsx(s.Placeholders,{onClick:Y,placeholders:el}),e.jsx("div",{children:U&&D&&e.jsx(s.SeedQuestions,{seedQuestions:D.seedQuestions||[],handleSeedQuestionClick:V})})]}),e.jsx(s.ChatInputWithContext,{ref:a,setInput:T,stop:y,input:L,handleInputChange:A,handleSubmit:H=>{Q(),I(H)},isLoading:R,onFocus:()=>{}}),F&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",F.promptTokens," prompt tokens,"," ",F.completionTokens," completion tokens,"," ",F.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(g==null?void 0:g.selectedEntities)||[],open:d,onOpenChange:m,dataSource:g||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function Wt(t,a){return`${t}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Yt(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function sl(t,a){const n=s.getDataType(t.dataType);return n==="number"?"metrics":n==="date"||n==="string"?"groupBy":"metrics"}function cs(t,a){const n=Wt(a,t),r=s.getDataType(t.dataType),l=r==="date",i={id:n,name:t.name,dataType:t.dataType,label:s.toLabel(t.name),qualifiedEntityName:t.qualifiedEntityName,entityId:t.entityId,entityName:t.entityName,entityType:t.entityType};if(a==="metrics"){const c=r==="number"?"SUM":"COUNT",o=Yt(t.label,c);return{...i,role:"metric",label:o,aggregate:c}}return a==="groupBy"?{...i,role:"groupby",...l&&{granularity:"month",dateFormat:"YYYY-MM"}}:a==="pivotBy"?{...i,role:"pivotby"}:a==="sortBy"?{...i,role:"sortby",label:t.label,direction:"asc"}:null}function Kt(t,a,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:t===a||t===n.baseEntity.name||a===n.baseEntity.name?!0:n.joins.some(l=>{const i=s.getQualifiedEntityName(l.source),c=s.getQualifiedEntityName(l.target);return i===t&&c===a||i===a&&c===t})}function tl(t,a,n){if(a.length===0)return{isValid:!0};const r=a[0].qualifiedEntityName;if(!r)return{isValid:!0};if(r!==t.qualifiedEntityName&&t.qualifiedEntityName)if(n){if(!Kt(r,t.qualifiedEntityName,n))return{isValid:!1,showError:!0}}else return{isValid:!1,showError:!0};return{isValid:!0}}function ds(){s.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})}function us(t,a){return a.some(n=>n.name===t.name&&n.qualifiedEntityName===t.qualifiedEntityName)}const As=t=>{var T;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:i,removeGroupByColumn:c,removeMetricColumn:o,removePivotByColumn:d,removeSortByColumn:m}=s.useEditorActions(),h=s.useEditorStore(R=>R.card.type),u=t==null?void 0:t.id,p=M.useCallback(R=>{if(!(t!=null&&t.config))return[];switch(R){case"groupBy":return(t.config.groupByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,dateFormat:A.dateFormat,customFormat:A.customFormat,granularity:A.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,direction:A.direction}));case"source":return[];default:return[]}},[t]),g=M.useCallback((R,A)=>{if(u)switch(R){case"groupBy":{a(u,{groupByColumns:A});break}case"metrics":{a(u,{metricColumns:A});break}case"pivotBy":{a(u,{pivotByColumns:A});break}case"sortBy":{a(u,{sortByColumns:A});break}}},[u,a]),f=M.useCallback((R,A,I)=>{if(!u)return;const E=p(R)[A];if(E)switch(R){case"groupBy":n(u,E.id,{label:I});break;case"metrics":r(u,E.id,{label:I});break;case"pivotBy":l(u,E.id,{label:I});break;case"sortBy":i(u,E.id,{label:I});break}},[u,p,n,r,l,i]),x=M.useCallback((R,A)=>{if(!u)return;const y=p("metrics")[R];y&&r(u,y.id,{aggregate:A,label:Yt(y.name,A)})},[u,p,r]),S=M.useCallback((R,A,I)=>{if(!u)return;const E=p("groupBy")[R];if(!E)return;const F={dateFormat:A};A==="custom"&&I?F.customFormat=I:F.customFormat=void 0,n(u,E.id,F)},[u,p,n]),j=M.useCallback((R,A)=>{if(!u)return;const y=p("groupBy")[R];y&&n(u,y.id,{granularity:A})},[u,p,n]),v=M.useCallback((R,A)=>{if(!u)return;const y=p("metrics")[R];y&&r(u,y.id,{aliasTemplate:A})},[u,p,r]),C=M.useCallback((R,A)=>{if(console.log("handleValueAliasesChange",R,A),!u)return;console.log("handleValueAliasesChange",R,A);const y=p("metrics")[R];y&&(console.log("handleValueAliasesChange",A),r(u,y.id,{valueAliases:A}))},[u,p,r]),O=M.useCallback(R=>{u&&a(u,{comparisonType:R})},[u,a]),D=M.useCallback(R=>{u&&a(u,{showTrendline:R})},[u,a]),N=M.useCallback(R=>{u&&a(u,{trendlineWindow:R})},[u,a]),b=M.useCallback(R=>{u&&a(u,{trendlineGranularity:R})},[u,a]),k=M.useCallback(R=>{u&&a(u,{targetValue:R})},[u,a]),w=M.useCallback(R=>{var _;if(!u)return;const A=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],I=(_=t==null?void 0:t.config)==null?void 0:_.joinPlan,y=tl(R,A,I);if(!y.isValid){y.showError&&ds();return}const E=sl(R),F=p(E);if(us(R,F))return;const z=cs(R,E);z&&g(E,[...F,z])},[u,(T=t==null?void 0:t.config)==null?void 0:T.joinPlan,p,g]),L=M.useCallback((R,A)=>{if(!u)return;const y=p(R)[A];if(y){if(R!=="sortBy"){const E=p("sortBy"),F=E.filter(z=>!(z.name===y.name&&z.qualifiedEntityName===y.qualifiedEntityName));F.length!==E.length&&a(u,{sortByColumns:F})}switch(R){case"groupBy":c(u,y.id);break;case"metrics":o(u,y.id);break;case"pivotBy":d(u,y.id);break;case"sortBy":m(u,y.id);break}}},[u,p,c,o,d,m,a]);return{getFieldsForContainer:p,setFieldsForContainer:g,updateLabel:f,handleAggregationChange:x,handleDateFormatChange:S,handleGranularityChange:j,handleAliasTemplateChange:v,handleValueAliasesChange:C,removeField:L,handleFieldClick:w,handleKpiComparisonTypeChange:O,handleKpiShowTrendlineChange:D,handleKpiTrendlineWindowChange:N,handleKpiTrendlineGranularityChange:b,handleKpiTargetValueChange:k,cardType:h}};function nl({field:t}){const{attributes:a,listeners:n,setNodeRef:r,transform:l,transition:i,isDragging:c}=s.useSortable({id:t.id}),[o,d]=M.useState(!1),m=s.useEditorStore(x=>x.card),{handleFieldClick:h}=As(m),u={transform:s.CSS.Transform.toString(l),transition:i},p=s.getDataType(t.dataType),f=(x=>{const S=(x||"").toLowerCase();switch(s.getDataType(S)){case"number":return fs;case"date":return s.Calendar;case"boolean":return ot;case"json":return wn;case"geo":return Hn;default:return it}})(t.dataType);return e.jsxs("div",{ref:r,style:u,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:border-blue-200 hover:bg-blue-50 dark:hover:border-blue-800 dark:hover:bg-blue-950"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 p-2",onClick:()=>h(t),children:[e.jsx("div",{className:"flex-shrink-0 hover:cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"invisible size-3.5 text-gray-400 group-hover/container:visible"})}),e.jsx(f,{className:s.cn("size-3.5 flex-shrink-0 text-gray-500",p==="string"?"text-blue-500":"",p==="number"?"text-green-500":"",p==="date"?"text-purple-500":"",p==="boolean"?"text-orange-500":"")}),e.jsx(s.TooltipProvider$1,{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/90 hover:text-foreground dark:text-muted-foreground ${o?"whitespace-normal break-words":"truncate"}`,children:t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:t.label||t.name}),t.description&&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:t.description})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"mr-2 text-muted-foreground",children:"Name:"}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.name})]}),e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"mr-2 text-muted-foreground",children:"Type:"}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.dataType})]}),t.qualifiedEntityName&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[t.entityType?t.entityType.charAt(0).toUpperCase()+t.entityType.slice(1):"Entity",":"]}),e.jsx("span",{className:"font-mono text-muted-foreground",children:t.qualifiedEntityName})]})]})]})})]})})]}),o&&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(lt,{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(aa,{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 al(){const[t,a]=M.useState(""),[n,r]=M.useState("all"),l=s.useEditorStore(C=>C.card.dataSource),{columns:i=[],columnGroups:c=[],isLoading:o,error:d}=s.useColumns(),m=i.filter(C=>C.name.toLowerCase().includes(t.toLowerCase())||C.dataType.toLowerCase().includes(t.toLowerCase())||C.qualifiedEntityName&&C.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),h=C=>{if(C.dataType==="number"||C.dataType==="integer"||C.dataType==="float"||C.dataType==="decimal"||C.dataType==="currency")return"metrics";const O=s.getDataType(C.dataType);return["date","string","boolean"].includes(O)?"dimensions":O==="number"?"metrics":"dimensions"},p=(n==="all"?m:m.filter(C=>h(C)===n)).reduce((C,O)=>{const D=O.qualifiedEntityName||"Other Fields";return C[D]||(C[D]={label:s.toLabel(O.entityName),fields:[]}),C[D].fields.push(O),C},{}),f=Object.keys(p),x=m.filter(C=>h(C)==="dimensions").length,S=m.filter(C=>h(C)==="metrics").length,j=m.filter(C=>h(C)==="calculated").length,v=m.length>0;return o?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):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:[i.length>0&&e.jsx("div",{className:"mb-4",children:e.jsx(s.Input$1,{type:"text",placeholder:"Search fields...",value:t,onChange:C=>a(C.target.value)})}),v&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:C=>r(C),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: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:x})]}),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:S})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Nn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:f,className:"space-y-2",children:Object.entries(p).map(([C,O])=>{const D=c.find(N=>N.entityName===C)||{entityName:C,label:O.label};return e.jsxs(s.AccordionItem,{value:C,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-3 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-primary",children:D.label||D.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:O.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:O.fields.map(N=>e.jsx(nl,{field:N},N.id))})})]},C)})}),Object.keys(p).length===0&&i.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(p).length===0&&i.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 rl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(al,{})," "]})}function ll({initialJoinPlan:t,availableDataSources:a}){const[n,r]=M.useState(t),[l,i]=M.useState(new Set),c=()=>{const N=n.joins.length>0?Math.max(...n.joins.map(k=>k.sequence))+1:1,b={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:N,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,b]}),i(new Set([...l,b.id]))},o=N=>{r({...n,joins:n.joins.filter(b=>b.id!==N)}),i(new Set([...l].filter(b=>b!==N)))},d=(N,b)=>{var T,R;const k=n.joins.find(A=>A.id===N);if(!k)return;const w={...k,...b},L=n.joins.map(A=>A.id===N?w:A);if((T=w.source)!=null&&T.name&&((R=w.target)!=null&&R.name)&&w.joinKeyGroups[0].keys.length===0){const A=a.find(F=>{var z;return F.name===((z=w.source)==null?void 0:z.name)}),I=a.find(F=>{var z;return F.name===((z=w.target)==null?void 0:z.name)}),y={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="},E=[...w.joinKeyGroups];E[0]={...E[0],keys:[y]},w.joinKeyGroups=E,L[L.findIndex(F=>F.id===N)]=w}r({...n,joins:L})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:o,updateJoin:d,moveJoinUp:N=>{const b=n.joins.findIndex(k=>k.id===N);if(b>0){const k=[...n.joins],w={...k[b]},L={...k[b-1]};k[b]=L,k[b-1]=w,k.forEach((R,A)=>{R.sequence=A+1});const T={...n,joins:k};r(T)}},moveJoinDown:N=>{const b=n.joins.findIndex(k=>k.id===N);if(b<n.joins.length-1){const k=[...n.joins],w={...k[b]},L={...k[b+1]};k[b]=L,k[b+1]=w,k.forEach((R,A)=>{R.sequence=A+1});const T={...n,joins:k};r(T)}},toggleJoinExpansion:N=>{const b=new Set(l);b.has(N)?b.delete(N):b.add(N),i(b)},getAvailableSourceEntities:N=>{if(n.joins.length===0)return a;const b=n.joins.findIndex(w=>w.id===N);if(b===0)return a;const k=new Set;return n.baseEntity.name&&k.add(n.baseEntity.name),n.joins.slice(0,b).forEach(w=>{k.add(w.source.name),k.add(w.target.name)}),a.filter(w=>k.has(w.name))},getAvailableTargetEntities:N=>a.filter(b=>b.name!==N),addJoinKeyGroup:N=>{const b=n.joins.find(w=>w.id===N);if(!b)return;const k=[...b.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(N,{joinKeyGroups:k})},updateGroupOperator:(N,b,k)=>{const w=n.joins.find(T=>T.id===N);if(!w)return;const L=[...w.joinKeyGroups];L[b]={...L[b],operator:k},d(N,{joinKeyGroups:L})},removeJoinKeyGroup:(N,b)=>{const k=n.joins.find(L=>L.id===N);if(!k)return;const w=[...k.joinKeyGroups];w.splice(b,1),d(N,{joinKeyGroups:w})},addJoinKey:(N,b)=>{const k=n.joins.find(A=>A.id===N);if(!k)return;const w=a.find(A=>A.name===k.source.name),L=a.find(A=>A.name===k.target.name),T=[...k.joinKeyGroups],R={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(L==null?void 0:L.name)||"",entityName:(L==null?void 0:L.name)||"",entityType:(L==null?void 0:L.type)||"table"},operator:"="};T[b]={...T[b],keys:[...T[b].keys,R]},d(N,{joinKeyGroups:T})},updateJoinKey:(N,b,k,w,L)=>{const T=n.joins.find(E=>E.id===N);if(!T)return;const R=a.find(E=>E.name===T.source.name),A=a.find(E=>E.name===T.target.name),I=[...T.joinKeyGroups],y=I[b].keys[k];w==="sourceColumnName"&&R?I[b].keys[k]={...y,source:{...y.source,name:L}}:w==="targetColumnName"&&A?I[b].keys[k]={...y,target:{...y.target,name:L}}:w==="operator"&&(I[b].keys[k]={...y,operator:L}),d(N,{joinKeyGroups:I})},removeJoinKey:(N,b,k)=>{const w=n.joins.find(T=>T.id===N);if(!w)return;const L=[...w.joinKeyGroups];L[b].keys.splice(k,1),d(N,{joinKeyGroups:L})},generateSQLPreview:()=>{const N=[...n.joins].sort((w,L)=>w.sequence-L.sequence),b=n.baseEntity;if(!b.name)return"SELECT * FROM table -- Please select a base entity";let k=`SELECT *
415
+ FROM ${b.name}`;return N.forEach(w=>{const L=a.find(A=>A.name===w.target.name);if(!L)return;const T=w.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const I=A.keys.filter(y=>{var E,F,z,_;return((E=y.source)==null?void 0:E.name)&&((F=y.target)==null?void 0:F.name)&&((z=y.source)==null?void 0:z.entityName)&&((_=y.target)==null?void 0:_.entityName)}).map(y=>`${y.source.entityName}.${y.source.name} ${y.operator} ${y.target.entityName}.${y.target.name}`);return I.length>1?`(${I.join(` ${A.operator} `)})`:I[0]}).filter(Boolean),R=T.length>1?T.join(" OR "):T[0]||"condition_here";k+=`
416
416
  ${w.joinType} JOIN ${L.name}
417
- ON ${R}`}),k},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(w=>!w.source.name||!w.target.name)||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.length===0))||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.some(T=>!T.source.name||!T.target.name||!T.operator))))}}function ol({joinPlan:t,availableDataSources:a,onSave:n,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:m,addJoin:h,removeJoin:u,updateJoin:p,moveJoinUp:j,moveJoinDown:f,toggleJoinExpansion:x,getAvailableSourceEntities:S,getAvailableTargetEntities:g,addJoinKeyGroup:v,updateGroupOperator:N,removeJoinKeyGroup:O,addJoinKey:C,updateJoinKey:D,removeJoinKey:b,generateSQLPreview:k,isValidConfiguration:w}=ll({initialJoinPlan:t,availableDataSources:a}),L=T=>{const R=c.find(A=>A.entityName===T);return(R==null?void 0:R.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 R=a.find(A=>A.name===T);m({...i,baseEntity:{connectionId:(R==null?void 0:R.connectionId)||"",connectionType:(R==null?void 0:R.connectionType)||"none",type:(R==null?void 0:R.type)||"table",name:T,database:R==null?void 0:R.database,schema:R==null?void 0:R.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.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:h,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 R=a.find(y=>y.name===T.source.name),A=a.find(y=>y.name===T.target.name),I=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,R&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",R.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(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:()=>f(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:()=>x(T.id),children:I?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:()=>u(T.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),I&&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:y=>{const E=a.find(F=>F.name===y);p(T.id,{source:{connectionId:(E==null?void 0:E.connectionId)||"",connectionType:(E==null?void 0:E.connectionType)||"none",type:(E==null?void 0:E.type)||"table",name:y,database:E==null?void 0:E.database,schema:E==null?void 0:E.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:S(T.id).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name]})},y.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:T.joinType,onValueChange:y=>p(T.id,{joinType:y}),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:y=>{const E=a.find(F=>F.name===y);p(T.id,{target:{connectionId:(E==null?void 0:E.connectionId)||"",connectionType:(E==null?void 0:E.connectionType)||"none",type:(E==null?void 0:E.type)||"table",name:y,database:E==null?void 0:E.database,schema:E==null?void 0:E.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?g(T.source.name).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,y.name===T.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},y.name)):[]})]})]})]}),T.source.name&&T.target.name&&R&&A&&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:()=>v(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((y,E)=>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 ",E+1]}),E>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:y.operator,onValueChange:F=>N(T.id,E,F),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:()=>O(T.id,E),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[y.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:y.keys.map((F,z)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[z>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:y.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.source.name,onValueChange:_=>D(T.id,E,z,"sourceColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:L(T.source.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:F.operator,onValueChange:_=>D(T.id,E,z,"operator",_),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:F.target.name,onValueChange:_=>D(T.id,E,z,"targetColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:L(T.target.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>b(T.id,E,z),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||z))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>C(T.id,E),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},y.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:()=>n(i),disabled:!w(),children:"Save"})]})]})}function Ys({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,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(ol,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function il({joins:t,baseEntityId:a,availableDataSources:n,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=n.find(c=>c.name===a);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=n.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=n.find(d=>d.name===l.source.name),i=n.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,m)=>d+m.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,m)=>d+m.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 cl(){var h,u;const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.actions.updateCardConfig),n=((h=t==null?void 0:t.config)==null?void 0:h.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=M.useState(!1),o=((u=t==null?void 0:t.dataSource)==null?void 0:u.selectedEntities)||[],c=p=>{a(t.id,{...t==null?void 0:t.config,joinPlan:p}),l(!1)},i=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},m=()=>{const p=[...n.joins].sort((x,S)=>x.sequence-S.sequence),j=n.baseEntity;if(!j.name)return"SELECT * FROM table -- Please select a base entity";let f=`SELECT *
418
- FROM ${j.name}`;return p.forEach(x=>{const S=o.find(N=>N.name===x.target.name);if(!S)return;const g=x.joinKeyGroups.filter(N=>N.keys&&N.keys.length>0).map(N=>{const O=N.keys.filter(C=>{var D,b,k,w;return((D=C.source)==null?void 0:D.name)&&((b=C.target)==null?void 0:b.name)&&((k=C.source)==null?void 0:k.entityName)&&((w=C.target)==null?void 0:w.entityName)}).map(C=>`${C.source.entityName}.${C.source.name} ${C.operator} ${C.target.entityName}.${C.target.name}`);return O.length>1?`(${O.join(` ${N.operator} `)})`:O[0]}).filter(Boolean),v=g.length>1?g.join(" OR "):g[0]||"condition_here";f+=`
417
+ ON ${R}`}),k},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(w=>!w.source.name||!w.target.name)||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.length===0))||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.some(T=>!T.source.name||!T.target.name||!T.operator))))}}function ol({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:l}){const{setCardConfig:i}=s.useEditorActions();s.useEditorStore(T=>T.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:o,expandedJoins:d,setJoinPlan:m,addJoin:h,removeJoin:u,updateJoin:p,moveJoinUp:g,moveJoinDown:f,toggleJoinExpansion:x,getAvailableSourceEntities:S,getAvailableTargetEntities:j,addJoinKeyGroup:v,updateGroupOperator:C,removeJoinKeyGroup:O,addJoinKey:D,updateJoinKey:N,removeJoinKey:b,generateSQLPreview:k,isValidConfiguration:w}=ll({initialJoinPlan:t,availableDataSources:a}),L=T=>{const R=c.find(A=>A.entityName===T);return(R==null?void 0:R.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:o.baseEntity.name,onValueChange:T=>{const R=a.find(A=>A.name===T);m({...o,baseEntity:{connectionId:(R==null?void 0:R.connectionId)||"",connectionType:(R==null?void 0:R.connectionType)||"none",type:(R==null?void 0:R.type)||"table",name:T,database:R==null?void 0:R.database,schema:R==null?void 0:R.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.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 (",o.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:h,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),o.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:o.joins.map(T=>{const R=a.find(y=>y.name===T.source.name),A=a.find(y=>y.name===T.target.name),I=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,R&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",R.name," → ",A.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:()=>f(T.id),disabled:T.sequence===o.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(T.id),children:I?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:()=>u(T.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),I&&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:y=>{const E=a.find(F=>F.name===y);p(T.id,{source:{connectionId:(E==null?void 0:E.connectionId)||"",connectionType:(E==null?void 0:E.connectionType)||"none",type:(E==null?void 0:E.type)||"table",name:y,database:E==null?void 0:E.database,schema:E==null?void 0:E.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:S(T.id).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name]})},y.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:T.joinType,onValueChange:y=>p(T.id,{joinType:y}),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:y=>{const E=a.find(F=>F.name===y);p(T.id,{target:{connectionId:(E==null?void 0:E.connectionId)||"",connectionType:(E==null?void 0:E.connectionType)||"none",type:(E==null?void 0:E.type)||"table",name:y,database:E==null?void 0:E.database,schema:E==null?void 0:E.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?j(T.source.name).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,y.name===T.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},y.name)):[]})]})]})]}),T.source.name&&T.target.name&&R&&A&&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:()=>v(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((y,E)=>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 ",E+1]}),E>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:y.operator,onValueChange:F=>C(T.id,E,F),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:()=>O(T.id,E),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[y.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:y.keys.map((F,z)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[z>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:y.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.source.name,onValueChange:_=>N(T.id,E,z,"sourceColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:L(T.source.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:F.operator,onValueChange:_=>N(T.id,E,z,"operator",_),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:F.target.name,onValueChange:_=>N(T.id,E,z,"targetColumnName",_),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:L(T.target.name).map(_=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:_.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:_.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:_.dataType})]})},_.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>b(T.id,E,z),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||z))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>D(T.id,E),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},y.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:()=>n(o),disabled:!w(),children:"Save"})]})]})}function Ys({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:l,onRemove:i,onSave:c,onCancel:o}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,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(ol,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:o,onRemove:i})]}),t]})}function il({joins:t,baseEntityId:a,availableDataSources:n,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,o)=>c.sequence-o.sequence),i=n.find(c=>c.name===a);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:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const o=n.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:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.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,i)=>l.sequence-i.sequence).map((l,i)=>{const c=n.find(d=>d.name===l.source.name),o=n.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:i+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," → ",o==null?void 0:o.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,m)=>d+m.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,m)=>d+m.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 cl(){var h,u;const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>p.actions.updateCardConfig),n=((h=t==null?void 0:t.config)==null?void 0:h.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=M.useState(!1),i=((u=t==null?void 0:t.dataSource)==null?void 0:u.selectedEntities)||[],c=p=>{a(t.id,{...t==null?void 0:t.config,joinPlan:p}),l(!1)},o=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},m=()=>{const p=[...n.joins].sort((x,S)=>x.sequence-S.sequence),g=n.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let f=`SELECT *
418
+ FROM ${g.name}`;return p.forEach(x=>{const S=i.find(C=>C.name===x.target.name);if(!S)return;const j=x.joinKeyGroups.filter(C=>C.keys&&C.keys.length>0).map(C=>{const O=C.keys.filter(D=>{var N,b,k,w;return((N=D.source)==null?void 0:N.name)&&((b=D.target)==null?void 0:b.name)&&((k=D.source)==null?void 0:k.entityName)&&((w=D.target)==null?void 0:w.entityName)}).map(D=>`${D.source.entityName}.${D.source.name} ${D.operator} ${D.target.entityName}.${D.target.name}`);return O.length>1?`(${O.join(` ${C.operator} `)})`:O[0]}).filter(Boolean),v=j.length>1?j.join(" OR "):j[0]||"condition_here";f+=`
419
419
  ${x.joinType} JOIN ${S.name}
420
- ON ${v}`}),f};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:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{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":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(il,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:o,generateSQLPreview:m})})]})}),e.jsx(Ys,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(Ys,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function dl({entity:t,title:a,maxDetails:n=10}){const l=s.getEntityDetails(t).slice(0,n),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:a||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 ul({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((a,n)=>{const r=s.getEntityDetails(a),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(a)}),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-${a.type}-${a.name}-${n}`)})})]})})}function ml({isVisible:t,onToggleVisibility:a}){const[n,r]=M.useState(!1),[l,o]=M.useState(!0),c=s.useEditorStore(h=>h.card.dataSource),{updateDataSource:i}=s.useEditorActions(),d={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},m={...d,...c,selectedEntities:(c==null?void 0:c.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden border-r bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!l}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",onClick:()=>o(!l),children:[l?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"}),e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${l?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[m.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[m.selectedEntities.slice(0,3).map((h,u)=>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:p=>{p.stopPropagation();const j=m.selectedEntities.filter(f=>!(f.name===h.name&&f.type===h.type));i({...d,...c,selectedEntities:j})},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(dl,{entity:h})]},`${h.type}-${h.name}-${u}`)),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(ul,{entities:m.selectedEntities.slice(3)})]})]})}),e.jsx(cl,{})]})]}),e.jsx(rl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(c==null?void 0:c.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:m,fallbackDataSource:d})]})}const ze=[{id:"table",icon:Je,label:"Table"},{id:"bar",icon:$e,label:"Bar Chart"},{id:"line",icon:Ge,label:"Line Chart"},{id:"area",icon:et,label:"Area Chart"},{id:"stackedBar",icon:ms,label:"Stacked Bar Chart"},{id:"combo",icon:Cn,label:"Combo Chart"},{id:"stackedLine",icon:ks,label:"Stacked Line Chart"},{id:"scatter",icon:xs,label:"Scatter Chart"},{id:"bubble",icon:ws,label:"Bubble Chart"},{id:"pie",icon:He,label:"Pie Chart"},{id:"doughnut",icon:ps,label:"Doughnut Chart"},{id:"funnel",icon:Ts,label:"Funnel Chart"},{id:"radar",icon:js,label:"Radar Chart"},{id:"polarArea",icon:Ss,label:"Polar Area Chart"},{id:"tornado",icon:ys,label:"Tornado Chart"},{id:"range",icon:hs,label:"Range Chart"},{id:"kpi",icon:Ds,label:"KPI"},{id:"text",icon:Zs,label:"Text"},{id:"map",icon:gs,label:"Map"}],Ms=t=>{const a=t.toLowerCase();for(const n of ze)if(n.id==="doughnut"){if(a.includes("doughnut")||a.includes("donut")){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}}else if(a.includes(n.id.toLowerCase())){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}return null},hl="chart-selector-standard-first";function xl(){const[t,a]=s.useLocalStorageState(hl,!0);return{standardFirst:t,updatePreference:a}}const Ks=({pluginVisual:t,index:a,onSelect:n})=>{const r=Ye(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=Ms(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,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}-${a}`)},Qs=["default","standardPlugin","customPlugin"];function pl({selectedChart:t,onChartChange:a}){var D;const[n,r]=M.useState([]),[l,o]=M.useState(!1),{data:c}=Cs();xl();const d=((D=s.useEditorStore(b=>b.card).customCardPreferences)==null?void 0:D.url)||"";s.useRemoteChartStore(d);const{setCardType:m,setCardPreferences:h,setIsDevMode:u}=s.useEditorStore(b=>b.actions),{setCardCustomCfg:p,setCustomCardPreferences:j,setQueryConfig:f}=s.useEditorActions(),[x,S]=s.useLocalStorageState("chart-section-active",null),g=M.useMemo(()=>x?[x,...Qs.filter(b=>b!==x)]:Qs,[x]);M.useEffect(()=>{(async()=>{if(c){const w=(await Promise.allSettled(c.plugins.map(async L=>{try{return(await s.loadManifest(L.value)).visuals.map(R=>({name:R.name,icon:R.icon,url:L.value,pluginName:L.label,pluginType:L.type,chartType:R.chartType,componentType:R.componentType}))}catch(T){return console.error(`Failed to load manifest for plugin ${L.label}`,T),[]}}))).filter(L=>L.status==="fulfilled").flatMap(L=>L.value);r(w)}})()},[c]);function v(b){p(null),h({}),m(b),["custom","text","map"].includes(b)&&(u(!0),f(void 0)),a(b),o(!1)}function N(b){p(null),h({}),m("custom"),j({type:"component",visualType:"single",url:b.url,componentName:b.name,icon:b.icon,pluginChartType:b.chartType}),f(void 0),a("custom"),o(!1)}const O=()=>{var k;if(t==="custom"){const w=s.useEditorStore.getState().card;return((k=w==null?void 0:w.customCardPreferences)==null?void 0:k.componentName)||"Custom Visual"}const b=ze.find(w=>w.id===t);return(b==null?void 0:b.label)||"Select chart type"},C=()=>{var k,w;if(t==="custom"){const L=s.useEditorStore.getState().card,T=(k=L==null?void 0:L.customCardPreferences)==null?void 0:k.icon,R=(w=L==null?void 0:L.customCardPreferences)==null?void 0:w.componentName;if(T&&R)return e.jsx(fl,{icon:T,componentName:R});if(R){const A=Ms(R);if(A)return A}return e.jsx(Ae,{className:"h-4 w-4"})}const b=ze.find(L=>L.id===t);if(b){const L=b.icon;return e.jsx(L,{className:"h-4 w-4"})}return e.jsx(Ae,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:l,onOpenChange:o,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[C(),e.jsx("span",{children:O()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[335px] 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."}),g.map(b=>{if(b==="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:x==="default",onCheckedChange:k=>S(k?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:ze.map(k=>{const w=k.icon;return e.jsx(s.CommandItem,{value:`${k.label} ${k.id} chart graph visualization`,onSelect:()=>v(k.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{className:"h-4 w-4"}),e.jsx("span",{children:k.label})]})},k.id)})},"default");if(b==="standardPlugin"){const k=n.filter(w=>w.pluginType==="standard");return k.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:x==="standardPlugin",onCheckedChange:w=>S(w?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.filter(w=>w.componentType==="chart").map((w,L)=>e.jsx(Ks,{pluginVisual:w,index:L,onSelect:()=>N(w)},`${w.url}-${w.name}-${L}`))},"standardPlugin"):null}if(b==="customPlugin"){const k=n.filter(w=>w.pluginType==="custom");return k.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:x==="customPlugin",onCheckedChange:w=>S(w?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.map((w,L)=>e.jsx(Ks,{pluginVisual:w,index:L,onSelect:()=>N(w)},`${w.url}-${w.name}-${L}`))},"customPlugin"):null}return null})]})]})})]})})}const fl=({icon:t,componentName:a})=>{const n=Ye(),r=Ms(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Ae,{className:"h-4 w-4"})},Qt=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-blue-500 text-xs text-white",children:"T"}):a==="number"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-green-500 text-xs text-white",children:"#"}):a==="date"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-purple-500 text-xs text-white",children:"D"}):a==="boolean"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-orange-500 text-xs text-white",children:"B"}):e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-gray-500 text-xs text-white",children:"?"})};function gl({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=M.useState(t),[l,o]=M.useState(!1),c=(d=s.useEditorStore(m=>{var h;return(h=m.card.config)==null?void 0:h.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?n:t,onChange:m=>{r(m.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&l&&n!==t?(a(n),o(!1)):m.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&n!==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:()=>{a(n),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 jl({valueAliases:t,onValueAliasesChange:a}){const[n,r]=M.useState(null),[l,o]=M.useState(""),[c,i]=M.useState(""),d=()=>{a({...t,"":""})},m=u=>{const p={...t};delete p[u],a(p)},h=u=>{const p={...t};delete p[u],p[l]=c,a(p),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(([u,p],j)=>e.jsx("div",{className:"flex items-center gap-2",children:n===u?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:f=>o(f.target.value),className:"h-8 w-24 text-xs",onPointerDown:f=>f.stopPropagation(),onKeyDown:f=>{f.key==="Enter"?h(u):f.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:f=>i(f.target.value),className:"h-8 w-24 text-xs",onPointerDown:f=>f.stopPropagation(),onKeyDown:f=>{f.key==="Enter"?h(u):f.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:()=>h(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 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:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(u),o(u),i(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(u),o(u),i(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(u),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},u+j)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Xs({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[o,c]=M.useState(t??""),[i,d]=M.useState(!1);M.useEffect(()=>{c(t??"")},[t]);const m=()=>{a(o),d(!1)},h=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:i?o:t??"",onChange:u=>{c(u.target.value),d(!0)},onFocus:()=>d(!0),onClick:u=>u.stopPropagation(),className:"h-8 text-xs",onPointerDown:u=>u.stopPropagation(),onKeyDown:u=>{u.stopPropagation(),u.key==="Enter"&&i&&o!==t?m():u.key==="Escape"&&h()},"aria-label":n||"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:m,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:h,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function yl({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Rs;const{attributes:i,listeners:d,setNodeRef:m,transform:h,transition:u,isDragging:p}=s.useSortable({id:t.id}),j=s.useEditorStore(X=>X.card),{updateLabel:f,handleAggregationChange:x,handleDateFormatChange:S,handleGranularityChange:g,handleAliasTemplateChange:v,handleValueAliasesChange:N,removeField:O,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:D,handleKpiTrendlineWindowChange:b,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:w}=As(j),[L,T]=M.useState(!1),[R,A]=M.useState(t.dateFormat||"YYYY-MM-DD"),[I,y]=M.useState(t.customFormat||""),[E,F]=M.useState(!!t.customFormat),[z,_]=M.useState(t.granularity||"day"),[P,Q]=M.useState(t.aliasTemplate||""),[Y,V]=M.useState(t.valueAliases||{}),q=X=>{X==="custom"?F(!0):(F(!1),A(X),a==="groupBy"&&S(n,X,""))},$=X=>{y(X),a==="groupBy"&&S(n,"custom",X)},U=X=>{_(X),a==="groupBy"&&g(n,X)},H=X=>{Q(X),a==="metrics"&&v(n,X)},W=X=>{V(X),a==="metrics"&&N(n,X)},G=X=>{f(a,n,X)},Z=()=>{O(a,n)},se={transform:s.CSS.Transform.toString(h),transition:u},ne=s.getDataType(t.dataType),ee=ne==="date",ae=c==="kpi",J=[{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..."}],B=!ae&&a!=="pivotBy",K=ae&&ee&&a==="groupBy",re=!ae&&ee&&a==="groupBy",he=ae&&ee&&a==="groupBy",je=ae&&a==="metrics"&&((Rs=j.config)==null?void 0:Rs.comparisonType)==="target",te=a==="metrics",le=()=>e.jsx("div",{onPointerDown:X=>{X.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),oe=()=>B?e.jsx(Xs,{value:t.label??"",onSave:G,placeholder:"Display label...",type:"text"}):null,Os=()=>K?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:z,onValueChange:U,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"}),e.jsx(s.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(s.SelectItem,{value:"year",children:"Year"})]})]})]}):null,en=()=>re?e.jsxs(e.Fragment,{children:[Os(),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:E?"custom":R,onValueChange:q,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:J.map(X=>e.jsx(s.SelectItem,{value:X.value,children:X.label},X.value))})]}),E&&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:I,onChange:X=>{X.stopPropagation(),$(X.target.value)},onClick:X=>X.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,sn=()=>{var X,xe,Te,Bs,Fs;return he?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:((X=j.config)==null?void 0:X.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:((xe=j.config)==null?void 0:xe.showTrendline)||!1,onCheckedChange:D})]})}),((Te=j.config)==null?void 0:Te.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:((Bs=j.config)==null?void 0:Bs.trendlineWindow)||30,onChange:an=>{const rn=parseInt(an.target.value)||30;b(rn)},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:((Fs=j.config)==null?void 0:Fs.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},tn=()=>{var X,xe;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(Xs,{value:((X=j.config)==null?void 0:X.targetValue)!==void 0&&((xe=j.config)==null?void 0:xe.targetValue)!==null?String(j.config.targetValue):"",onSave:Te=>{!isNaN(Number(Te))&&Te!==null?w(Number(Te)):w(0)},placeholder:"Enter target value...",type:"text"})]}):null},nn=()=>te?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:X=>{x(n,X)},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,{value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(Ht,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(gl,{aliasTemplate:P,onAliasTemplateChange:H}),e.jsx(jl,{valueAliases:Y,onValueAliasesChange:W})]})]}):null;return e.jsxs("div",{ref:m,style:se,...i,...d,className:`group mx-auto flex w-full max-w-[300px] flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.GripVertical,{className:"h-3 w-3"}),e.jsx(Qt,{dataType:ne}),e.jsx(Es,{className:"max-w-[180px] flex-1 text-sm",children:t.label||t.name}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),T(!L)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${L?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const xe=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",xe),l(xe)},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 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),L&&e.jsxs("div",{className:"space-y-3",children:[le(),oe(),Os(),en(),sn(),tn(),nn()]})]})}function vl({concept:t}){const a=()=>{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$1,{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:a()})]})})}function Fe({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),m=s.useEditorStore(f=>f.card),h=s.useEditorStore(f=>f.card.type),u=a.length>0,p=(f,x)=>{var g;!((g=m.config)!=null&&g.sortByColumns)||m.config.sortByColumns.findIndex(v=>v.id===f)===-1||d(m.id,f,{direction:x})};if(t==="sortBy"&&l===!1)return null;const j=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4",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:n}),j&&e.jsx(vl,{concept:t})]}),e.jsx("div",{ref:i,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":"border-muted-foreground/20 bg-muted/50"}`,children:a.length===0?e.jsxs("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),r]}):e.jsx(s.SortableContext,{items:a.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((f,x)=>{const g=f.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(yl,{field:f,zone:t,index:x,sortDirection:g,onSortDirectionChange:v=>p(f.id,v),hasPivotColumns:o,cardType:h})})},f.id)})})})})]})}function bl({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const l=s.useEditorStore(u=>u.card),o=l==null?void 0:l.type,c=t.length>0||n.length>0,i=o!=="kpi",d=o!=="kpi"&&c,m=()=>o==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},h=()=>o==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Fe,{zone:"groupBy",fields:t,label:m().label,placeholder:m().placeholder}),i&&e.jsx(Fe,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Fe,{zone:"metrics",fields:n,label:h().label,placeholder:h().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(Fe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function Nl({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(u=>u.showAIDialog),i=n.length>0||r.length>0||l.length>0,{setShowAIDialog:d}=s.useEditorActions(),m=s.useEditorStore(u=>u.card),{data:h}=s.useDashboardCardQuery(m);return e.jsxs("div",{className:"flex w-96 flex-col border-r bg-background",children:[e.jsxs("div",{className:"space-y-4 border-b px-6 py-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(pl,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||h}),children:e.jsx(s.EditorClearButton,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(ta,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(bl,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Cl({initialFilters:t,availableFields:a}={}){const[n,r]=M.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=a||l||[],d={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},m=C=>{const D=b=>{if(b.id===C){const k=i[0]||d;return{...b,conditions:[...b.conditions,{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}]}}return{...b,groups:b.groups.map(D)}};r(D(n))},h=C=>{const D=b=>{if(b.id===C){const k=i[0]||d;return{...b,groups:[...b.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}],groups:[]}]}}return{...b,groups:b.groups.map(D)}};r(D(n))},u=(C,D)=>{const b=k=>k.id===C?{...k,conditions:k.conditions.filter(w=>w.id!==D)}:{...k,groups:k.groups.map(b)};r(b(n))},p=(C,D)=>{const b=k=>k.id===C?{...k,groups:k.groups.filter(w=>w.id!==D)}:{...k,groups:k.groups.map(b)};r(b(n))},j=(C,D,b,k)=>{if(b==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const w=L=>L.id===C?{...L,conditions:L.conditions.map(T=>T.id===D?{...T,[b]:k}:T)}:{...L,groups:L.groups.map(w)};r(w(n))},f=(C,D,b)=>{const k=w=>w.id===C?{...w,conditions:w.conditions.map(L=>L.id===D?{...L,...b}:L)}:{...w,groups:w.groups.map(k)};r(k(n))},x=(C,D)=>{const b=k=>k.id===C?{...k,logicalOperator:D}:{...k,groups:k.groups.map(b)};r(b(n))},S=(C,D)=>{const b=k=>k.id===C?{...k,negate:D}:{...k,groups:k.groups.map(b)};r(b(n))},g=(C,D,b)=>{const k=w=>w.id===C?{...w,conditions:s.arrayMove(w.conditions,D,b)}:{...w,groups:w.groups.map(k)};r(k(n))},v=(C,D,b)=>{const k=w=>w.id===C?{...w,groups:s.arrayMove(w.groups,D,b)}:{...w,groups:w.groups.map(k)};r(k(n))},N=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const D=k=>{let w="";typeof k.field=="object"?w=k.field.entityName?`${k.field.entityName}.${k.field.name}`:k.field.name:w=String(k.field);const L=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")(typeof T=="string"||T instanceof Date)&&(T=`DATE('${T}')`);else if(["in","not in"].includes(k.operator)){let R=[];Array.isArray(T)?R=T.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof T=="string"?R=T.split(",").map(A=>{const I=A.trim();return k.field.dataType==="string"?`'${I}'`:I}):typeof T=="number"&&(R=[String(T)]),T=`(${R.join(", ")})`}switch(L){case"contains":return typeof T=="string"?`${w} LIKE '%${T.replace(/'/g,"")}'`:`${w} LIKE '%${String(T)}'`;case"startsWith":return typeof T=="string"?`${w} LIKE '${T.replace(/'/g,"")}%'`:`${w} LIKE '${String(T)}%'`;case"endsWith":return typeof T=="string"?`${w} LIKE '%${T.replace(/'/g,"")}'`:`${w} LIKE '%${String(T)}'`;default:return`${w} ${L} ${T}`}},b=k=>{const w=k.conditions.map(D),L=k.groups.map(I=>b(I)),T=[...w,...L].filter(Boolean);if(T.length===0)return"";const R=T.join(` ${k.logicalOperator} `),A=T.length>1?`(${R})`:R;return k.negate?`NOT ${A}`:A};return b(C)},O=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:m,addGroup:h,removeCondition:u,removeGroup:p,updateCondition:j,updateConditionFields:f,updateGroupOperator:x,updateGroupNegate:S,reorderConditions:g,reorderGroups:v,generateSQLPreview:N,hasAnyFilters:O}}function Sl({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const wl=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(Ln,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Tl=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function kl({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[o,c]=M.useState(!1),i=M.useMemo(()=>{const d={};return n.forEach(m=>{const h=Tl(m);d[h]||(d[h]={}),d[h][m.entityId]||(d[h][m.entityId]=[]),d[h][m.entityId].push(m)}),d},[n]);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(Sl,{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,m])=>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(m).map(([h,u])=>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:[wl(u[0].entityType),e.jsx("span",{children:u[0].entityName})]}),u.map((p,j)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{a(p),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)===p.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:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+j))]},`${d}-${h}`))},d))})]})})]})}function Ls(t){var f;const a=s.useEditorStore(x=>x.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(x=>x.card.config),l=r==null?void 0:r.joinPlan,o={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...o,role:"sortby",direction:"asc"},d={joinPlan:l,groupByColumns:[o],metricColumns:[c],sortByColumns:[i]},m=((f=a.dataSource)==null?void 0:f.connectionId)||a.connectionId,{data:h,isPending:u,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:m,cardConfig:d,cardDataSource:a.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:u,error:p}}function Dl({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[o,c]=ye.useState(!1),{filterValues:i}=Ls(t),d=h=>{n(a.filter(u=>u!==h))},m=h=>{a.includes(h)?n(a.filter(u=>u!==h)):n([...a,h])};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:a.length>0?a.map(h=>{const u=i.find(p=>p.value===h);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[u==null?void 0:u.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:p=>{p.key==="Enter"&&d(h)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),d(h)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},h)}):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((h,u)=>e.jsxs(s.CommandItem,{onSelect:()=>m(h.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(h.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.count})]})]},h.value+u))})]})]})})]})})}const Xt=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=Xt(n)}),a};function El({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=Ls(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:o.map((d,m)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+m))})]})}const Il=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Al=["=","!=","contains","startsWith","endsWith","in","not in"],Ml=["=","!=",">",">=","<","<=","in","not in"],Ll=["=","!="],Ol=["=","!=",">",">=","<","<=","in","not in"];function Rl(t){switch(t){case"string":return Al;case"number":return Ml;case"boolean":return Ll;case"date":return Ol;default:return Il}}function Zt({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:m,listeners:h,setNodeRef:u,transform:p,transition:j,isDragging:f}=s.useSortable({id:t.id}),{isPending:x,error:S}=Ls(t.field),g={transform:s.CSS.Transform.toString(p),transition:j};return e.jsxs("div",{ref:u,style:g,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${f?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...h,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:v=>c(n,v),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"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(kl,{value:t.field,onValueChange:v=>{d(n,t.id,{field:v,value:""})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:v=>{v==="in"||v==="not in"?d(n,t.id,{operator:v,value:[]}):d(n,t.id,{operator:v,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Rl(s.getDataType(t.field.dataType)).map(v=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:v,children:v},v))})]}),s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?x?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..."]}):S?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Dl,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(v=>typeof v=="string")?t.value:[],onChange:v=>d(n,t.id,{value:v}),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:v=>d(n,t.id,{value:v.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(El,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:v=>d(n,t.id,{value:v}),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:v=>d(n,t.id,{value:v==="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"})]})]}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:v=>l(n,t.id,"value",v.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(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Bl({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:m,onReorderGroups:h,onAddCondition:u,onAddGroup:p,availableFields:j,renderFilterGroup:f,updateConditionFields:x}){const{attributes:S,listeners:g,setNodeRef:v,transform:N,transition:O,isDragging:C}=s.useSortable({id:t.id}),D={transform:s.CSS.Transform.toString(N),transition:O},b=w=>{const{active:L,over:T}=w;if(T&&L.id!==T.id){const R=t.conditions.findIndex(I=>I.id===L.id),A=t.conditions.findIndex(I=>I.id===T.id);R!==-1&&A!==-1&&m(t.id,R,A)}},k=w=>{const{active:L,over:T}=w;if(T&&L.id!==T.id&&n){const R=t.groups.findIndex(I=>I.id===L.id),A=t.groups.findIndex(I=>I.id===T.id);R!==-1&&A!==-1&&h(n,R,A)}};return e.jsxs("div",{ref:v,style:D,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${C?"z-50 opacity-50":""}`,children:[a>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",{...S,...g,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:w=>r(t.id,w),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:()=>n&&o(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>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:b,children:e.jsx(s.SortableContext,{items:t.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((w,L)=>e.jsx(Zt,{condition:w,index:L,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:j,updateConditionFields:x},w.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(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(w=>f(w,a+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:()=>u(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:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Fl({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:m,removeCondition:h,removeGroup:u,updateCondition:p,updateConditionFields:j,updateGroupOperator:f,updateGroupNegate:x,reorderConditions:S,reorderGroups:g,generateSQLPreview:v,hasAnyFilters:N,setCurrentFilters:O}=Cl({initialFilters:t,availableFields:a}),C=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[D,b]=M.useState(!1),k=(T,R,A)=>{const I=y=>y.id===T?{...y,conditions:y.conditions.map(E=>E.id===R?{...E,field:A,dataType:A.dataType}:E)}:{...y,groups:y.groups.map(I)};O(I(o))},w=(T,R=0,A)=>R===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:I=>{const{active:y,over:E}=I;if(E&&y.id!==E.id){const F=T.conditions.findIndex(_=>_.id===y.id),z=T.conditions.findIndex(_=>_.id===E.id);F!==-1&&z!==-1&&S(T.id,F,z)}},children:e.jsx(s.SortableContext,{items:T.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:T.conditions.map((I,y)=>e.jsx(Zt,{condition:I,index:y,groupId:T.id,groupLogicalOperator:T.logicalOperator,onUpdateCondition:p,onUpdateField:k,onRemoveCondition:h,onUpdateGroupOperator:f,availableFields:c,updateConditionFields:j},I.id))})}),e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:E}=I;if(E&&y.id!==E.id){const F=T.groups.findIndex(_=>_.id===y.id),z=T.groups.findIndex(_=>_.id===E.id);F!==-1&&z!==-1&&g(T.id,F,z)}},children:e.jsx(s.SortableContext,{items:T.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:T.groups.map(I=>w(I,R+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"]}),D&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(T.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},T.id):e.jsx(Bl,{group:T,depth:R,parentGroupId:A,onUpdateGroupOperator:f,onUpdateGroupNegate:x,onRemoveGroup:u,onUpdateCondition:p,onUpdateField:k,onRemoveCondition:h,onReorderConditions:S,onReorderGroups:g,onAddCondition:d,onAddGroup:m,availableFields:c,renderFilterGroup:w,updateConditionFields:j},T.id),L=Xt(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..."})]}):w(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.Checkbox,{id:"advanced-mode",checked:D,onCheckedChange:T=>b(!!T)}),e.jsx("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)"})]})}),N&&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:v(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),L>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(N?o:null),children:"Apply Filters"})]})]})}function zl({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=m=>{n(t,m),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:m=>{m.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(Fl,{filters:a,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function Pl({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var j;const[l,o]=M.useState(null),c=s.useEditorStore(f=>f.card),i=(j=c==null?void 0:c.config)==null?void 0:j.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],m=M.useCallback(f=>f.startsWith("card-")?null:f.startsWith("source-")||a.find(x=>x.id===f)?"source":n("groupBy").find(x=>x.id===f)?"groupBy":n("metrics").find(x=>x.id===f)?"metrics":n("pivotBy").find(x=>x.id===f)?"pivotBy":n("sortBy").find(x=>x.id===f)?"sortBy":null,[a,n]),h=M.useCallback(f=>{o(f.active.id)},[]),u=M.useCallback(f=>{const{active:x,over:S}=f;if(!S||!t){o(null);return}const g=x.id,v=S.id,N=m(g),O=m(v)||v;if(N==="source"&&O==="sortBy"){o(null);return}if(N==="source"&&O!=="source"&&O!=="sortBy"){const C=[...a].find(w=>w.id===g);if(!C){o(null);return}const D=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(D.length>0){const w=D[0].qualifiedEntityName;if(!w){o(null);return}if(w!==C.qualifiedEntityName&&C.qualifiedEntityName)if(i){if(!Kt(w,C.qualifiedEntityName,i)){ds(),o(null);return}}else{ds(),o(null);return}}const b=n(O);if(us(C,b)){o(null);return}const k=cs(C,O);o(null),r(O,[...b,k]);return}if(N&&O&&N!=="source"&&O!=="source"&&N!==O){const C=n(N),D=n(O),b=C.find(L=>L.id===g);if(!b){o(null);return}const k=cs(b,O);if(o(null),O==="sortBy"){if(N==="pivotBy"){o(null);return}us(b,D)||r(O,[...D,k]);return}const w=C.filter(L=>L.id!==g);r(N,w),r(O,[...D,k]);return}if(N&&O&&N===O&&N!=="source"){const C=n(N),D=C.findIndex(k=>k.id===g),b=C.findIndex(k=>k.id===v);if(D!==b){const k=s.arrayMove(C,D,b);r(N,k)}}o(null)},[t,a,n,r,m,i]),p=l?d.find(f=>f.id===l):null;return{activeId:l,activeField:p,handleDragStart:h,handleDragEnd:u}}function _l({activeView:t,onViewChange:a}){const n=s.useEditorStore(l=>l.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:l=>a(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-2 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"}),n.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const Vl=[{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 Ul(){var d,m;const t=s.useEditorStore(h=>h.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=M.useState(!1),[l,o]=M.useState(""),c=h=>{if(h==="custom"){r(!0);return}r(!1),a(t.id,parseInt(h))},i=h=>{const u=h.target.value;o(u),u&&!isNaN(parseInt(u))&&a(t.id,parseInt(u))};return e.jsx("div",{className:"flex items-center gap-2",children:n?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:((m=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:m.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:Vl.map(h=>e.jsx(s.SelectItem,{value:h.value,children:h.label},h.value))})]})})}function ql({isOpen:t,onClose:a}){const n=jt(a,{enabled:t}),r=s.useEditorStore(h=>{var u;return((u=h.card.customCardPreferences)==null?void 0:u.url)||""}),l=s.useEditorStore(h=>h.card),o=s.useEditorStore(h=>{var u;return((u=h.card.customCardPreferences)==null?void 0:u.pluginChartType)||""}),c=s.useEditorStore(h=>{var u;return((u=h.card.customCardPreferences)==null?void 0:u.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),m=M.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,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:a,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:m&&e.jsx(M.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(m,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function $l({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:m,columns:h,columnsLoading:u,columnsError:p}){var R;const j=s.useEditorStore(A=>A.card),f=s.useDashboardStore(A=>A.filterValues),{updateCardConfig:x}=s.useEditorActions(),S=s.useEditorStore(A=>A.showAIDialog),[g,v]=M.useState(!1),N=s.useEditorStore(A=>{var I;return((I=A.card.customCardPreferences)==null?void 0:I.url)&&A.card.type==="custom"}),{data:O,errorMessage:C,isPending:D,isLoading:b,isFetching:k}=s.useDashboardCardQuery(m);function w(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",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(j.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(f||{},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(m.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",h.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:u?"Loading...":p?"Error loading columns":JSON.stringify(h.slice(0,5),null,2)})]})]})})}const L=A=>{if(!j.config)return;if(!A.length){x(j.id,{...j.config,sortByColumns:[]});return}const I=j.config,y=A.map(({id:E,desc:F})=>{var Q,Y;const z=(Q=I.metricColumns)==null?void 0:Q.find(V=>V.label===E),_=(Y=I.groupByColumns)==null?void 0:Y.find(V=>V.label===E),P=z||_;return P?{id:Wt("sortBy",P),name:P.name,dataType:P.dataType,label:P.label,qualifiedEntityName:P.qualifiedEntityName,entityId:P.entityId,entityName:P.entityName,entityType:P.entityType,role:"sortby",direction:F?"desc":"asc"}:null}).filter(E=>E!==null);x(j.id,{...I,sortByColumns:y})},T=M.useMemo(()=>{var A,I;return(I=(A=j.config)==null?void 0:A.sortByColumns)==null?void 0:I.map(y=>({id:y.label,desc:y.direction==="desc"}))},[(R=j.config)==null?void 0:R.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(s.ExplorerHeader,{showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&w(),e.jsx(s.Separator,{}),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"&&S&&e.jsx(zt,{variant:"outline"}),e.jsx(_l,{activeView:t,onViewChange:a}),i&&e.jsxs(s.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:i,children:[e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),d>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:d})]}),e.jsx("div",{className:"ml-2",children:e.jsx(Ul,{})}),S&&e.jsx(s.EditorClearButton,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(Pt,{})})]}),!g&&N&&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(Zn,{className:"size-4"})}),e.jsxs("div",{className:"flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:b||k?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(_t,{})}),t==="table"&&(O==null?void 0:O.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(b||k)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(s.TableVisual,{card:m,data:O==null?void 0:O.records,onSortChange:L,sortState:T})]}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md border bg-background p-4",children:[(O==null?void 0:O.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(At,{sql:O==null?void 0:O.sql,error:C})]})})]}),e.jsx(ql,{isOpen:g,onClose:()=>v(!1)})]})]})}function Gl({activeField:t}){const[a,n]=M.useState(!0);return M.useEffect(()=>{t&&n(!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 ${a?"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(Qt,{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 Hl=()=>{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 a=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},n=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",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Jl(){var V,q;const[t,a]=M.useState("chart"),[n,r]=M.useState(!1),[l,o]=M.useState(!1),[c,i]=M.useState(!0),d=s.useEditorStore($=>$.showAIDialog),m=s.useDashboardStore($=>$.isVisualEditing),{setCardType:h}=s.useEditorActions(),u=s.useEditorStore($=>$.card.type);M.useEffect(()=>Hl(),[]);const p=()=>{console.log("Accept clicked - would save/apply current configuration")},j=()=>{console.log("Clear clicked - would reset all configurations")},f=()=>{console.log("Advanced mode toggled")},x=()=>{o(!0)},S=$=>{h($)},g=s.useEditorStore($=>$.frame),v=s.useEditorStore($=>$.card);s.useEditorStore($=>$.activeTabCardId),s.useEditorStore($=>$.actions.getAvailableFields);const{addCard:N,removeCard:O,updateCard:C,setActiveCard:D,updateFilters:b}=s.useEditorActions(),{columns:k=[],isLoading:w,error:L}=s.useColumns(),T=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),R=v,{getFieldsForContainer:A,setFieldsForContainer:I}=As(R),{activeField:y,handleDragStart:E,handleDragEnd:F}=Pl({activeCardId:g.activeCardId,sourceFields:k,getFieldsForContainer:A,setFieldsForContainer:I}),z=($,U)=>{U&&b($,U)},_=$=>{var U;C($,{config:{...(U=g.cards.find(H=>H.id===$))==null?void 0:U.config,filters:void 0}})},P=k,Q=$=>{if(!$)return 0;let U=$.conditions.length;return $.groups.forEach(H=>{U+=Q(H)}),U},Y=Q(((V=R==null?void 0:R.config)==null?void 0:V.filters)||null);return e.jsxs(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragStart:E,onDragEnd:F,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(ml,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Nl,{selectedChart:u,onChartChange:S,groupByFields:A("groupBy"),pivotByFields:A("pivotBy"),metricsFields:A("metrics"),sortByFields:A("sortBy")}),e.jsx($l,{selectedChart:u,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:p,onClear:j,onAdvancedToggle:f,onFiltersClick:x,filterCount:Y,activeCard:R,dataSourceState:v.dataSource||s.EMPTY_DATA_SOURCE,columns:k,columnsLoading:w,columnsError:L,getFieldsForContainer:A,cards:g.cards,activeCardId:g.activeCardId,addCard:N,setActiveCard:D})]}),!c&&m&&e.jsx("div",{className:"fixed bottom-4 left-4 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"})})})]}),R&&e.jsx(zl,{cardId:R.id,filters:((q=R.config)==null?void 0:q.filters)||null,onFiltersChange:z,onClearFilters:_,availableFields:P,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Gl,{activeField:y||null})})]})}function Wl({authToken:t,onSave:a,onClose:n}){const r=M.useRef(null),l=s.useEditorStore(v=>v.showAIDialog),o=s.useEditorStore(v=>v.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:m}=s.useEditorActions(),{handleDragOver:h,handleDragEnd:u,handleDragStart:p,handleDragCancel:j,sensors:f}=za();M.useEffect(()=>{a&&d(a),n&&m(n)},[a,d,n,m]),M.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),M.useEffect(()=>{var v,N;l?((v=r.current)==null||v.resize(40),i(!0)):(i(!1),(N=r.current)==null||N.resize(0))},[l,i]);function x(v){v<1?i(!1):l||i(!0)}function S(){return e.jsxs(e.Fragment,{children:[e.jsx(Et,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Xr,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Ws,{})})]})]})}function g(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Jl,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Ws,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:f,onDragStart:p,onDragEnd:u,onDragOver:h,onDragCancel:j,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:S()})}):g()})}function Yl(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),a(!1))}function o(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Wl,{onSave:l,onClose:o})})}function Kl(){const t=s.useEditorStore(o=>o.selectedDatabaseName),a=s.useEditorStore(o=>o.selectedTableName),n=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=$t();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=n==null?void 0:n.find(i=>i.column===s.fmt(o.column_name)&&i.table===a&&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(bs,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function Ql(){s.useDashboardStore(a=>a.showFilters);const t=s.useDashboardStore(a=>a.actions.setShowFilters);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:e.jsx(Et,{type:"filter",ColumnsComponent:()=>e.jsx(Kl,{})})})]})}function Xl(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.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)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.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 Zl(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(Xl,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Ql,{})})]})}function eo(){const t=s.useDashboardStore(l=>l.dashboard),a=s.useDashboardStore(l=>l.actions.setDashboard),n=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),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),a(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 so({showControls:t=!1,showFooter:a=!0,...n}){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsxs(s.UXProvider,{children:[e.jsx(eo,{}),e.jsxs("main",{className:"flex h-full flex-col",children:[t&&e.jsx(La,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(Yl,{}),e.jsx(Zl,{})]})]})]})]})})}exports.DashboardPlus=so;exports.ResourceManagementPanel=kt;exports.ScheduleDashboard=mt;exports.SelectComponent=ke;exports.cleanCard=ct;exports.downloadPdf=ut;exports.getDashbaordStateWithoutData=vs;
420
+ ON ${v}`}),f};return i.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:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{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":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(il,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:i,generateSQLPreview:m})})]})}),e.jsx(Ys,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:i,onSave:c,onCancel:d,onRemove:o,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(Ys,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:i,onSave:c,onCancel:d,onRemove:o,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function dl({entity:t,title:a,maxDetails:n=10}){const l=s.getEntityDetails(t).slice(0,n),i=l.find(o=>o.label==="Description"),c=l.filter(o=>o.label==="Description"?!1:!["Connection","Database","Schema"].includes(o.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a||s.getDisplayName(t)}),i&&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:i.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((o,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[o.label,":"]}),e.jsx("span",{className:"font-mono",children:o.value})]},d))})]})})}function ul({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((a,n)=>{const r=s.getEntityDetails(a),l=r.find(c=>c.label==="Description"),i=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(a)}),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})]}),i.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:i.map((c,o)=>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})]},o))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function ml({isVisible:t,onToggleVisibility:a}){const[n,r]=M.useState(!1),[l,i]=M.useState(!0),c=s.useEditorStore(h=>h.card.dataSource),{updateDataSource:o}=s.useEditorActions(),d={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},m={...d,...c,selectedEntities:(c==null?void 0:c.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden border-r bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!l}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",onClick:()=>i(!l),children:[l?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"}),e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${l?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[m.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[m.selectedEntities.slice(0,3).map((h,u)=>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:p=>{p.stopPropagation();const g=m.selectedEntities.filter(f=>!(f.name===h.name&&f.type===h.type));o({...d,...c,selectedEntities:g})},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(dl,{entity:h})]},`${h.type}-${h.name}-${u}`)),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(ul,{entities:m.selectedEntities.slice(3)})]})]})}),e.jsx(cl,{})]})]}),e.jsx(rl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(c==null?void 0:c.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:m,fallbackDataSource:d})]})}const ze=[{id:"table",icon:Je,label:"Table"},{id:"bar",icon:$e,label:"Bar Chart"},{id:"line",icon:Ge,label:"Line Chart"},{id:"area",icon:et,label:"Area Chart"},{id:"stackedBar",icon:ms,label:"Stacked Bar Chart"},{id:"combo",icon:Cn,label:"Combo Chart"},{id:"stackedLine",icon:ks,label:"Stacked Line Chart"},{id:"scatter",icon:xs,label:"Scatter Chart"},{id:"bubble",icon:ws,label:"Bubble Chart"},{id:"pie",icon:He,label:"Pie Chart"},{id:"doughnut",icon:ps,label:"Doughnut Chart"},{id:"funnel",icon:Ts,label:"Funnel Chart"},{id:"radar",icon:js,label:"Radar Chart"},{id:"polarArea",icon:Ss,label:"Polar Area Chart"},{id:"tornado",icon:ys,label:"Tornado Chart"},{id:"range",icon:hs,label:"Range Chart"},{id:"kpi",icon:Ds,label:"KPI"},{id:"text",icon:Zs,label:"Text"},{id:"map",icon:gs,label:"Map"}],Ms=t=>{const a=t.toLowerCase();for(const n of ze)if(n.id==="doughnut"){if(a.includes("doughnut")||a.includes("donut")){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}}else if(a.includes(n.id.toLowerCase())){const r=n.icon;return M.createElement(r,{className:"h-4 w-4"})}return null},hl="chart-selector-standard-first";function xl(){const[t,a]=s.useLocalStorageState(hl,!0);return{standardFirst:t,updatePreference:a}}const Ks=({pluginVisual:t,index:a,onSelect:n})=>{const r=Ye(t.icon||""),l=t.name.charAt(0).toUpperCase(),i=Ms(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,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"}):i||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}-${a}`)},Qs=["default","standardPlugin","customPlugin"];function pl({selectedChart:t,onChartChange:a}){var N;const[n,r]=M.useState([]),[l,i]=M.useState(!1),{data:c}=Cs();xl();const d=((N=s.useEditorStore(b=>b.card).customCardPreferences)==null?void 0:N.url)||"";s.useRemoteChartStore(d);const{setCardType:m,setCardPreferences:h,setIsDevMode:u}=s.useEditorStore(b=>b.actions),{setCardCustomCfg:p,setCustomCardPreferences:g,setQueryConfig:f}=s.useEditorActions(),[x,S]=s.useLocalStorageState("chart-section-active",null),j=M.useMemo(()=>x?[x,...Qs.filter(b=>b!==x)]:Qs,[x]);M.useEffect(()=>{(async()=>{if(c){const w=(await Promise.allSettled(c.plugins.map(async L=>{try{return(await s.loadManifest(L.value)).visuals.map(R=>({name:R.name,icon:R.icon,url:L.value,pluginName:L.label,pluginType:L.type,chartType:R.chartType,componentType:R.componentType}))}catch(T){return console.error(`Failed to load manifest for plugin ${L.label}`,T),[]}}))).filter(L=>L.status==="fulfilled").flatMap(L=>L.value);r(w)}})()},[c]);function v(b){p(null),h({}),m(b),["custom","text","map"].includes(b)&&(u(!0),f(void 0)),a(b),i(!1)}function C(b){p(null),h({}),m("custom"),g({type:"component",visualType:"single",url:b.url,componentName:b.name,icon:b.icon,pluginChartType:b.chartType}),f(void 0),a("custom"),i(!1)}const O=()=>{var k;if(t==="custom"){const w=s.useEditorStore.getState().card;return((k=w==null?void 0:w.customCardPreferences)==null?void 0:k.componentName)||"Custom Visual"}const b=ze.find(w=>w.id===t);return(b==null?void 0:b.label)||"Select chart type"},D=()=>{var k,w;if(t==="custom"){const L=s.useEditorStore.getState().card,T=(k=L==null?void 0:L.customCardPreferences)==null?void 0:k.icon,R=(w=L==null?void 0:L.customCardPreferences)==null?void 0:w.componentName;if(T&&R)return e.jsx(fl,{icon:T,componentName:R});if(R){const A=Ms(R);if(A)return A}return e.jsx(Ae,{className:"h-4 w-4"})}const b=ze.find(L=>L.id===t);if(b){const L=b.icon;return e.jsx(L,{className:"h-4 w-4"})}return e.jsx(Ae,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:l,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[D(),e.jsx("span",{children:O()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[335px] 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."}),j.map(b=>{if(b==="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:x==="default",onCheckedChange:k=>S(k?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:ze.map(k=>{const w=k.icon;return e.jsx(s.CommandItem,{value:`${k.label} ${k.id} chart graph visualization`,onSelect:()=>v(k.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{className:"h-4 w-4"}),e.jsx("span",{children:k.label})]})},k.id)})},"default");if(b==="standardPlugin"){const k=n.filter(w=>w.pluginType==="standard");return k.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:x==="standardPlugin",onCheckedChange:w=>S(w?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.filter(w=>w.componentType==="chart").map((w,L)=>e.jsx(Ks,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"standardPlugin"):null}if(b==="customPlugin"){const k=n.filter(w=>w.pluginType==="custom");return k.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:x==="customPlugin",onCheckedChange:w=>S(w?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.map((w,L)=>e.jsx(Ks,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"customPlugin"):null}return null})]})]})})]})})}const fl=({icon:t,componentName:a})=>{const n=Ye(),r=Ms(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Ae,{className:"h-4 w-4"})},Qt=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-blue-500 text-xs text-white",children:"T"}):a==="number"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-green-500 text-xs text-white",children:"#"}):a==="date"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-purple-500 text-xs text-white",children:"D"}):a==="boolean"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-orange-500 text-xs text-white",children:"B"}):e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-gray-500 text-xs text-white",children:"?"})};function gl({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=M.useState(t),[l,i]=M.useState(!1),c=(d=s.useEditorStore(m=>{var h;return(h=m.card.config)==null?void 0:h.pivotByColumns}))==null?void 0:d[0],o=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:o,value:l?n:t,onChange:m=>{r(m.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&l&&n!==t?(a(n),i(!1)):m.key==="Escape"&&(r(t),i(!1))},"aria-label":"Edit alias template"}),l&&n!==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:()=>{a(n),i(!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),i(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function jl({valueAliases:t,onValueAliasesChange:a}){const[n,r]=M.useState(null),[l,i]=M.useState(""),[c,o]=M.useState(""),d=()=>{a({...t,"":""})},m=u=>{const p={...t};delete p[u],a(p)},h=u=>{const p={...t};delete p[u],p[l]=c,a(p),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(([u,p],g)=>e.jsx("div",{className:"flex items-center gap-2",children:n===u?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:f=>i(f.target.value),className:"h-8 w-24 text-xs",onPointerDown:f=>f.stopPropagation(),onKeyDown:f=>{f.key==="Enter"?h(u):f.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:f=>o(f.target.value),className:"h-8 w-24 text-xs",onPointerDown:f=>f.stopPropagation(),onKeyDown:f=>{f.key==="Enter"?h(u):f.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:()=>h(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 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:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(u),i(u),o(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(u),i(u),o(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(u),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},u+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 Xs({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[i,c]=M.useState(t??""),[o,d]=M.useState(!1);M.useEffect(()=>{c(t??"")},[t]);const m=()=>{a(i),d(!1)},h=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:o?i:t??"",onChange:u=>{c(u.target.value),d(!0)},onFocus:()=>d(!0),onClick:u=>u.stopPropagation(),className:"h-8 text-xs",onPointerDown:u=>u.stopPropagation(),onKeyDown:u=>{u.stopPropagation(),u.key==="Enter"&&o&&i!==t?m():u.key==="Escape"&&h()},"aria-label":n||"Edit field"}),o&&i!==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:m,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:h,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function yl({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:i=!1,cardType:c}){var Rs;const{attributes:o,listeners:d,setNodeRef:m,transform:h,transition:u,isDragging:p}=s.useSortable({id:t.id}),g=s.useEditorStore(X=>X.card),{updateLabel:f,handleAggregationChange:x,handleDateFormatChange:S,handleGranularityChange:j,handleAliasTemplateChange:v,handleValueAliasesChange:C,removeField:O,handleKpiComparisonTypeChange:D,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:b,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:w}=As(g),[L,T]=M.useState(!1),[R,A]=M.useState(t.dateFormat||"YYYY-MM-DD"),[I,y]=M.useState(t.customFormat||""),[E,F]=M.useState(!!t.customFormat),[z,_]=M.useState(t.granularity||"day"),[P,Q]=M.useState(t.aliasTemplate||""),[Y,V]=M.useState(t.valueAliases||{}),q=X=>{X==="custom"?F(!0):(F(!1),A(X),a==="groupBy"&&S(n,X,""))},$=X=>{y(X),a==="groupBy"&&S(n,"custom",X)},U=X=>{_(X),a==="groupBy"&&j(n,X)},H=X=>{Q(X),a==="metrics"&&v(n,X)},W=X=>{V(X),a==="metrics"&&C(n,X)},G=X=>{f(a,n,X)},Z=()=>{O(a,n)},se={transform:s.CSS.Transform.toString(h),transition:u},ne=s.getDataType(t.dataType),ee=ne==="date",ae=c==="kpi",J=[{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..."}],B=!ae&&a!=="pivotBy",K=ae&&ee&&a==="groupBy",re=!ae&&ee&&a==="groupBy",he=ae&&ee&&a==="groupBy",je=ae&&a==="metrics"&&((Rs=g.config)==null?void 0:Rs.comparisonType)==="target",te=a==="metrics",le=()=>e.jsx("div",{onPointerDown:X=>{X.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),oe=()=>B?e.jsx(Xs,{value:t.label??"",onSave:G,placeholder:"Display label...",type:"text"}):null,Os=()=>K?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:z,onValueChange:U,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"}),e.jsx(s.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(s.SelectItem,{value:"year",children:"Year"})]})]})]}):null,en=()=>re?e.jsxs(e.Fragment,{children:[Os(),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:E?"custom":R,onValueChange:q,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:J.map(X=>e.jsx(s.SelectItem,{value:X.value,children:X.label},X.value))})]}),E&&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:I,onChange:X=>{X.stopPropagation(),$(X.target.value)},onClick:X=>X.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,sn=()=>{var X,xe,Te,Bs,Fs;return he?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:((X=g.config)==null?void 0:X.comparisonType)||"none",onValueChange:D,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:((xe=g.config)==null?void 0:xe.showTrendline)||!1,onCheckedChange:N})]})}),((Te=g.config)==null?void 0:Te.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:((Bs=g.config)==null?void 0:Bs.trendlineWindow)||30,onChange:an=>{const rn=parseInt(an.target.value)||30;b(rn)},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:((Fs=g.config)==null?void 0:Fs.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},tn=()=>{var X,xe;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(Xs,{value:((X=g.config)==null?void 0:X.targetValue)!==void 0&&((xe=g.config)==null?void 0:xe.targetValue)!==null?String(g.config.targetValue):"",onSave:Te=>{!isNaN(Number(Te))&&Te!==null?w(Number(Te)):w(0)},placeholder:"Enter target value...",type:"text"})]}):null},nn=()=>te?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:X=>{x(n,X)},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,{value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(Ht,{column:t}),i&&e.jsxs(e.Fragment,{children:[e.jsx(gl,{aliasTemplate:P,onAliasTemplateChange:H}),e.jsx(jl,{valueAliases:Y,onValueAliasesChange:W})]})]}):null;return e.jsxs("div",{ref:m,style:se,...o,...d,className:`group mx-auto flex w-full max-w-[300px] flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.GripVertical,{className:"h-3 w-3"}),e.jsx(Qt,{dataType:ne}),e.jsx(Es,{className:"max-w-[180px] flex-1 text-sm",children:t.label||t.name}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),T(!L)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${L?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const xe=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",xe),l(xe)},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 opacity-0 group-hover:opacity-100",onClick:X=>{X.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),L&&e.jsxs("div",{className:"space-y-3",children:[le(),oe(),Os(),en(),sn(),tn(),nn()]})]})}function vl({concept:t}){const a=()=>{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$1,{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:a()})]})})}function Fe({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:i=!1}){const{isOver:c,setNodeRef:o}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),m=s.useEditorStore(f=>f.card),h=s.useEditorStore(f=>f.card.type),u=a.length>0,p=(f,x)=>{var j;!((j=m.config)!=null&&j.sortByColumns)||m.config.sortByColumns.findIndex(v=>v.id===f)===-1||d(m.id,f,{direction:x})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4",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:n}),g&&e.jsx(vl,{concept:t})]}),e.jsx("div",{ref:o,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":"border-muted-foreground/20 bg-muted/50"}`,children:a.length===0?e.jsxs("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),r]}):e.jsx(s.SortableContext,{items:a.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((f,x)=>{const j=f.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(yl,{field:f,zone:t,index:x,sortDirection:j,onSortDirectionChange:v=>p(f.id,v),hasPivotColumns:i,cardType:h})})},f.id)})})})})]})}function bl({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const l=s.useEditorStore(u=>u.card),i=l==null?void 0:l.type,c=t.length>0||n.length>0,o=i!=="kpi",d=i!=="kpi"&&c,m=()=>i==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},h=()=>i==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Fe,{zone:"groupBy",fields:t,label:m().label,placeholder:m().placeholder}),o&&e.jsx(Fe,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Fe,{zone:"metrics",fields:n,label:h().label,placeholder:h().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(Fe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function Nl({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:i}){const c=s.useEditorStore(u=>u.showAIDialog),o=n.length>0||r.length>0||l.length>0,{setShowAIDialog:d}=s.useEditorActions(),m=s.useEditorStore(u=>u.card),{data:h}=s.useDashboardCardQuery(m);return e.jsxs("div",{className:"flex w-96 flex-col border-r bg-background",children:[e.jsxs("div",{className:"space-y-4 border-b px-6 py-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(pl,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:o||h}),children:e.jsx(s.EditorClearButton,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(ta,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(bl,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:i}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Cl({initialFilters:t,availableFields:a}={}){const[n,r]=M.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(D=>D.card.dataSource);const{columns:l,isLoading:i}=s.useColumns(),o=a||l||[],d={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},m=D=>{const N=b=>{if(b.id===D){const k=o[0]||d;return{...b,conditions:[...b.conditions,{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}]}}return{...b,groups:b.groups.map(N)}};r(N(n))},h=D=>{const N=b=>{if(b.id===D){const k=o[0]||d;return{...b,groups:[...b.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}],groups:[]}]}}return{...b,groups:b.groups.map(N)}};r(N(n))},u=(D,N)=>{const b=k=>k.id===D?{...k,conditions:k.conditions.filter(w=>w.id!==N)}:{...k,groups:k.groups.map(b)};r(b(n))},p=(D,N)=>{const b=k=>k.id===D?{...k,groups:k.groups.filter(w=>w.id!==N)}:{...k,groups:k.groups.map(b)};r(b(n))},g=(D,N,b,k)=>{if(b==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const w=L=>L.id===D?{...L,conditions:L.conditions.map(T=>T.id===N?{...T,[b]:k}:T)}:{...L,groups:L.groups.map(w)};r(w(n))},f=(D,N,b)=>{const k=w=>w.id===D?{...w,conditions:w.conditions.map(L=>L.id===N?{...L,...b}:L)}:{...w,groups:w.groups.map(k)};r(k(n))},x=(D,N)=>{const b=k=>k.id===D?{...k,logicalOperator:N}:{...k,groups:k.groups.map(b)};r(b(n))},S=(D,N)=>{const b=k=>k.id===D?{...k,negate:N}:{...k,groups:k.groups.map(b)};r(b(n))},j=(D,N,b)=>{const k=w=>w.id===D?{...w,conditions:s.arrayMove(w.conditions,N,b)}:{...w,groups:w.groups.map(k)};r(k(n))},v=(D,N,b)=>{const k=w=>w.id===D?{...w,groups:s.arrayMove(w.groups,N,b)}:{...w,groups:w.groups.map(k)};r(k(n))},C=D=>{if(!D||D.conditions.length===0&&D.groups.length===0)return"-- No filters defined";const N=k=>{let w="";typeof k.field=="object"?w=k.field.entityName?`${k.field.entityName}.${k.field.name}`:k.field.name:w=String(k.field);const L=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")(typeof T=="string"||T instanceof Date)&&(T=`DATE('${T}')`);else if(["in","not in"].includes(k.operator)){let R=[];Array.isArray(T)?R=T.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof T=="string"?R=T.split(",").map(A=>{const I=A.trim();return k.field.dataType==="string"?`'${I}'`:I}):typeof T=="number"&&(R=[String(T)]),T=`(${R.join(", ")})`}switch(L){case"contains":return typeof T=="string"?`${w} LIKE '%${T.replace(/'/g,"")}'`:`${w} LIKE '%${String(T)}'`;case"startsWith":return typeof T=="string"?`${w} LIKE '${T.replace(/'/g,"")}%'`:`${w} LIKE '${String(T)}%'`;case"endsWith":return typeof T=="string"?`${w} LIKE '%${T.replace(/'/g,"")}'`:`${w} LIKE '%${String(T)}'`;default:return`${w} ${L} ${T}`}},b=k=>{const w=k.conditions.map(N),L=k.groups.map(I=>b(I)),T=[...w,...L].filter(Boolean);if(T.length===0)return"";const R=T.join(` ${k.logicalOperator} `),A=T.length>1?`(${R})`:R;return k.negate?`NOT ${A}`:A};return b(D)},O=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:o,isLoading:i,addCondition:m,addGroup:h,removeCondition:u,removeGroup:p,updateCondition:g,updateConditionFields:f,updateGroupOperator:x,updateGroupNegate:S,reorderConditions:j,reorderGroups:v,generateSQLPreview:C,hasAnyFilters:O}}function Sl({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const wl=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(Ln,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Tl=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function kl({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[i,c]=M.useState(!1),o=M.useMemo(()=>{const d={};return n.forEach(m=>{const h=Tl(m);d[h]||(d[h]={}),d[h][m.entityId]||(d[h][m.entityId]=[]),d[h][m.entityId].push(m)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:i,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Sl,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(o).map(([d,m])=>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(m).map(([h,u])=>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:[wl(u[0].entityType),e.jsx("span",{children:u[0].entityName})]}),u.map((p,g)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{a(p),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)===p.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:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+g))]},`${d}-${h}`))},d))})]})})]})}function Ls(t){var f;const a=s.useEditorStore(x=>x.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(x=>x.card.config),l=r==null?void 0:r.joinPlan,i={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...i,role:"sortby",direction:"asc"},d={joinPlan:l,groupByColumns:[i],metricColumns:[c],sortByColumns:[o]},m=((f=a.dataSource)==null?void 0:f.connectionId)||a.connectionId,{data:h,isPending:u,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:m,cardConfig:d,cardDataSource:a.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:u,error:p}}function Dl({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[i,c]=ye.useState(!1),{filterValues:o}=Ls(t),d=h=>{n(a.filter(u=>u!==h))},m=h=>{a.includes(h)?n(a.filter(u=>u!==h)):n([...a,h])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:i,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":i,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:a.length>0?a.map(h=>{const u=o.find(p=>p.value===h);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[u==null?void 0:u.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:p=>{p.key==="Enter"&&d(h)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),d(h)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},h)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:o.map((h,u)=>e.jsxs(s.CommandItem,{onSelect:()=>m(h.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(h.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.count})]})]},h.value+u))})]})]})})]})})}const Xt=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=Xt(n)}),a};function El({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:i,isPending:c,error:o}=Ls(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):o?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:i.map((d,m)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+m))})]})}const Il=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Al=["=","!=","contains","startsWith","endsWith","in","not in"],Ml=["=","!=",">",">=","<","<=","in","not in"],Ll=["=","!="],Ol=["=","!=",">",">=","<","<=","in","not in"];function Rl(t){switch(t){case"string":return Al;case"number":return Ml;case"boolean":return Ll;case"date":return Ol;default:return Il}}function Zt({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:i,onUpdateGroupOperator:c,availableFields:o,updateConditionFields:d}){const{attributes:m,listeners:h,setNodeRef:u,transform:p,transition:g,isDragging:f}=s.useSortable({id:t.id}),{isPending:x,error:S}=Ls(t.field),j={transform:s.CSS.Transform.toString(p),transition:g};return e.jsxs("div",{ref:u,style:j,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${f?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...h,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:v=>c(n,v),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"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(kl,{value:t.field,onValueChange:v=>{d(n,t.id,{field:v,value:""})},availableFields:o,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:v=>{v==="in"||v==="not in"?d(n,t.id,{operator:v,value:[]}):d(n,t.id,{operator:v,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Rl(s.getDataType(t.field.dataType)).map(v=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:v,children:v},v))})]}),s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?x?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..."]}):S?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Dl,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(v=>typeof v=="string")?t.value:[],onChange:v=>d(n,t.id,{value:v}),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:v=>d(n,t.id,{value:v.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(El,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:v=>d(n,t.id,{value:v}),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:v=>d(n,t.id,{value:v==="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"})]})]}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:v=>l(n,t.id,"value",v.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:()=>i(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Bl({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:i,onUpdateCondition:c,onUpdateField:o,onRemoveCondition:d,onReorderConditions:m,onReorderGroups:h,onAddCondition:u,onAddGroup:p,availableFields:g,renderFilterGroup:f,updateConditionFields:x}){const{attributes:S,listeners:j,setNodeRef:v,transform:C,transition:O,isDragging:D}=s.useSortable({id:t.id}),N={transform:s.CSS.Transform.toString(C),transition:O},b=w=>{const{active:L,over:T}=w;if(T&&L.id!==T.id){const R=t.conditions.findIndex(I=>I.id===L.id),A=t.conditions.findIndex(I=>I.id===T.id);R!==-1&&A!==-1&&m(t.id,R,A)}},k=w=>{const{active:L,over:T}=w;if(T&&L.id!==T.id&&n){const R=t.groups.findIndex(I=>I.id===L.id),A=t.groups.findIndex(I=>I.id===T.id);R!==-1&&A!==-1&&h(n,R,A)}};return e.jsxs("div",{ref:v,style:N,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${D?"z-50 opacity-50":""}`,children:[a>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",{...S,...j,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:w=>r(t.id,w),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:()=>n&&i(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>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:b,children:e.jsx(s.SortableContext,{items:t.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((w,L)=>e.jsx(Zt,{condition:w,index:L,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:o,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:x},w.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(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(w=>f(w,a+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:()=>u(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:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Fl({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:i,availableFields:c,isLoading:o,addCondition:d,addGroup:m,removeCondition:h,removeGroup:u,updateCondition:p,updateConditionFields:g,updateGroupOperator:f,updateGroupNegate:x,reorderConditions:S,reorderGroups:j,generateSQLPreview:v,hasAnyFilters:C,setCurrentFilters:O}=Cl({initialFilters:t,availableFields:a}),D=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[N,b]=M.useState(!1),k=(T,R,A)=>{const I=y=>y.id===T?{...y,conditions:y.conditions.map(E=>E.id===R?{...E,field:A,dataType:A.dataType}:E)}:{...y,groups:y.groups.map(I)};O(I(i))},w=(T,R=0,A)=>R===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:D,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:E}=I;if(E&&y.id!==E.id){const F=T.conditions.findIndex(_=>_.id===y.id),z=T.conditions.findIndex(_=>_.id===E.id);F!==-1&&z!==-1&&S(T.id,F,z)}},children:e.jsx(s.SortableContext,{items:T.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:T.conditions.map((I,y)=>e.jsx(Zt,{condition:I,index:y,groupId:T.id,groupLogicalOperator:T.logicalOperator,onUpdateCondition:p,onUpdateField:k,onRemoveCondition:h,onUpdateGroupOperator:f,availableFields:c,updateConditionFields:g},I.id))})}),e.jsx(s.DndContext,{sensors:D,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:E}=I;if(E&&y.id!==E.id){const F=T.groups.findIndex(_=>_.id===y.id),z=T.groups.findIndex(_=>_.id===E.id);F!==-1&&z!==-1&&j(T.id,F,z)}},children:e.jsx(s.SortableContext,{items:T.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:T.groups.map(I=>w(I,R+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"]}),N&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(T.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},T.id):e.jsx(Bl,{group:T,depth:R,parentGroupId:A,onUpdateGroupOperator:f,onUpdateGroupNegate:x,onRemoveGroup:u,onUpdateCondition:p,onUpdateField:k,onRemoveCondition:h,onReorderConditions:S,onReorderGroups:j,onAddCondition:d,onAddGroup:m,availableFields:c,renderFilterGroup:w,updateConditionFields:g},T.id),L=Xt(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[o?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):w(i),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.Checkbox,{id:"advanced-mode",checked:N,onCheckedChange:T=>b(!!T)}),e.jsx("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)"})]})}),C&&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:v(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),L>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(C?i:null),children:"Apply Filters"})]})]})}function zl({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:i,onOpenChange:c}){const o=m=>{n(t,m),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:i,onOpenChange:c,children:[i&&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:m=>{m.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(Fl,{filters:a,availableFields:l,onSave:o,onCancel:()=>c(!1),onClearAll:d})]})]})}function Pl({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var g;const[l,i]=M.useState(null),c=s.useEditorStore(f=>f.card),o=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],m=M.useCallback(f=>f.startsWith("card-")?null:f.startsWith("source-")||a.find(x=>x.id===f)?"source":n("groupBy").find(x=>x.id===f)?"groupBy":n("metrics").find(x=>x.id===f)?"metrics":n("pivotBy").find(x=>x.id===f)?"pivotBy":n("sortBy").find(x=>x.id===f)?"sortBy":null,[a,n]),h=M.useCallback(f=>{i(f.active.id)},[]),u=M.useCallback(f=>{const{active:x,over:S}=f;if(!S||!t){i(null);return}const j=x.id,v=S.id,C=m(j),O=m(v)||v;if(C==="source"&&O==="sortBy"){i(null);return}if(C==="source"&&O!=="source"&&O!=="sortBy"){const D=[...a].find(w=>w.id===j);if(!D){i(null);return}const N=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(N.length>0){const w=N[0].qualifiedEntityName;if(!w){i(null);return}if(w!==D.qualifiedEntityName&&D.qualifiedEntityName)if(o){if(!Kt(w,D.qualifiedEntityName,o)){ds(),i(null);return}}else{ds(),i(null);return}}const b=n(O);if(us(D,b)){i(null);return}const k=cs(D,O);i(null),r(O,[...b,k]);return}if(C&&O&&C!=="source"&&O!=="source"&&C!==O){const D=n(C),N=n(O),b=D.find(L=>L.id===j);if(!b){i(null);return}const k=cs(b,O);if(i(null),O==="sortBy"){if(C==="pivotBy"){i(null);return}us(b,N)||r(O,[...N,k]);return}const w=D.filter(L=>L.id!==j);r(C,w),r(O,[...N,k]);return}if(C&&O&&C===O&&C!=="source"){const D=n(C),N=D.findIndex(k=>k.id===j),b=D.findIndex(k=>k.id===v);if(N!==b){const k=s.arrayMove(D,N,b);r(C,k)}}i(null)},[t,a,n,r,m,o]),p=l?d.find(f=>f.id===l):null;return{activeId:l,activeField:p,handleDragStart:h,handleDragEnd:u}}function _l({activeView:t,onViewChange:a}){const n=s.useEditorStore(l=>l.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:l=>a(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-2 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"}),n.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const Vl=[{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 Ul(){var d,m;const t=s.useEditorStore(h=>h.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=M.useState(!1),[l,i]=M.useState(""),c=h=>{if(h==="custom"){r(!0);return}r(!1),a(t.id,parseInt(h))},o=h=>{const u=h.target.value;i(u),u&&!isNaN(parseInt(u))&&a(t.id,parseInt(u))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:l,onChange:o,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((m=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:m.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:Vl.map(h=>e.jsx(s.SelectItem,{value:h.value,children:h.label},h.value))})]})})}function ql({isOpen:t,onClose:a}){const n=jt(a,{enabled:t}),r=s.useEditorStore(h=>{var u;return((u=h.card.customCardPreferences)==null?void 0:u.url)||""}),l=s.useEditorStore(h=>h.card),i=s.useEditorStore(h=>{var u;return((u=h.card.customCardPreferences)==null?void 0:u.pluginChartType)||""}),c=s.useEditorStore(h=>{var u;return((u=h.card.customCardPreferences)==null?void 0:u.settings)||{}}),{data:o}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),m=M.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,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:a,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:m&&e.jsx(M.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(m,{chartData:(o==null?void 0:o.records)||[],chartType:i,settings:c})})})]})})}function $l({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:l,onClear:i,onAdvancedToggle:c,onFiltersClick:o,filterCount:d,activeCard:m,columns:h,columnsLoading:u,columnsError:p}){var R;const g=s.useEditorStore(A=>A.card),f=s.useDashboardStore(A=>A.filterValues),{updateCardConfig:x}=s.useEditorActions(),S=s.useEditorStore(A=>A.showAIDialog),[j,v]=M.useState(!1),C=s.useEditorStore(A=>{var I;return((I=A.card.customCardPreferences)==null?void 0:I.url)&&A.card.type==="custom"}),{data:O,errorMessage:D,isPending:N,isLoading:b,isFetching:k}=s.useDashboardCardQuery(m);function w(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",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(g.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(f||{},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(m.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",h.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:u?"Loading...":p?"Error loading columns":JSON.stringify(h.slice(0,5),null,2)})]})]})})}const L=A=>{if(!g.config)return;if(!A.length){x(g.id,{...g.config,sortByColumns:[]});return}const I=g.config,y=A.map(({id:E,desc:F})=>{var Q,Y;const z=(Q=I.metricColumns)==null?void 0:Q.find(V=>V.label===E),_=(Y=I.groupByColumns)==null?void 0:Y.find(V=>V.label===E),P=z||_;return P?{id:Wt("sortBy",P),name:P.name,dataType:P.dataType,label:P.label,qualifiedEntityName:P.qualifiedEntityName,entityId:P.entityId,entityName:P.entityName,entityType:P.entityType,role:"sortby",direction:F?"desc":"asc"}:null}).filter(E=>E!==null);x(g.id,{...I,sortByColumns:y})},T=M.useMemo(()=>{var A,I;return(I=(A=g.config)==null?void 0:A.sortByColumns)==null?void 0:I.map(y=>({id:y.label,desc:y.direction==="desc"}))},[(R=g.config)==null?void 0:R.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(s.ExplorerHeader,{showDebug:n,onDebugToggle:r,onAccept:l,onClear:i,onAdvancedToggle:c,onFiltersClick:o,filterCount:d}),n&&w(),e.jsx(s.Separator,{}),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"&&S&&e.jsx(zt,{variant:"outline"}),e.jsx(_l,{activeView:t,onViewChange:a}),o&&e.jsxs(s.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:o,children:[e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),d>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:d})]}),e.jsx("div",{className:"ml-2",children:e.jsx(Ul,{})}),S&&e.jsx(s.EditorClearButton,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(Pt,{})})]}),!j&&C&&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(Zn,{className:"size-4"})}),e.jsxs("div",{className:"flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:b||k?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(_t,{})}),t==="table"&&(O==null?void 0:O.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(b||k)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(s.TableVisual,{card:m,data:O==null?void 0:O.records,onSortChange:L,sortState:T})]}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md border bg-background p-4",children:[(O==null?void 0:O.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(At,{sql:O==null?void 0:O.sql,error:D})]})})]}),e.jsx(ql,{isOpen:j,onClose:()=>v(!1)})]})]})}function Gl({activeField:t}){const[a,n]=M.useState(!0);return M.useEffect(()=>{t&&n(!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 ${a?"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(Qt,{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 Hl=()=>{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 a=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},n=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",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Jl(){var V,q;const[t,a]=M.useState("chart"),[n,r]=M.useState(!1),[l,i]=M.useState(!1),[c,o]=M.useState(!0),d=s.useEditorStore($=>$.showAIDialog),m=s.useDashboardStore($=>$.isVisualEditing),{setCardType:h}=s.useEditorActions(),u=s.useEditorStore($=>$.card.type);M.useEffect(()=>Hl(),[]);const p=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},f=()=>{console.log("Advanced mode toggled")},x=()=>{i(!0)},S=$=>{h($)},j=s.useEditorStore($=>$.frame),v=s.useEditorStore($=>$.card);s.useEditorStore($=>$.activeTabCardId),s.useEditorStore($=>$.actions.getAvailableFields);const{addCard:C,removeCard:O,updateCard:D,setActiveCard:N,updateFilters:b}=s.useEditorActions(),{columns:k=[],isLoading:w,error:L}=s.useColumns(),T=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),R=v,{getFieldsForContainer:A,setFieldsForContainer:I}=As(R),{activeField:y,handleDragStart:E,handleDragEnd:F}=Pl({activeCardId:j.activeCardId,sourceFields:k,getFieldsForContainer:A,setFieldsForContainer:I}),z=($,U)=>{U&&b($,U)},_=$=>{var U;D($,{config:{...(U=j.cards.find(H=>H.id===$))==null?void 0:U.config,filters:void 0}})},P=k,Q=$=>{if(!$)return 0;let U=$.conditions.length;return $.groups.forEach(H=>{U+=Q(H)}),U},Y=Q(((V=R==null?void 0:R.config)==null?void 0:V.filters)||null);return e.jsxs(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragStart:E,onDragEnd:F,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(ml,{isVisible:c,onToggleVisibility:()=>o(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Nl,{selectedChart:u,onChartChange:S,groupByFields:A("groupBy"),pivotByFields:A("pivotBy"),metricsFields:A("metrics"),sortByFields:A("sortBy")}),e.jsx($l,{selectedChart:u,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:p,onClear:g,onAdvancedToggle:f,onFiltersClick:x,filterCount:Y,activeCard:R,dataSourceState:v.dataSource||s.EMPTY_DATA_SOURCE,columns:k,columnsLoading:w,columnsError:L,getFieldsForContainer:A,cards:j.cards,activeCardId:j.activeCardId,addCard:C,setActiveCard:N})]}),!c&&m&&e.jsx("div",{className:"fixed bottom-4 left-4 z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>o(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),R&&e.jsx(zl,{cardId:R.id,filters:((q=R.config)==null?void 0:q.filters)||null,onFiltersChange:z,onClearFilters:_,availableFields:P,isOpen:l,onOpenChange:i}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Gl,{activeField:y||null})})]})}function Wl({authToken:t,onSave:a,onClose:n}){const r=M.useRef(null),l=s.useEditorStore(v=>v.showAIDialog),i=s.useEditorStore(v=>v.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:o,setOnSave:d,setOnClose:m}=s.useEditorActions(),{handleDragOver:h,handleDragEnd:u,handleDragStart:p,handleDragCancel:g,sensors:f}=za();M.useEffect(()=>{a&&d(a),n&&m(n)},[a,d,n,m]),M.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),M.useEffect(()=>{var v,C;l?((v=r.current)==null||v.resize(40),o(!0)):(o(!1),(C=r.current)==null||C.resize(0))},[l,o]);function x(v){v<1?o(!1):l||o(!0)}function S(){return e.jsxs(e.Fragment,{children:[e.jsx(Et,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Xr,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Ws,{})})]})]})}function j(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Jl,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Ws,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:i?e.jsx(s.DndContext,{sensors:f,onDragStart:p,onDragEnd:u,onDragOver:h,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:S()})}):j()})}function Yl(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),a(!1))}function i(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Wl,{onSave:l,onClose:i})})}function Kl(){const t=s.useEditorStore(i=>i.selectedDatabaseName),a=s.useEditorStore(i=>i.selectedTableName),n=s.useDashboardStore(i=>i.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=$t();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(i=>{const c=n==null?void 0:n.find(o=>o.column===s.fmt(i.column_name)&&o.table===a&&o.database===t);return e.jsx("div",{onClick:()=>l(i),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(bs,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function Ql(){s.useDashboardStore(a=>a.showFilters);const t=s.useDashboardStore(a=>a.actions.setShowFilters);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:e.jsx(Et,{type:"filter",ColumnsComponent:()=>e.jsx(Kl,{})})})]})}function Xl(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.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)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.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 Zl(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(Xl,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Ql,{})})]})}function eo(){const t=s.useDashboardStore(l=>l.dashboard),a=s.useDashboardStore(l=>l.actions.setDashboard),n=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),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),a(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 so({showControls:t=!1,showFooter:a=!0,...n}){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsxs(s.UXProvider,{children:[e.jsx(eo,{}),e.jsxs("main",{className:"flex h-full flex-col",children:[t&&e.jsx(La,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(Yl,{}),e.jsx(Zl,{})]})]})]})]})})}exports.DashboardPlus=so;exports.ResourceManagementPanel=kt;exports.ScheduleDashboard=mt;exports.SelectComponent=ke;exports.cleanCard=ct;exports.downloadPdf=ut;exports.getDashbaordStateWithoutData=vs;