react-semaphor 0.0.603 → 0.0.604
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{dashboard-plus-DaQzKbBt.js → dashboard-plus-BCYkzhJl.js} +8 -8
- package/dist/chunks/{dashboard-plus-C77hCbZC.js → dashboard-plus-DLNR8UT-.js} +481 -471
- package/dist/chunks/index-Bca4CpHf.js +866 -0
- package/dist/chunks/{index-sYcwJnZF.js → index-CzP4rV5O.js} +41704 -40828
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -3
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/dist/types/dashboard.d.ts +6 -1
- package/dist/types/main.d.ts +7 -1
- package/dist/types/surfboard.d.ts +6 -1
- package/dist/types/types.d.ts +6 -1
- package/package.json +1 -1
- package/dist/chunks/index-CggdOrtY.js +0 -871
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var et=t=>{throw TypeError(t)};var bs=(t,n,a)=>n.has(t)||et("Cannot "+a);var oe=(t,n,a)=>(bs(t,n,"read from private field"),a?a.call(t):n.get(t)),Ye=(t,n,a)=>n.has(t)?et("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(t):n.set(t,a),Ge=(t,n,a,r)=>(bs(t,n,"write to private field"),r?r.call(t,a):n.set(t,a),a),Ke=(t,n,a)=>(bs(t,n,"access private method"),a);const e=require("react/jsx-runtime"),s=require("./index-
|
|
1
|
+
"use strict";var et=t=>{throw TypeError(t)};var bs=(t,n,a)=>n.has(t)||et("Cannot "+a);var oe=(t,n,a)=>(bs(t,n,"read from private field"),a?a.call(t):n.get(t)),Ye=(t,n,a)=>n.has(t)?et("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(t):n.set(t,a),Ge=(t,n,a,r)=>(bs(t,n,"write to private field"),r?r.call(t,a):n.set(t,a),a),Ke=(t,n,a)=>(bs(t,n,"access private method"),a);const e=require("react/jsx-runtime"),s=require("./index-Bca4CpHf.js"),A=require("react");require("react-dom");function Cn(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const pe=Cn(A);var Le,Re,xe,we,ke,hs,As,jt,Sn=(jt=class extends s.Subscribable{constructor(n,a){super();Ye(this,ke);Ye(this,Le);Ye(this,Re);Ye(this,xe);Ye(this,we);Ge(this,Le,n),this.setOptions(a),this.bindMethods(),Ke(this,ke,hs).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var r;const a=this.options;this.options=oe(this,Le).defaultMutationOptions(n),s.shallowEqualObjects(this.options,a)||oe(this,Le).getMutationCache().notify({type:"observerOptionsUpdated",mutation:oe(this,xe),observer:this}),a!=null&&a.mutationKey&&this.options.mutationKey&&s.hashKey(a.mutationKey)!==s.hashKey(this.options.mutationKey)?this.reset():((r=oe(this,xe))==null?void 0:r.state.status)==="pending"&&oe(this,xe).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=oe(this,xe))==null||n.removeObserver(this)}onMutationUpdate(n){Ke(this,ke,hs).call(this),Ke(this,ke,As).call(this,n)}getCurrentResult(){return oe(this,Re)}reset(){var n;(n=oe(this,xe))==null||n.removeObserver(this),Ge(this,xe,void 0),Ke(this,ke,hs).call(this),Ke(this,ke,As).call(this)}mutate(n,a){var r;return Ge(this,we,a),(r=oe(this,xe))==null||r.removeObserver(this),Ge(this,xe,oe(this,Le).getMutationCache().build(oe(this,Le),this.options)),oe(this,xe).addObserver(this),oe(this,xe).execute(n)}},Le=new WeakMap,Re=new WeakMap,xe=new WeakMap,we=new WeakMap,ke=new WeakSet,hs=function(){var a;const n=((a=oe(this,xe))==null?void 0:a.state)??s.getDefaultState();Ge(this,Re,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},As=function(n){s.notifyManager.batch(()=>{var a,r,l,o,c,i,u,d;if(oe(this,we)&&this.hasListeners()){const m=oe(this,Re).variables,h=oe(this,Re).context;(n==null?void 0:n.type)==="success"?((r=(a=oe(this,we)).onSuccess)==null||r.call(a,n.data,m,h),(o=(l=oe(this,we)).onSettled)==null||o.call(l,n.data,null,m,h)):(n==null?void 0:n.type)==="error"&&((i=(c=oe(this,we)).onError)==null||i.call(c,n.error,m,h),(d=(u=oe(this,we)).onSettled)==null||d.call(u,void 0,n.error,m,h))}this.listeners.forEach(m=>{m(oe(this,Re))})})},jt);function $e(t,n){const a=s.useQueryClient(),[r]=pe.useState(()=>new Sn(a,t));pe.useEffect(()=>{r.setOptions(t)},[r,t]);const l=pe.useSyncExternalStore(pe.useCallback(c=>r.subscribe(s.notifyManager.batchCalls(c)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=pe.useCallback((c,i)=>{r.mutate(c,i).catch(s.noop)},[r]);if(l.error&&s.shouldThrowError(r.options.throwOnError,[l.error]))throw l.error;return{...l,mutate:o,mutateAsync:l.mutate}}/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -338,7 +338,7 @@
|
|
|
338
338
|
*
|
|
339
339
|
* This source code is licensed under the ISC license.
|
|
340
340
|
* See the LICENSE file in the root directory of this source tree.
|
|
341
|
-
*/const ja=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function ya(){const{setTheme:t}=s.useTheme(),n=s.useDashboardStore(a=>a.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(pa,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(aa,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function xs(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>St(c))}})}})}}function St(t){return{...t,customCfg:va(t.customCfg),data:[]}}function va(t){var n,a;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(a=(n=t==null?void 0:t.data)==null?void 0:n.datasets)==null?void 0:a.map(r=>({...r,data:[]}))}}:null}async function ba(t,n,a,r){if(!r)return null;const l=JSON.stringify(n);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:l,filterValues:a,operation:"create"})}async function Ls(t,n){if(!n)return null;const{id:a,template:r,filterValues:l,isDefault:o,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",n,{lensId:a,template:r,filterValues:l,isDefault:o,shared:c,operation:"update"})}async function Na(t,n){return n?await s.postRequest("https://semaphor.cloud/api/v1/lens",n,{operation:"delete",lensId:t}):null}function Ca(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),l=s.useDashboardStore(x=>x.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,u]=A.useState(!1),[d,m]=A.useState(!1),h=s.useDashboardStore(x=>x.dashboard),f=s.useDashboardStore(x=>x.filterValues),{authToken:g}=s.useSemaphorContext();async function j(){u(!0);const x=xs(h),y=await ba(t,x,f,g==null?void 0:g.accessToken);y&&(o([...l||[],y]),c(y.id),m(!1)),u(!1)}return e.jsxs(s.Dialog,{open:d,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:x=>{n(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:j,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Sa(){const[t,n]=A.useState(!1),a=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(m){o(m)}async function u(m){if(await Na(m,c==null?void 0:c.accessToken)){const f=a==null?void 0:a.filter(g=>g.id!==m);l(f||[]),o("original")}}async function d(m){const h=a==null?void 0:a.map(j=>j.id===m.id?{...j,isDefault:!m.isDefault}:{...j,isDefault:!1});l(h||[]);const f={...m,isDefault:!m.isDefault};await Ls(f,c==null?void 0:c.accessToken);const g=a==null?void 0:a.find(j=>j.isDefault);if(g&&g.id!==m.id){const j={...g,isDefault:!1};await Ls(j,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Yn,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(m=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:m.id,children:[e.jsx("p",{children:m.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),d(m)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!m.isDefault,"text-green-500":m.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),u(m.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},m.id))]})]})]})}function wa({iconClassName:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(""),[o,c]=A.useState(!1),i=s.useDashboardStore(m=>m.isDownloadingPdf);async function u(){const m=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(),s.ue.dismiss(m),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",h)}}async function d(){if(!r)return;a(!1),l(""),c(!1);const m=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(r),s.ue.dismiss(m),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",h)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(Bs,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:n,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:m=>l(m.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:m=>{m.key==="Enter"&&r&&d()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:d,disabled:!r,children:"Download"})]})]})})]})}function je({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(u=>e.jsx(s.SelectItem,{value:u.value,children:u.label},u.value))]})})]})}const at=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function wt({triggerButtonClassName:t}){const{data:n,handleScheduleSubscription:a,handleDeleteSubscription:r,status:l,error:o,isDeleting:c}=Da(),[i,u]=A.useState(""),[d,m]=A.useState(at[0].value),[h,f]=A.useState("06:00"),[g,j]=A.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=>u(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=>{j(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(je,{className:"col-span-2 h-8",label:"Select Frequency",options:at,value:d,onValueChange:x=>m(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:h,onChange:x=>f(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 a({email:i,frequency:d,time:h,subject:g}),f("00:00"),u(""),j("")},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(yt,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:o})})]}),"Schedule"]})}),n&&n.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:n==null?void 0:n.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(rt,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Rn,{className:"size-3.5"})}),e.jsx(rt,{tooltip:`${x.endUserEmail}`,children:e.jsx(sa,{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 rt=({children:t,tooltip:n})=>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:n})]})});function Da(){const[t,n]=A.useState("idle"),[a,r]=A.useState(""),[l,o]=A.useState(null),c=s.useDashboardStore(T=>T.authToken),i=s.useDashboardStore(T=>T.dashboard.id),u=s.useDashboardStore(T=>T.dashboard.title),{endUserId:d}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),m="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:i,endUserId:d},{data:f,isLoading:g,isError:j,isFetching:x,refetch:y}=s.useQuery({queryKey:["subscriptions",i,d],queryFn:()=>s.getRequest(m,(c==null?void 0:c.accessToken)||"",h),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!d});async function p({email:T,subject:R,frequency:N,time:w}){const{authToken:v,...D}=s.getParamsForPrint(),C=Intl.DateTimeFormat().resolvedOptions().timeZone,I={email:T,frequency:N,time:w,timezone:C,endUserId:d,endUserEmail:T,subject:R||u||"Scheduled Dashboard",dashboardId:i,dashboardParams:D};n("loading");const S="https://semaphor.cloud/api/v1/subscriptions/create";try{const O=await s.postRequestRegular(S,(v==null?void 0:v.accessToken)||"",{...I});n("success"),r(""),y(),setTimeout(()=>{n("idle")},2e3)}catch(O){console.error(O),n("error"),r(O.message)}}async function b(T){const R="https://semaphor.cloud/api/v1/subscriptions/delete";o(T);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:T}),y(),setTimeout(()=>{o(null)},2e3)}catch(N){console.error(N),o(null),n("error"),r(N.message)}}return{data:f,isLoading:g,isFetching:x,isError:j,isDeleting:l,refetch:y,handleScheduleSubscription:p,handleDeleteSubscription:b,status:t,error:a}}function Ie(){const{authToken:t,tokenProps:n}=s.useSemaphorContext();let a=null;n&&(n.endUserId&&n.endUserEmail&&n.tenantId?a={id:n.endUserId,name:n.endUserEmail?String(n.displayName):"",email:n.endUserEmail?String(n.endUserEmail):"",type:"tenant",tenantId:n.tenantId}:n.orgUserId&&n.orgUserEmail&&(a={id:n.orgUserId,name:n.orgUserEmail?String(n.displayName):"",email:n.orgUserEmail?String(n.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:l,isError:o}=s.useQuery({queryKey:["userInfo",a==null?void 0:a.id],queryFn:async()=>{if(!(a!=null&&a.id))return;const i=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${a.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)&&!!(a!=null&&a.id)});return{currentUser:a?{...a,...r||{}}:null,isLoading:l,isError:o}}function Dt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,n)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},n))})]})})}var ae=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(ae||{});const ka=async(t,n,a,r,l,o)=>{const c={},i={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${i[n]}`,t,c)},Ta=async(t,n,a)=>{const r={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[n]}`,t,a)},Ea=async(t,n,a,r)=>{const l={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${l[n]}/${a}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${o.status}`)}return o.json()},Ia=async(t,n,a)=>{const r={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!l.ok){const o=await l.json();throw new Error((o==null?void 0:o.error)||`HTTP error! status: ${l.status}`)}return l.json()},Aa=async(t,n,a)=>{const r={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}/duplicate`,t,{})},Ma=async(t,n,a,r)=>{const l={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${l[n]}/${a}/share`,t,r)},La=async(t,n,a,r)=>{const l={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${l[n]}/${a}/share`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${o.status}`)}return o.json()},Ra=async(t,n,a)=>{const r={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}/shares`,t)},Oa=async(t,n,a)=>{const r={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}`,t)};function Fa(t){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(n==null?void 0:n.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(n!=null&&n.accessToken):!!(n!=null&&n.accessToken)})}function Ba(t,n,a,r,l){const{authToken:o}=s.useSemaphorContext(),{currentUser:c}=Ie();return s.useQuery({queryKey:[t,n,a,r,l],queryFn:()=>ka((o==null?void 0:o.accessToken)||"",t),enabled:!!(o!=null&&o.accessToken)&&!!c})}function Pa(t,n){const{authToken:a}=s.useSemaphorContext(),r=s.useQueryClient();return $e({mutationFn:l=>Ta((a==null?void 0:a.accessToken)||"",t,l),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} created successfully`),n==null||n()},onError:l=>{s.ue.error(`Failed to create ${s.toTitleCase(t)}: ${l.message}`)}})}function kt(t){const{authToken:n}=s.useSemaphorContext(),a=s.useQueryClient();return $e({mutationFn:({resourceId:r,data:l})=>Ea((n==null?void 0:n.accessToken)||"",t,r,l),onMutate:async()=>{await a.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await a.invalidateQueries({queryKey:[t]})},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function za(t,n){const{authToken:a}=s.useSemaphorContext(),r=s.useQueryClient();return $e({mutationFn:l=>Ia((a==null?void 0:a.accessToken)||"",t,l),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} deleted successfully`),n==null||n()},onError:l=>{s.ue.error(`Failed to delete ${s.toTitleCase(t)}: ${l.message}`)}})}function Va(t){const{authToken:n}=s.useSemaphorContext(),a=s.useQueryClient();return $e({mutationFn:r=>Aa((n==null?void 0:n.accessToken)||"",t,r),onMutate:async()=>{await a.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await a.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} duplicated successfully`)},onError:r=>{s.ue.error(`Failed to duplicate ${s.toTitleCase(t)}: ${r.message}`)}})}function _a(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return $e({mutationFn:({resourceType:a,resourceId:r,data:l})=>Ma((t==null?void 0:t.accessToken)||"",a,r,l),onMutate:async a=>{await n.cancelQueries({queryKey:["resource-shares",a.resourceType,a.resourceId]})},onSuccess:async(a,r)=>{await n.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),n.invalidateQueries({queryKey:[r.resourceType]})},onError:a=>{s.ue.error(`Failed to share resource: ${a.message}`)}})}function Ua(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return $e({mutationFn:({resourceType:a,resourceId:r,data:l})=>La((t==null?void 0:t.accessToken)||"",a,r,l),onMutate:async a=>{await n.cancelQueries({queryKey:["resource-shares",a.resourceType,a.resourceId]})},onSuccess:async(a,r)=>{await n.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),n.invalidateQueries({queryKey:[r.resourceType]})},onError:a=>{s.ue.error(`Failed to remove resource shares: ${a.message}`)}})}function $a(t,n){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,n],queryFn:()=>Ra((a==null?void 0:a.accessToken)||"",t,n),enabled:!!(a!=null&&a.accessToken)&&!!n})}function qa(t,n,a){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,n],queryFn:()=>Oa((r==null?void 0:r.accessToken)||"",t,n),enabled:(a==null?void 0:a.enabled)!==void 0?a.enabled&&!!(r!=null&&r.accessToken)&&!!n:!!(r!=null&&r.accessToken)&&!!n})}function Ya(t,n){return qa(ae.VISUAL,t,n)}function Tt(){const[t,n]=A.useState(new Map),a=A.useCallback((o,c)=>{n(i=>{const u=new Map(i),d=new Set(u.get(o)||[]);return c?d.add(c):(d.add("title"),d.add("description")),u.set(o,d),u})},[]),r=A.useCallback((o,c)=>{n(i=>{const u=new Map(i),d=new Set(u.get(o)||[]);return c?d.delete(c):d.clear(),d.size===0?u.delete(o):u.set(o,d),u})},[]),l=A.useCallback((o,c)=>{const i=t.get(o);return i?c?i.has(c):i.size>0:!1},[t]);return{startUpdating:a,stopUpdating:r,isUpdating:l}}function Ps(t,n,a){var h;const r=Ba(t),l=Pa(t,a),o=kt(t),c=za(t,n),i=Va(t),u=_a(),d=Ua(),m={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"};return{resources:((h=r.data)==null?void 0:h[m[t]])||[],isLoading:r.isLoading,isError:r.isError,isFetching:r.isFetching,error:r.error,createResource:l.mutate,updateResource:o.mutate,deleteResource:c.mutate,duplicateResource:i.mutate,shareResource:u.mutate,removeResourceShares:d.mutate,isCreating:l.isPending,isUpdating:o.isPending,isDeleting:c.isPending,isDuplicating:i.isPending,isSharing:u.isPending,isRemovingShares:d.isPending,isUpdatingShares:u.isPending,refetch:r.refetch}}function Ga(t,n){return Ps(ae.DASHBOARD,t,n)}function Ka(t,n){return Ps(ae.VISUAL,t,n)}function Ha(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return $e({mutationFn:async({visualId:a,data:r})=>{const l=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t==null?void 0:t.accessToken}`},body:JSON.stringify(r)});if(!l.ok)throw new Error("Failed to update visual");return l.json()},onSuccess:()=>{s.ue.success("Visual updated successfully"),n.invalidateQueries({queryKey:["visuals"]})},onError:()=>{s.ue.error("Failed to update visual")}})}function Qa({visual:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:u,onDuplicateVisual:d,onShareVisual:m,formatDate:h}){var v,D,C;const{selectVisual:f}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),x=s.useDashboardStore(I=>I.actions.setIsDashboardPanelOpen),[y,p]=A.useState(!1),[b,T]=A.useState(!1);A.useEffect(()=>{a?(p(!0),T(!0)):b&&(p(!1),T(!1))},[a,b]);const R=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Bs,{className:"h-3 w-3 text-purple-500"}):e.jsx(Ee,{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"}),w=()=>{f(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:w,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:I=>i==null?void 0:i(t.id,{title:I}),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:R()})]}),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:I=>i==null?void 0:i(t.id,{description:I}),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:I=>{I.stopPropagation(),o(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:y,onOpenChange:p,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:I=>I.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:I=>{I.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.preventDefault(),I.stopPropagation(),d(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),c==null||c(t)},children:[e.jsx(oa,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),m(t)},children:[e.jsx(Ee,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),u(t),x(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((v=t.ownership.createdBy)==null?void 0:v.type)==="tenant"||((D=t.ownership.createdBy)==null?void 0:D.type)==="organization"&&j)&&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:h(t.lastModified)})]})]})]})]})]})})]})]},t.id)}function Et({value:t,onChange:n,placeholder:a="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:a,value:t,onChange:r=>n(r.target.value),className:"pl-9"})]})}function ps({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:o=!0}){var u;const c=((u=a.find(d=>d.value===t))==null?void 0:u.label)||t,i=a.filter(d=>d.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(d=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:d.value,disabled:r}),n(d.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:d.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:d.description})]})},d.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function It({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>a(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(o=>{const c=t.find(u=>u.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(ps,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:u=>r(o.id,u),roleOptions:i}),e.jsx("button",{onClick:()=>a(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function At({usersToRemove:t,allUsers:n,onRemove:a}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>a(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>a(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function Mt({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const u=n.find(d=>d.id===i);return(u==null?void 0:u.name)||"Unknown User"},c=i=>{const u=l.find(d=>d.value===i);return(u==null?void 0:u.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(Ee,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function Lt(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=A.useRef(null);return A.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function Ne(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function Wa(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Rt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function Ja(t,n,a){const r=Rt(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function Xa({user:t}){return Rt(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 Za({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=Wa((r==null?void 0:r.type)||""),i=a.some(h=>h.id===t.id),u=a.find(h=>h.id===t.id),d=u?u.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(ps,{currentRole:d,onRoleChange:h=>{o(t.id,n.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:Ne(d,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function er({hasAccess:t,isUserRemoving:n,isSelected:a,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!n&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),n&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),a&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(ts,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function sr({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function tr({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],u=c.specificTenantUsers||[],d=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((f,g)=>{var p,b;const j=((p=n.find(T=>T.id===f.orgUserId))==null?void 0:p.name)||"Unknown User",x=((b=n.find(T=>T.id===f.orgUserId))==null?void 0:b.type)||"",y=Ne(f.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:y})]},g)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",u.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[u.slice(0,3).map((f,g)=>{var p,b;const j=((p=n.find(T=>T.id===f.tenantUserId))==null?void 0:p.name)||"Unknown User",x=((b=n.find(T=>T.id===f.tenantUserId))==null?void 0:b.type)||"",y=Ne(f.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:y})]},g)}),u.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",u.length-3," more users"]})]})]}),d.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:d.map((f,g)=>{const j=Ne(f.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((f,g)=>{const j=Ne(f.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((f,g)=>{const j=Ne(f.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),!i.length&&!u.length&&!d.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((u,d)=>{var g,j;const m=((g=n.find(x=>x.id===u.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((j=n.find(x=>x.id===u.tenantUserId))==null?void 0:j.type)||"",f=Ne(u.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:f})]},d)}),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((u,d)=>{const m=Ne(u.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},d)})})]}),!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,u)=>{var f,g;const d=((f=n.find(j=>j.id===i.tenantUserId))==null?void 0:f.name)||"Unknown User",m=((g=n.find(j=>j.id===i.tenantUserId))==null?void 0:g.type)||"",h=Ne(i.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:d}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},u)}),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,u)=>{const d=Ne(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:d})]},u)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function nr({isInitialLoading:t,searchQuery:n,availableUsers:a}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):a.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:n?"No users found matching your search.":"No users available to share with."}):null}function ar({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:u,usersToUpdate:d,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:f,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:o,disabled:t.id===(u==null?void 0:u.id),onCheckedChange:()=>{l?a?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(Xa,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(ps,{currentRole:n==null?void 0:n.role,onRoleChange:j=>f(t.id,n.role,j),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(Za,{user:t,userShare:n,usersToUpdate:d,currentUser:u,getRoleOptions:()=>i,handleUpdateAccess:f}),o&&!l&&e.jsx("div",{onClick:j=>j.stopPropagation(),children:e.jsx(ps,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:j=>g(t.id,j),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(er,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(sr,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Ot({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:u,handleUpdateAccess:d}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),j=s.useShareManagementActions(),x=c||(N=>{const w=m.some(D=>D.id===N),v=h.includes(N);w?j.removeSelectedUser(N):v?j.removeUserFromRemove(N):j.addSelectedUser({id:N,role:"VIEWER"})}),y=i||j.updateSelectedUserRole,p=u||j.addUserToRemove,b=d||((N,w,v)=>{j.addUserToUpdate({id:N,currentRole:w,newRole:v})}),T=l,R=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(T??[]).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(tr,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(T==null?void 0:T.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===T.length?j.setSelectedUsers([]):j.setSelectedUsers(T.map(N=>({id:N.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===T.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(nr,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:T||[]}),!n&&!a&&(T==null?void 0:T.length)>0&&T.map(N=>{const w=t?Ja(N,t,o):void 0,v=R.includes(N.id),D=!!w,C=D&&!v,I=m.some(k=>k.id===N.id),S=m.find(k=>k.id===N.id),O=r(N.type);return e.jsx(ar,{user:N,userShare:w,isUserRemoving:v,hasAccess:C,hasAccessFromAPI:D,isSelected:I,selectedUser:S,roleOptions:O,currentUser:o,usersToUpdate:f,handleUserToggle:x,handleRemoveAccess:p,handleUpdateAccess:b,handleUserRoleChange:y},N.id)})]})]})}function Ft({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(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 Pe=()=>[{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 rr({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const u=s.useShareCurrentMode(),d=Pe().filter(b=>b.value==="VIEWER"||b.value==="EDITOR"||b.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",h=l?l.newRole:m,f=n.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,j=o,x=m==="NONE"||!m,y=b=>{switch(b){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(da,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},p=b=>{r(m,b)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!j&&!x?"border-orange-300 bg-orange-50":f?"border-green-300 bg-green-50":j||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(Ee,{className:"h-5 w-5"}),"Share with All"," ",u==="allOrgUsers"?"Organization":u==="allTenantUsers"?"Tenant":u==="specificOrgUsers"?"Org":"Tenant"," ","Users",f&&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"}),(j||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:j||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:d.map(b=>e.jsxs(s.Button,{variant:h===b.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>p(b.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[y(b.value),e.jsx("span",{className:"font-medium",children:b.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:b.description})]},b.value))})]})})]})})}function Bt({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:u}){const d=x=>x==="OWNER"?"CONTRIBUTOR":x,h=n?{role:d(n.role)}:{role:"NONE"},f=i?{currentRole:d(i.currentRole),newRole:d(i.newRole)}:null,g=(x,y)=>{o(x,y)},j=()=>{c()};return e.jsx(rr,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:j,allUsersToUpdate:f,allUsersToRemove:u})}const lr=async(t,n={})=>{const a={};return n.search&&(a.search=n.search),n.type&&(a.type=n.type),n.active!==void 0&&(a.active=n.active.toString()),n.tenantId&&(a.tenantId=n.tenantId),n.limit&&(a.limit=n.limit.toString()),n.offset&&(a.offset=n.offset.toString()),n.page&&(a.page=n.page.toString()),n.pageSize&&(a.pageSize=n.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,a)};function or(t={}){var o,c,i;const{authToken:n,tokenProps:a}=s.useSemaphorContext(),r=(a==null?void 0:a.endUserId)||(a==null?void 0:a.orgUserId),l=s.useQuery({queryKey:["unified-users",t],queryFn:()=>lr((n==null?void 0:n.accessToken)||"",t),enabled:!!(n!=null&&n.accessToken)&&!!r,retry:(u,d)=>d instanceof Error&&d.message.includes("401")||d instanceof Error&&d.message.includes("403")?!1:u<2,retryDelay:u=>Math.min(1e3*2**u,3e4)});return{users:((o=l.data)==null?void 0:o.users)||[],userContext:(c=l.data)==null?void 0:c.userContext,total:((i=l.data)==null?void 0:i.total)||0,isLoading:l.isLoading,isError:l.isError,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function Be(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=ae.DASHBOARD,userType:l,tenantId:o}=t,c=A.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading:u,isError:d}=or(c),m=$a(r,a);return{allUsers:i,isLoadingUsers:u,isErrorLoadingUsers:d,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function ir({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var X,K;const i=s.useShareSelectedTab(),u=s.useShareSelectedTenant(),{searchQuery:d,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),f=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),j=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),y=s.useShareOrgWideRole(),p=s.useShareManagementActions(),[b,T]=A.useState("specific_users"),R=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},N=()=>{if(i==="tenant"&&u)return u},{allUsers:w,existingShares:v,isLoadingUsers:D}=Be({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:R(),tenantId:N()});A.useEffect(()=>{p.setCurrentContext("org-tab"),p.setCurrentMode(b==="all_users"?"allOrgUsers":"specificOrgUsers")},[p,b]);const C=$=>{var U,Z;const Y=$;if(T(Y),r==null||r(Y),p.setCurrentContext("org-tab"),Y==="specific_users")p.setCurrentMode("specificOrgUsers");else if(Y==="all_users"){p.setCurrentMode("allOrgUsers");const q=(Z=(U=v==null?void 0:v.shares)==null?void 0:U.orgUsersOnly)==null?void 0:Z[0];q&&q.role!==void 0&&p.setOrgWideRole(q.role)}},I=w.filter($=>$.name.toLowerCase().includes(d.toLowerCase())||$.email.toLowerCase().includes(d.toLowerCase())),S=w.filter($=>f.some(Y=>Y.id===$.id)),O=$=>{var q,P;const Y=f.some(W=>W.id===$),U=g.includes($),Z=(P=(q=v==null?void 0:v.shares)==null?void 0:q.specificOrgUsers)==null?void 0:P.some(W=>W.orgUserId===$);Y?p.removeSelectedUser($):U?p.removeUserFromRemove($):Z||p.addSelectedUser({id:$,role:"VIEWER"})},k=($,Y)=>{p.updateSelectedUserRole($,Y)},E=$=>{p.addUserToRemove($),p.removeSelectedUser($)},M=$=>{p.removeUserFromRemove($)},B=$=>{p.removeUserFromUpdate($)},L=($,Y)=>{p.setOrgWideRole(Y)},F=()=>{p.setOrgWideRole((V==null?void 0:V.role)||"NONE")},V=(K=(X=v==null?void 0:v.shares)==null?void 0:X.orgUsersOnly)==null?void 0:K[0];A.useEffect(()=>{b==="all_users"&&V&&V.role!==void 0&&p.setOrgWideRole(V.role)},[b,V,p]);const z=D,J=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(Ft,{shareType:b,onShareTypeChange:C,currentUser:a,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 ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(Ee,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),b==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Et,{value:d,onChange:m}),e.jsx(It,{selectedUsers:f,selectedUserObjects:S,onRemove:O,onRoleChange:k,getRoleOptions:Pe}),e.jsx(At,{usersToRemove:g,allUsers:I,onRemove:M}),e.jsx(Mt,{usersToUpdate:j,allUsers:I,onRemove:B,getRoleOptions:Pe}),e.jsx(Ot,{existingShares:v,isInitialLoading:z,isSearching:J,resource:t,onShare:()=>{},getRoleOptions:Pe,allUsers:I,currentUser:a,handleUserToggle:O,handleUserRoleChange:k,handleRemoveAccess:E,handleUpdateAccess:($,Y,U)=>{p.addUserToUpdate({id:$,currentRole:Y,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Bt,{currentUser:a,currentShare:V,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:L,onRemoveAccess:F,allUsersToUpdate:x==="allOrgUsers"&&y!==((V==null?void 0:V.role)||"NONE")?{currentRole:(V==null?void 0:V.role)||"NONE",newRole:y}:null,allUsersToRemove:x==="allOrgUsers"&&(V==null?void 0:V.role)===void 0})})]}):null}function lt({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var q;const{searchQuery:i,debouncedSearchQuery:u,setSearchQuery:d}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareCurrentMode(),j=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),y=s.useShareSelectedTenant(),p=s.useShareManagementActions(),{data:b,isLoading:T}=Fa({enabled:(a==null?void 0:a.type)==="organization"}),[R,N]=A.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(p.setCurrentContext("tenant-dialog"),p.setCurrentMode("specificTenantUsers")):(p.setCurrentContext("tenant-tab"),p.setCurrentMode("allTenants"))},[p,a==null?void 0:a.type]);const w=P=>{var te,_,ee,le;N(P);let W;if(P==="specific_tenant_users"?W="specific_users":P==="all_tenant_users"||P==="all_tenants"?W="all_users":W="specific_users",r==null||r(W),(a==null?void 0:a.type)==="tenant"?(p.setCurrentContext("tenant-dialog"),P==="specific_tenant_users"?p.setCurrentMode("specificTenantUsers"):P==="all_tenant_users"&&(p.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&p.setSelectedTenant(a.tenantId))):(p.setCurrentContext("tenant-tab"),P==="specific_tenant_users"?p.setCurrentMode("specificTenantUsers"):P==="all_tenant_users"?p.setCurrentMode("allTenantUsers"):P==="all_tenants"&&p.setCurrentMode("allTenants")),P==="all_tenant_users"){const H=(_=(te=C==null?void 0:C.shares)==null?void 0:te.tenantWide)==null?void 0:_[0];H&&H.role!==void 0&&p.setTenantWideRole(H.role)}else if(P==="all_tenants"){const H=(le=(ee=C==null?void 0:C.shares)==null?void 0:ee.allTenantsOnly)==null?void 0:le[0];H&&H.role!==void 0&&p.setAllTenantsRole(H.role)}},v=P=>{p.setSelectedTenant(P)},{allUsers:D,existingShares:C,isLoadingUsers:I,isErrorLoadingUsers:S,isLoadingShares:O,isErrorLoadingShares:k}=Be({debouncedSearchQuery:u,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:y}),E=P=>{var ee,le;const W=m.some(H=>H.id===P),te=h.includes(P),_=(le=(ee=C==null?void 0:C.shares)==null?void 0:ee.specificTenantUsers)==null?void 0:le.some(H=>H.tenantUserId===P);W?p.removeSelectedUser(P):te?p.removeUserFromRemove(P):_||p.addSelectedUser({id:P,role:"VIEWER"})},M=(P,W)=>{p.updateSelectedUserRole(P,W)},B=P=>{p.addUserToRemove(P),p.removeSelectedUser(P)},L=P=>{p.removeUserFromRemove(P)},F=P=>{p.removeUserFromUpdate(P)},V=(P,W,te)=>{p.addUserToUpdate({id:P,currentRole:W,newRole:te})},z=(P,W)=>{R==="all_tenant_users"?p.setTenantWideRole(W):R==="all_tenants"&&p.setAllTenantsRole(W)},J=()=>{R==="all_tenant_users"?p.setTenantWideRole("VIEWER"):R==="all_tenants"&&p.setAllTenantsRole("VIEWER")},K=(()=>{var P,W,te,_;return g==="allTenants"?(W=(P=C==null?void 0:C.shares)==null?void 0:P.allTenantsOnly)==null?void 0:W[0]:g==="allTenantUsers"?(_=(te=C==null?void 0:C.shares)==null?void 0:te.tenantWide)==null?void 0:_[0]:null})();A.useEffect(()=>{var P,W,te,_;if(R==="all_tenant_users"){const ee=(W=(P=C==null?void 0:C.shares)==null?void 0:P.tenantWide)==null?void 0:W[0];ee&&ee.role!==void 0&&p.setTenantWideRole(ee.role)}else if(R==="all_tenants"){const ee=(_=(te=C==null?void 0:C.shares)==null?void 0:te.allTenantsOnly)==null?void 0:_[0];ee&&ee.role!==void 0&&p.setAllTenantsRole(ee.role)}},[R,C,p]);const $=D.filter(P=>m.some(W=>W.id===P.id)),Y=I||O,U=S||k,Z=()=>(a==null?void 0:a.type)==="tenant"||R==="all_tenants"?!0:y&&(R==="specific_tenant_users"||R==="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&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Ft,{shareType:R,onShareTypeChange:w,currentUser:a,options:(a==null?void 0:a.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(Ee,{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(st,{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"})}]}),(a==null?void 0:a.type)==="organization"&&(R==="specific_tenant_users"||R==="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:y||"",onValueChange:v,disabled:T,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:T?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(q=b==null?void 0:b.tenants)==null?void 0:q.map(P=>e.jsx(s.SelectItem,{value:P.id,children:P.name},P.id))})]})]}),Z()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Et,{value:i,onChange:d}),e.jsx(It,{selectedUsers:m,selectedUserObjects:$,onRemove:P=>E(P),onRoleChange:M,getRoleOptions:Pe}),e.jsx(At,{usersToRemove:h,allUsers:D,onRemove:L}),e.jsx(Mt,{usersToUpdate:f,allUsers:D,onRemove:F,getRoleOptions:Pe}),e.jsx(Ot,{existingShares:C,isInitialLoading:!!Y,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Pe,allUsers:D,currentUser:a,handleUserToggle:E,handleUserRoleChange:M,handleRemoveAccess:B,handleUpdateAccess:V})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Bt,{currentUser:a,currentShare:K,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:z,onRemoveAccess:J,allUsersToUpdate:g==="allTenantUsers"&&((K==null?void 0:K.role)===void 0||j!==K.role)||g==="allTenants"&&((K==null?void 0:K.role)===void 0||x!==K.role)?{currentRole:(K==null?void 0:K.role)||"VIEWER",newRole:g==="allTenantUsers"?j:x}:null,allUsersToRemove:g==="allTenantUsers"&&(K==null?void 0:K.role)===void 0||g==="allTenants"&&(K==null?void 0:K.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(R==="specific_tenant_users"||R==="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(st,{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 Pt=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),u=s.useShareTenantWideRole(),d=A.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:u}),[t,n,a,r,l,o,c,i,u]),m=A.useMemo(()=>f=>s.validateShareData(f),[]),h=A.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!o)return!1}else if(n==="specificTenantUsers")return o?a.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||l.length>0:!0}return!1},[t,n,a,r,l,o]);return{buildShareData:d,validateShareData:m,isCurrentStateValid:h,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:u}};function ot({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:u,onRemoveAccess:d}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const g=s.useShareSelectedTenant();s.useShareSelectedTab();const j=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),y=s.useShareTenantWideRole(),{buildShareData:p,validateShareData:b,isCurrentStateValid:T}=Pt(),R=a||r||l,N=()=>{var I,S,O,k;if(R)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const E=m.length+h.length+f.length;return E===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${E} user${E!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}else if(i==="all_users"){if(!u||u.role===void 0)return"Share with All Users";const E=u.role;return j===E?"Remove Access":"Update Access"}else if(i==="all_tenants"){const E=(S=(I=n==null?void 0:n.shares)==null?void 0:I.allTenantsOnly)==null?void 0:S[0];if(!E||E.role===void 0)return"Share with All Tenants";const M=E.role;return x===M?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const E=(k=(O=n==null?void 0:n.shares)==null?void 0:O.tenantWide)==null?void 0:k[0];if(!E||E.role===void 0)return"Share with All Tenant Users";const M=E.role;return y===M?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const E=m.length+h.length+f.length;return E===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${E} user${E!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}return"Share"},w=()=>R||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!T,v=()=>{const I=p();I&&b(I)&&o(I)},D=()=>{var I,S,O,k;if(i==="all_users")if(!u||u.role===void 0){const E=p();E&&b(E)&&o(E)}else{const E=u.role;if(j===E)d==null||d();else{const B=p();if(B&&b(B)){const L={...B,updateAccess:!0};o(L)}}}else if(i==="all_tenants"){const E=(S=(I=n==null?void 0:n.shares)==null?void 0:I.allTenantsOnly)==null?void 0:S[0];if(!E||E.role===void 0){const M=p();M&&b(M)&&o(M)}else{const M=E.role;if(x===M)d==null||d();else{const L=p();if(L&&b(L)){const F={...L,updateAccess:!0};o(F)}}}}else if(i==="all_tenant_users"){const E=(k=(O=n==null?void 0:n.shares)==null?void 0:O.tenantWide)==null?void 0:k[0];if(!E||E.role===void 0){const M=p();M&&b(M)&&o(M)}else{const M=E.role;if(y===M)d==null||d();else{const L=p();if(L&&b(L)){const F={...L,updateAccess:!0};o(F)}}}}},C=()=>{var I,S,O,k;if(i==="all_users"){if(!u||u.role===void 0)return"default";const E=u.role;return j===E?"destructive":"default"}else if(i==="all_tenants"){const E=(S=(I=n==null?void 0:n.shares)==null?void 0:I.allTenantsOnly)==null?void 0:S[0];if(!E||E.role===void 0)return"default";const M=E.role;return x===M?"destructive":"default"}else if(i==="all_tenant_users"){const E=(k=(O=n==null?void 0:n.shares)==null?void 0:O.tenantWide)==null?void 0:k[0];if(!E||E.role===void 0)return"default";const M=E.role;return y===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:R,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||f.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||R,variant:"default",children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ts,{className:"mr-2 h-4 w-4"}),!R&&N()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:D,disabled:w(),variant:C(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ee,{className:"mr-2 h-4 w-4"}),!R&&N()]})]})}function cr({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const u=s.useShareSelectedUsers(),d=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:g,isCurrentStateValid:j}=Pt(),x=n||a||r,y=()=>{if(x)return"Updating...";if(c==="specific_users"){if(u.length===0&&d.length===0&&m.length===0)return"Select users to share with";const N=u.length+d.length+m.length;return N===0?"Select users to share with":u.length>0&&d.length>0?`Update access for ${N} user${N!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Remove access for ${d.length} user${d.length!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:m.length>0&&u.length===0&&d.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${N} user${N!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const N=i.role;return h===N?"Remove Access":"Update Access"}return"Share"},p=()=>x||!t?!0:!j,b=()=>{const N=f();N&&g(N)&&l(N)},T=()=>{if(!i||i.role==="NONE"){const N=f();N&&g(N)&&l(N)}else{const N=i.role;if(h===N){const v=f();if(v&&g(v)){const D={...v,removeAccess:!0};l(D)}}else{const v=f();if(v&&g(v)){const D={...v,updateAccess:!0};l(D)}}}},R=()=>!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:(u.length>0||d.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:b,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(ts,{className:"mr-2 h-4 w-4"}),!x&&y()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:T,disabled:p(),variant:R(),children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ts,{className:"mr-2 h-4 w-4"}),!x&&y()]})]})}function zt({resource:t,resourceType:n,isSharing:a,isRemoving:r,isUpdating:l,onClose:o,onShare:c,onRemoveAccess:i}){var v,D,C,I;const{currentUser:u}=Ie(),[d,m]=A.useState("specific_users"),[h,f]=A.useState("specific_users"),g=s.useShareManagementActions(),j=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:y}=Be({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:p}=Be({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),b=(D=(v=y==null?void 0:y.shares)==null?void 0:v.tenantWide)==null?void 0:D[0],T=(I=(C=p==null?void 0:p.shares)==null?void 0:C.orgUsersOnly)==null?void 0:I[0],R=()=>{if(j==="org")return h;switch(x){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},N=A.useCallback(()=>{g.resetShareState(),o()},[g,o]),w=(u==null?void 0:u.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:N,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(ts,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:w?"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."})]}),w?e.jsxs(s.Tabs,{value:j,onValueChange:S=>{const O=S;g.setSelectedTab(O),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(ir,{resource:t,resourceType:n,currentUser:u,onShareTabTypeChange:f,isSharing:a,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(lt,{resource:t,resourceType:n,currentUser:u,onShareTabTypeChange:S=>m(S),isSharing:a,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(lt,{resource:t,resourceType:n,currentUser:u,onShareTabTypeChange:S=>m(S),isSharing:a,isUpdating:l,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:w?j==="org"?e.jsx(ot,{resource:t,existingShares:p,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:h,currentAllUsersShare:T,onRemoveAccess:i}):e.jsx(ot,{resource:t,existingShares:y,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:R(),currentAllUsersShare:b,onRemoveAccess:i}):e.jsx(cr,{resource:t,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:d,currentAllUsersShare:b,onRemoveAccess:i})})]})})}function ge(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Oe(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Vt(t,n,a){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:u}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=ge(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(d,{onSuccess:()=>{u()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h}=t;if(d&&d.length>0){const f=ge(r,l,d.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{u()}})}if(m&&m.length>0){const f=Oe(r,l,m.map(g=>{var x,y;const j=(y=(x=i==null?void 0:i.shares)==null?void 0:x.specificOrgUsers)==null?void 0:y.find(p=>p.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(f,{onSuccess:()=>{u()}})}h&&h.length>0&&h.forEach(f=>{const g=ge(r,l,[{scope:"specific_org_user",orgUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{u()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=ge(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(d,{onSuccess:()=>{u()}})}else if(t.mode==="allTenantUsers"){const d=ge(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{u()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h,tenantId:f}=t;if(m&&m.length>0){const g=Oe(r,l,m.map(j=>{var y,p;const x=(p=(y=i==null?void 0:i.shares)==null?void 0:y.specificTenantUsers)==null?void 0:p.find(b=>b.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,tenantId:f,role:(x==null?void 0:x.role)||"VIEWER"}}));c(g,{onSuccess:()=>{u()}})}if(h&&h.length>0&&h.forEach(g=>{const j=ge(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:f,role:g.newRole}]);o(j,{onSuccess:()=>{u()}})}),d&&d.length>0){const g=ge(r,l,d.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,tenantId:f,role:j.role})));o(g,{onSuccess:()=>{u()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=Oe(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(d,{onSuccess:()=>{u()}})}else if(t.updateAccess){const d=ge(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{u()}})}else{const d=ge(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{u()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h}=t;if(d&&d.length>0){const f=ge(r,l,d.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{u()}})}if(m&&m.length>0){const f=Oe(r,l,m.map(g=>{var x,y;const j=(y=(x=i==null?void 0:i.shares)==null?void 0:x.specificTenantUsers)==null?void 0:y.find(p=>p.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(f,{onSuccess:()=>{u()}})}h&&h.length>0&&h.forEach(f=>{const g=ge(r,l,[{scope:"specific_tenant_user",tenantUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{u()}})})}break}}function _t(t,n,a,r){var d,m,h,f,g,j;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:u}=r;if(o)if(t.length>0){const x=Oe(l,o,t.map(y=>{var b,T;const p=(T=(b=i==null?void 0:i.shares)==null?void 0:b.specificTenantUsers)==null?void 0:T.find(R=>R.tenantUserId===y);return{scope:"specific_tenant_user",tenantUserId:y,role:(p==null?void 0:p.role)||"VIEWER"}}));c(x,{onSuccess:()=>{u()},onError:y=>{console.error("Remove access failed:",y)}})}else{const x=n==="tenant"&&a==="allTenants",y=n==="tenant"&&a==="allTenantUsers";if(x){const p=(m=(d=i==null?void 0:i.shares)==null?void 0:d.allTenantsOnly)==null?void 0:m[0];if(p){const b=Oe(l,o,[{scope:"all_tenants_only",role:p.role}]);c(b,{onSuccess:()=>{u()},onError:T=>{console.error("Remove all-tenants access failed:",T)}})}}else if(y){const p=(f=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:f[0];if(p){const b=Oe(l,o,[{scope:"all_tenant_users",role:p.role}]);c(b,{onSuccess:()=>{u()},onError:T=>{console.error("Remove all-tenant-users access failed:",T)}})}}else{const p=(j=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:j[0];if(p){const b=Oe(l,o,[{scope:"org_users_only",role:p.role}]);c(b,{onSuccess:()=>{u()},onError:T=>{console.error("Remove org-wide access failed:",T)}})}}}}function dr(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=Ie(),{existingShares:u}=Be({debouncedSearchQuery:"",resourceId:t||"",resourceType:ae.DASHBOARD,userType:"tenant"}),d=A.useCallback(()=>{r.resetUserSelections()},[r]),m=A.useCallback(f=>{if(!t)return;const g={resourceType:ae.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:u,resetUserSelections:d};Vt(f,g,i)},[t,n,a,u,d,i]),h=A.useCallback(()=>{if(!t)return;const f={resourceType:ae.DASHBOARD,resourceId:t,removeMutation:a,existingShares:u,resetUserSelections:d};_t(l,o||"",c||"",f)},[t,n,a,u,d,l,o,c]);return{handleShareSubmit:m,handleRemoveAccess:h}}function ur(t,n,a){const{currentUser:r}=Ie(),l=s.useShareManagementActions(),o=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),i=s.useShareCurrentMode(),{existingShares:u}=Be({debouncedSearchQuery:"",resourceId:t||"",resourceType:ae.VISUAL,userType:"tenant"}),d=A.useCallback(()=>{l.resetUserSelections()},[l]),m=A.useCallback(f=>{if(!t)return;const g={resourceType:ae.VISUAL,resourceId:t,shareMutation:n,removeMutation:a,existingShares:u,resetUserSelections:d};Vt(f,g,r)},[t,n,a,u,d,r]),h=A.useCallback(()=>{if(!t)return;const f={resourceType:ae.VISUAL,resourceId:t,removeMutation:a,existingShares:u,resetUserSelections:d};_t(o,c||"",i||"",f)},[t,n,a,u,d,o,c,i]);return{handleShareSubmit:m,handleRemoveAccess:h}}function mr(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function zs(t){const[n,a]=A.useState(null),[r,l]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const u=await import(i);if(typeof u.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>u.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),a(null)}})()},[t]),n}function hr(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return n}}return t[0].id}async function it(t,n,a){if(!t||!n)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",n],l=a.getQueryData(r);if(l)return console.log("Using cached visual data for:",n),{data:l,fromCache:!0};console.log("Fetching visual data from network for:",n);const o=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return a.setQueryData(r,i),s.ue.dismiss(o),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(o),c}}function xr(t,n,a,r,l){const o=t.frameObject;n(o);const c=o.cards.find(i=>i.id===o.activeCardId);c&&a(c),r(!0),l(!0)}function pr(){var f;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=zs(((f=a.customCardPreferences)==null?void 0:f.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),u=s.useEditorStore(g=>g.selectedConnectionId),d=s.useEditorStore(g=>g.isShowingVisual),m=a.sql;return{getUpdatedFrame:A.useCallback(()=>{var p;let g=m;m&&!m.includes("{{")&&(g=mr(m),t(g));const j=(p=r==null?void 0:r.getState())==null?void 0:p.settings,x={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:u,sql:g,customCfg:d?a.customCfg:null,...j&&{customCardPreferences:{...a.customCardPreferences,settings:j}}},y=n.cards.map(b=>b.id===a.id?x:b);return{...n,cards:y,activeCardId:hr(y,n.activeCardId)}},[a,n,d,l,o,c,i,u,t,r,m])}}function Vs(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient(),a=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:l,setCard:o}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:u,addFrame:d,setIsDashboardPanelOpen:m}=s.useDashboardActions(),h=s.useDashboardStore(x=>x.selectedSheetId),f=Ya((a==null?void 0:a.id)||"",{enabled:!!(a!=null&&a.id)&&!!(t!=null&&t.accessToken)}),g=A.useCallback(async x=>{try{r(x);const{data:y,fromCache:p}=await it((t==null?void 0:t.accessToken)||"",x.id,n);return xr(y,l,o,c,i),{success:!0,fromCache:p}}catch(y){return console.error("Error editing visual:",y),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n,r,l,o,c,i]),j=A.useCallback(async x=>{try{if(r(x),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:y,fromCache:p}=await it((t==null?void 0:t.accessToken)||"",x.id,n),b=y.frameObject;if(!b)return{success:!1,error:"Visual has no frame data"};const T={...b,id:s.v4()};return d(h,T,"end"),c(!0),u(T.id),m(!1),{success:!0,fromCache:p}}catch(y){return console.error("Error adding visual:",y),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n,r,h,d,c,u,m]);return{visual:f.data,isLoading:f.isLoading,isError:f.isError,error:f.error,handleEditLibraryVisual:g,handleAddLibraryVisual:j,getUpdatedFrame:pr().getUpdatedFrame,refetch:f.refetch}}function fr(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),[l,o]=A.useState(""),[c,i]=A.useState(""),[u,d]=A.useState(!1),[m,h]=A.useState(null),[f,g]=A.useState(!1),[j,x]=A.useState(null),[y,p]=A.useState(null),{setIsDashboardEditing:b,setIsVisualEditing:T}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:N}=Vs(),{resources:w,isLoading:v,isError:D,createResource:C,updateResource:I,deleteResource:S,duplicateResource:O,shareResource:k,isCreating:E,isDeleting:M,removeResourceShares:B,isSharing:L,isRemovingShares:F,isUpdatingShares:V}=Ka(()=>{g(!1),x(null)},()=>{r(!1),o(""),i("")}),{handleShareSubmit:z,handleRemoveAccess:J}=ur((m==null?void 0:m.id)||null,k,B);Ie();const X=w.filter(Q=>{var re,de;return((re=Q==null?void 0:Q.title)==null?void 0:re.toLowerCase().includes(t.toLowerCase()))||((de=Q==null?void 0:Q.description)==null?void 0:de.toLowerCase().includes(t.toLowerCase()))}),K=Q=>new Date(Q).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{l.trim()&&C({title:l,description:c,isPrivate:!1})},Y=Q=>{x(Q),g(!0)},U=()=>{j&&S(j.id)},{startUpdating:Z,stopUpdating:q,isUpdating:P}=Tt(),W=(Q,re)=>{const de=re.title!==void 0?"title":"description";Z(Q,de),I({resourceId:Q,data:re},{onSuccess:()=>{q(Q,de)},onError:()=>{q(Q,de)}})},te=Q=>{p(Q),O(Q,{onSettled:()=>p(null)})},_=Q=>{R(Q)},ee=Q=>{N(Q)},le=Q=>{const re=w.find(de=>de.id===Q);re&&I({resourceId:Q,data:{isPrivate:!re.isPrivate}})},H=Q=>{h(Q),d(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),Be({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:ae.VISUAL,userType:"tenant"}),v?e.jsx(Dt,{}):D?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:a?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:Q=>o(Q.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:Q=>i(Q.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||E,children:E?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:E,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:E,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),E?"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:Q=>n(Q.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:X.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(s.ChartPie,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):X.map(Q=>e.jsx(Qa,{visual:Q,onAddVisual:ee,onEditVisual:_,onUpdateVisual:W,onDeleteClick:Y,onDuplicateVisual:te,onTogglePrivacy:le,onShareVisual:H,isDeleting:M,isDuplicating:y===Q.id,isTitleUpdating:P(Q.id,"title"),isDescriptionUpdating:P(Q.id,"description"),formatDate:K},Q.id))})}),u&&m&&e.jsx(zt,{resource:m,resourceType:ae.VISUAL,onShare:z,isSharing:L,isRemoving:F,isUpdating:V,onClose:()=>{d(!1),h(null)},onRemoveAccess:J}),e.jsx(s.AlertDialog,{open:f,onOpenChange:Q=>{!Q&&M||(g(Q),Q||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 "',j==null?void 0:j.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:M,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:M,children:M?"Deleting...":"Delete"})]})]})})]})}function gr({dashboard:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:u,onShareDashboard:d,formatDate:m,onDashboardItemClick:h}){var v,D,C;const{selectDashboard:f}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),[x,y]=A.useState(!1),[p,b]=A.useState(!1),T=s.useDashboardStore(I=>I.actions.setIsDashboardPanelOpen);A.useEffect(()=>{a?(y(!0),b(!0)):p&&(y(!1),b(!1))},[a,p]);const R=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Bs,{className:"h-3 w-3 text-purple-500"}):e.jsx(Ee,{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.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),w=()=>{f(t),o(t.id),h==null||h(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:w,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:I=>c==null?void 0:c(t.id,{title:I}),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:R()})]}),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:I=>c==null?void 0:c(t.id,{description:I}),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:x,onOpenChange:y,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:I=>I.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:I=>{I.preventDefault(),I.stopPropagation(),u(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),d(t)},children:[e.jsx(Ee,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),i(t),T(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((v=t.ownership.createdBy)==null?void 0:v.type)==="tenant"||((D=t.ownership.createdBy)==null?void 0:D.type)==="organization"&&j)&&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:m(t.lastModified)})]})]})]})]})})})]})]},t.id)}function jr({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 yr(t){const[n,a]=A.useState(""),[r,l]=A.useState(!1),[o,c]=A.useState(""),[i,u]=A.useState(""),[d,m]=A.useState(!1),[h,f]=A.useState(null),[g,j]=A.useState(!1),[x,y]=A.useState(null),[p,b]=A.useState(null),T=s.useManagementStore(H=>H.lastSelectedDashboard),R=s.useManagementStore(H=>H.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:N,isLoading:w,isError:v,createResource:D,updateResource:C,deleteResource:I,duplicateResource:S,isCreating:O,isDeleting:k,isSharing:E,isRemovingShares:M,isUpdatingShares:B,shareResource:L,removeResourceShares:F}=Ga(()=>{j(!1),y(null),T&&R(T)},()=>{l(!1),c(""),u("")}),{handleShareSubmit:V,handleRemoveAccess:z}=dr((h==null?void 0:h.id)||null,L,F),{currentUser:J}=Ie(),X=N.filter(H=>{var Q,re;return((Q=H==null?void 0:H.title)==null?void 0:Q.toLowerCase().includes(n.toLowerCase()))||((re=H==null?void 0:H.description)==null?void 0:re.toLowerCase().includes(n.toLowerCase()))}),K=H=>new Date(H).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{o.trim()&&D({title:o,description:i,isPrivate:!1})},Y=H=>{var Q;(Q=t.onLoadDashboard)==null||Q.call(t,H)},U=H=>{y(H),j(!0)},Z=()=>{x&&I(x.id)},q=H=>{b(H),S(H,{onSettled:()=>b(null)})},{startUpdating:P,stopUpdating:W,isUpdating:te}=Tt(),_=(H,Q)=>{const re=Q.title!==void 0?"title":"description";P(H,re),C({resourceId:H,data:Q},{onSuccess:()=>{W(H,re)},onError:()=>{W(H,re)}})},ee=H=>{const Q=N.find(re=>re.id===H);Q&&C({resourceId:H,data:{isPrivate:!Q.isPrivate}})},le=H=>{f(H),J==null||J.type,m(!0)};return Be({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ae.DASHBOARD,userType:"tenant"}),w?e.jsx(Dt,{}):v?e.jsx(jr,{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:H=>c(H.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:H=>u(H.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||O,children:O?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),u("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:O,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"h-8 w-full",size:"sm",disabled:O,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),O?"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:n,onChange:H=>a(H.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:X.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx($n,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):X.map(H=>e.jsx(gr,{dashboard:H,isDeleting:k,isDuplicating:p===H.id,isTitleUpdating:te(H.id,"title"),isDescriptionUpdating:te(H.id,"description"),onLoadDashboard:Y,onEditDashboard:t.onEditDashboard,onUpdateDashboard:_,onDeleteClick:U,onDuplicateDashboard:q,onTogglePrivacy:ee,onShareDashboard:le,formatDate:K,onDashboardItemClick:t.onDashboardItemClick},H.id))})}),d&&h&&e.jsx(zt,{resource:h,resourceType:ae.DASHBOARD,onShare:V,isSharing:E,isRemoving:M,isUpdating:B,onClose:()=>{m(!1),f(null)},onRemoveAccess:z}),e.jsx(s.AlertDialog,{open:g,onOpenChange:H=>{!H&&k||(j(H),H||y(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:k,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:H=>{H.preventDefault(),H.stopPropagation(),Z()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:k,children:k?"Deleting...":"Delete"})]})]})})]})}function Ut({isOpen:t,onClose:n,className:a,onDashboardItemClick:r}){s.useDashboardStore(g=>g.dashboard);const{setDashboard:l,addSheet:o}=s.useDashboardStore(g=>g.actions),{currentUser:c}=Ie(),i=c,[u,d]=s.useLocalStorageState("resource-management-active-tab","dashboards"),m=Lt(n,{enabled:t}),h=g=>{},f=g=>{console.log("Editing dashboard:",g)};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":"hidden -translate-x-full",a),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:i&&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:i.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:i.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:i.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:i.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.email}),i.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(i.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",i.id]})]})})]})})}),e.jsx(s.IconButton,{className:"h-6 p-1 text-muted-foreground hover:text-foreground",onClick:n,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:u,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(yr,{onLoadDashboard:h,onEditDashboard:f,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(fr,{})})]})})]})})}function vr(){var Z,q;const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{isLocalDev:a}=s.useDashboardPreferences();s.useDashboardStore(P=>P.theme);const r=s.useDashboardStore(P=>P.lenses),l=s.useDashboardStore(P=>P.selectedLensId),o=r==null?void 0:r.find(P=>P.id===l),c=s.useDashboardStore(P=>P.dashboard);s.useDashboardStore(P=>P.selectedSheetId);const i=s.useDashboardStore(P=>P.isDashboardEditing),u=s.useEditorStore(P=>P.card),d=s.useEditorStore(P=>P.selectedConnectionId),[m,h]=A.useState(!1),f=s.useDashboardStore(P=>P.isDashboardPanelOpen),g=s.useDashboardStore(P=>P.actions.setIsDashboardPanelOpen),j=s.useDashboardStore(P=>P.filterValues),x=s.useDashboardStore(P=>P.isVisualEditing),y=s.useManagementStore(P=>P.selectedDashboard),p=s.useManagementStore(P=>P.initialDashboard),b=y?(q=y==null?void 0:y.permissions)==null?void 0:q.canEdit:(Z=p==null?void 0:p.permissions)==null?void 0:Z.canEdit,T=s.useDashboardStore(P=>P.showFilters),R=s.useDashboardStore(P=>P.showDashboardJSON),N=s.useDashboardStore(P=>P.onSaveFunction),w=s.useDashboardStore(P=>P.actions.setShowFilters),{addFrame:v,setSelectedFrameId:D}=s.useDashboardStore(P=>P.actions),{getSelectedSheet:C,setIsDashboardEditing:I,setShowDashboardJSON:S}=s.useDashboardStore(P=>P.actions),O=C(),{setInitialDashboard:k}=s.useManagementStore(P=>P.actions),{resources:E}=Ps(ae.DASHBOARD);A.useEffect(()=>{if(E&&E.length>0){const P=c==null?void 0:c.id;if(P){const W=E.find(te=>te.id===P);W&&k(W)}}},[E,c==null?void 0:c.id,k]);const M=n.orgUserId||n.tenantId,B=i&&!x&&M&&b;function L(){var _,ee;const P=u.dataSource;if(P)return P;const W=(ee=(_=c.aiContext)==null?void 0:_.selectedEntities)==null?void 0:ee[0],te=W==null?void 0:W.type;if(W)return{connectionId:W.connectionId,connectionType:W.connectionType,type:te,selectedEntities:[W]}}const F=()=>{if(!i||!O)return;const W={dataSource:L(),mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},te={id:s.v4(),cards:[W],activeCardId:W.id};v(O.id,te),D(te.id)},V=()=>{I(!0)},[z,J]=A.useState(!1),X=kt(ae.DASHBOARD);async function K(){const P=xs(c);J(!0);const W={template:P};X.mutate({resourceId:P.id,data:W},{onSuccess:()=>{J(!1),s.ue.success("Dashboard saved!")},onError:()=>{J(!1),s.ue.error("Failed to save dashboard")}})}async function $(){if(h(!0),!l||!o)return;const P=xs(c),W=JSON.stringify(P),te={...o,template:W,filterValues:j};await Ls(te,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),N==null||N(P),h(!1)}if(x)return null;const Y=(o==null?void 0:o.name)||c.title,U=n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[U&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>g(!0),className:"h-7 p-2",children:e.jsx(Hn,{className:"h-4 w-4"})}),!x&&e.jsx(s.Label,{children:Y})]}),e.jsxs("div",{className:"flex gap-2",children:[a&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:s.invalidateToken,className:"h-7 p-2",children:e.jsx(ua,{className:"h-4 w-4"})}),!x&&e.jsx(wa,{}),!x&&e.jsx(wt,{}),i&&!x&&M&&a&&e.jsx(Ca,{}),!x&&M&&a&&e.jsx(Sa,{}),i&&!x&&M&&o&&a&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:m,onClick:$,size:"sm",children:[e.jsx(Ms,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),i&&!x&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!i,onClick:F,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!x&&!i&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:V,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),i&&!x&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{I(!1),S(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),B&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:z,onClick:K,size:"sm",children:[z?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ms,{className:"mr-2 h-4 w-4"}),z?"Saving...":"Save"]}),!T&&!x&&i&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>w(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!x&&i&&a&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>S(!R),size:"sm",variant:"ghost",children:e.jsx(Qe,{className:"h-4 w-4"})})}),!x&&a&&e.jsx(ya,{}),!x&&e.jsx(Ut,{isOpen:f,onClose:()=>g(!1)})]})]})}function br({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:u,showNone:d=!1}){const m=pe.useRef(null),[h,f]=pe.useState(!1),[g,j]=pe.useState("100%"),x=d?[...n||[],{id:"none",name:"None"}]:n;pe.useLayoutEffect(()=>{m.current&&j(m.current.offsetWidth)},[]);function y(){var b;return l?"Loading...":o?"Error":a?(b=n==null?void 0:n.find(T=>T.id===a))==null?void 0:b.name:`Select ${t}`}function p(b,T){r(T),f(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:f,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[u&&e.jsx("div",{className:"mr-2",children:u}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:y()})]}),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(bt,{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(b=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:b.name,onSelect:T=>p(T,b.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===b.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:b.name,children:b.name})]})},b.id))})]})]})})]})}function He({title:t,items:n,value:a,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:u,disabled:d=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":a;function f(){if(t==="Connection")return e.jsx(ia,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(ra,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(Mn,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:d,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",u),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(bt,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((x,y)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},y))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function j(){return e.jsx(br,{icon:f(),items:n,value:h,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:m==="select"?g():j()})})}function Nr({column:t}){const[n,a]=A.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:u,connectionType:d}=s.useEditorAside(),m=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),f=s.useEditorStore(x=>x.actions.setRunSql);function g(x,y){var R;const p=s.createSqlGenConfig(x,i,y),b=(R=u==null?void 0:u.find(N=>N.id===c))==null?void 0:R.name;m(p);const T=s.getSql(p,s.fmt(l||""),s.fmt(r),b||"",d,o||"");T&&(h(T),f(!0)),a(!1)}function j(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>g(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>g(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>g(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>g(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>g(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:j()})]})}function Cr({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Te,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(es,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(as,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})}function Ns({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",n),children:[e.jsx(Cr,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Sr({id:t,children:n,type:a="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:a}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:n})}function wr({onClick:t,column:n}){const a=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||u(m)||d(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function u(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function d(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(n),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(Ns,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(Ns,{column:n})}),e.jsx(Sr,{id:n.column_name,type:"column",children:e.jsx(Ns,{column:n})})]})}const Cs={id:"__placeholder__",role:"groupby",type:"string"},Ss={id:"__placeholder__",role:"groupby",type:"string"},ws={id:"__placeholder__",role:"metric",type:"number"},Ds={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},$t={id:"__placeholder__"},ze="droppable-group-by",Ve="droppable-metrics",_e="droppable-pivot-by",fs="sortable-group-by",Rs="sortable-metrics",gs="sortable-pivot-by",Os="droppable-filters",Fs="sortable-filters",_s="sortable-order-by";function Dr(){const t=s.useDndStore(E=>E.insertIndex),n=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.groupByColumns)||[]}),a=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.metricColumns)||[]}),r=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.filterColumns)||[]}),l=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.orderBy)||[]}),o=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:u,setPreviewMetricColumns:d,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:f,setMetricColumns:g,setFilterColumns:j,setOrderByColumns:x,setPivotByColumns:y}=s.useEditorActions(),{columns:p}=s.useDataColumns(),{formattedTableName:b}=s.useEditorAside(),T=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=E=>{var L;const{active:M,over:B}=E;if(((L=M.data.current)==null?void 0:L.type)==="column"&&B){const F=B.id,V=p.find(K=>K.column_name===M.id);if(!V)return;const z=s.isNumberDataType(V.data_type),J=s.isTextDataType(V.data_type),X=s.isDateDataType(V.data_type);if(J||X){if(n.some($=>$.id===F)){const $=n.findIndex(U=>U.id===F);c($);const Y=n.filter(U=>U.id!==Cs.id);Y.splice($,0,Cs),u(Y)}else if(B.id===ze){c(n.length);const $=[...n,Cs];u($),d(a),m(r)}}if(J||X){if(o.some($=>$.id===F)){const $=o.findIndex(U=>U.id===F);c($);const Y=o.filter(U=>U.id!==Ss.id);Y.splice($,0,Ss),h(Y)}else if(B.id===_e){c(o.length);const $=[...o,Ss];h($),u(n),d(a),m(r)}}if(z||J){if(a.some($=>$.id===F)){console.log("isOverMetricSortable",F);const $=a.findIndex(U=>U.id===F);c($);const Y=a.filter(U=>U.id!==ws.id);Y.splice($,0,ws),d(Y)}else if(B.id===Ve){c(a.length);const $=[...a,ws];d($),m(r),u(n),h(o)}}if(w(V)){if(r.some($=>$.id===F)){const $=r.findIndex(U=>U.id===F);c($);const Y=r.filter(U=>U.id!==Ds.id);Y.splice($,0,Ds),m(Y)}else if(B.id===Os){c(r.length);const $=[...r,Ds];m($),d(a),u(n),h(o)}}}else u(n),d(a),m(r),h(o)};function N(E){i(E.active.id),c(null),u(n),d(a),m(r),h(o)}function w(E){return!r.some(M=>M.name===E.column_name)}function v(E,M="SUM"){const{column_name:B,data_type:L}=E,F=[...a],V=t!==null?t:a.length,z={...E,id:Ce(B),name:B,label:ns(B,M),type:L,role:"metric",aggregate:M};F.splice(V,0,z),g(F)}function D(E){const M=s.isTextDataType(E.data_type);s.isDateDataType(E.data_type);const B=[...o],L=t!==null?t:o.length;let F;M?F={...E,id:Ce(E.column_name),name:E.column_name,type:E.data_type,role:"groupby"}:F={...E,id:Ce(E.column_name),name:E.column_name,type:E.data_type,role:"groupby",label:We(E.column_name,"month"),granularity:"month"},B.splice(L,0,F),y(B)}function C(E){const M=s.isTextDataType(E.data_type);s.isDateDataType(E.data_type);const B=[...n],L=t!==null?t:n.length;let F;M?F={...E,id:Ce(E.column_name),name:E.column_name,type:E.data_type,role:"groupby"}:F={...E,id:Ce(E.column_name),name:E.column_name,type:E.data_type,role:"groupby",label:We(E.column_name,"month"),granularity:"month"},B.splice(L,0,F),f(B)}function I(E){const M=[...r],B=t!==null?t:r.length,L={...E,id:Ce(E.column_name),name:E.column_name,type:E.data_type,sql:s.getDefaultFilterSql(E.data_type,b,s.fmt(E.column_name)),role:"filter"};M.splice(B,0,L),j(M)}function S(E){var F,V,z,J,X,K,$,Y;const{active:M,over:B}=E,L=M.data.current;if((L==null?void 0:L.type)==="column"&&B){const U=p.find(W=>W.column_name===M.id);if(!U)return;const Z=s.isNumberDataType(U.data_type),q=s.isTextDataType(U.data_type),P=s.isDateDataType(U.data_type);(q||P)&&(B.id===ze||((F=B.data.current)==null?void 0:F.type)===fs)&&C(U),(q||P)&&(B.id===_e||((V=B.data.current)==null?void 0:V.type)===gs)?D(U):(Z||q)&&(B.id===Ve||((z=B.data.current)==null?void 0:z.type)===Rs)?(Z&&v(U),q&&v(U,"COUNT")):w(U)&&(B.id===Os||((J=B.data.current)==null?void 0:J.type)===Fs)&&I(U)}if(B&&((X=B.data.current)==null?void 0:X.type)===fs&&n.some(U=>U.id===M.id)){const U=n.findIndex(q=>q.id===M.id),Z=n.findIndex(q=>q.id===B.id);if(U!==-1&&Z!==-1&&U!==Z){const q=[...n],[P]=q.splice(U,1);q.splice(Z,0,P),f(q)}}if(B&&((K=B.data.current)==null?void 0:K.type)===gs&&o.some(U=>U.id===M.id)){const U=o.findIndex(q=>q.id===M.id),Z=o.findIndex(q=>q.id===B.id);if(U!==-1&&Z!==-1&&U!==Z){const q=[...o],[P]=q.splice(U,1);q.splice(Z,0,P),y(q)}}if(B&&(($=B.data.current)==null?void 0:$.type)===Rs&&a.some(U=>U.id===M.id)){const U=a.findIndex(q=>q.id===M.id),Z=a.findIndex(q=>q.id===B.id);if(U!==-1&&Z!==-1&&U!==Z){const q=[...a],[P]=q.splice(U,1);q.splice(Z,0,P),g(q)}}if(B&&((Y=B.data.current)==null?void 0:Y.type)===Fs&&r.some(U=>U.id===M.id)){const U=r.findIndex(q=>q.id===M.id),Z=r.findIndex(q=>q.id===B.id);if(U!==-1&&Z!==-1&&U!==Z){const q=[...r],[P]=q.splice(U,1);q.splice(Z,0,P),j(q)}}O(E),i(null),c(null),u(n),d(a),m(r),h(o)}function O(E){const{active:M,over:B}=E,L=M.data.current;if((L==null?void 0:L.type)===_s&&B){const F=l.findIndex(z=>Ze(z.columnId)===M.id),V=l.findIndex(z=>Ze(z.columnId)===B.id);if(F!==-1&&V!==-1&&F!==V){const z=[...l],[J]=z.splice(F,1);z.splice(V,0,J),x(z)}}}function k(){i(null),c(null),u(n),d(a),m(r)}return{handleDragOver:R,handleDragEnd:S,handleDragStart:N,handleDragCancel:k,sensors:T}}function Ce(t){return`${t}-${s.v4()}`}function ns(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"SUM":return`Sum of ${a}`;case"COUNT":return`Count of ${a}`;case"DISTINCT":return`Unique ${a}`;case"AVG":return`Average of ${a}`;case"MIN":return`Min of ${a}`;case"MAX":return`Max of ${a}`;default:return a}}function Ze(t){return`${_s}-${t}`}function We(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function kr({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Te,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(es,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(as,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})}function Tr({schemaName:t,tableName:n,columns:a,status:r}){const[l,o]=A.useState(""),[c,i]=A.useState("all"),u=s.useEditorStore(F=>F.sqlGen),d=s.useEditorStore(F=>F.isDevMode);s.useEditorStore(F=>F.selectedConnectionId);const m=s.useEditorStore(F=>{var V,z;return(z=(V=F.card)==null?void 0:V.queryConfig)==null?void 0:z.metricColumns});s.useEditorStore(F=>{var V,z;return(z=(V=F.card)==null?void 0:V.queryConfig)==null?void 0:z.groupByColumns});const h=s.useEditorStore(F=>F.selectedDatabaseName);s.useEditorStore(F=>F.selectedSchemaName),s.useEditorStore(F=>F.selectedTableName);const f=s.useEditorStore(F=>F.selectedDatamodelId);s.useDashboardStore(F=>F.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:j}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:y,setCardSql:p,setRunSql:b,setSqlGen:T,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:N,modelItems:w,selectedDatamodelName:v}=s.useEditorAside();function D(F){var V;if(d){const z=s.createSqlGenConfig(F,u);T(z);const J=(V=w==null?void 0:w.find(K=>K.id===f))==null?void 0:V.name,X=s.getSql(z,s.fmt(t),s.fmt(n),J||"",N,h||"");X&&(p(X),b(!0))}if(!d){if(s.isTextDataType(F.data_type))if(m&&m.length>0){const z={...F,role:"groupby",id:Ce(F.column_name),name:F.column_name,type:F.data_type};y(z)}else{const z={...F,role:"metric",id:Ce(F.column_name),name:F.column_name,label:ns(F.column_name,"COUNT"),type:F.data_type,aggregate:"COUNT"};x(z)}if(s.isDateDataType(F.data_type)){const z={...F,role:"groupby",id:Ce(F.column_name),name:F.column_name,type:F.data_type,label:We(F.column_name,"month"),granularity:"month"};y(z)}if(s.isNumberDataType(F.data_type)){const z={...F,role:"metric",id:Ce(F.column_name),name:F.column_name,label:ns(F.column_name,"SUM"),type:F.data_type,aggregate:"SUM"};x(z)}}}function C(){const F=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:N,databaseName:h||""});R(!1);const V=N==="MSSQL"?`SELECT top 10 * FROM ${F}`:`SELECT * FROM ${F} LIMIT 10`;p(V),b(!0)}function I(){const F=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:N,databaseName:h||""});p(`SELECT COUNT(*) as count FROM ${F}`),b(!0)}const S=(a==null?void 0:a.filter(F=>F.column_name.toLowerCase().includes(l.toLowerCase())))||[],O=F=>s.isNumberDataType(F.data_type)?"number":"text",k=c==="all"?S:S.filter(F=>O(F)===c),E=S.filter(F=>O(F)==="text").length,M=S.filter(F=>O(F)==="number").length;function B(F){return d?e.jsxs("div",{className:"group flex cursor-pointer items-center justify-between border border-dashed border-background px-2 py-[6px] text-sm transition-colors hover:bg-muted/50",onClick:()=>D(F),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kr,{dataType:F.data_type}),e.jsx("span",{children:F.column_name})]}),e.jsx("div",{onClick:V=>V.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(F.data_type)&&e.jsx(Nr,{column:F})})]}):e.jsx(wr,{onClick:D,column:F})}function L(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:C,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(ea,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:I,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Nt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-4",children:Array.from({length:3}).map((F,V)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},V))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[d&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:L()}),a&&a.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:F=>o(F.target.value)})]}),S.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:F=>i(F),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:S.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:E})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:M})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[k.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),k.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:k==null?void 0:k.map(F=>e.jsx("div",{children:B(F)},F.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function qt({ColumnsComponent:t,type:n}){var se;const[a,r]=A.useState(!1),l=s.useEditorStore(ne=>ne.card),o=s.useEditorStore(ne=>ne.selectedConnectionId),c=s.useDashboardStore(ne=>ne.showFilters),i=s.useEditorStore(ne=>ne.selectedDatamodelId),u=s.useEditorStore(ne=>ne.selectedDatabaseName),d=s.useEditorStore(ne=>ne.selectedSchemaName),m=s.useEditorStore(ne=>ne.selectedTableName),h=s.useEditorStore(ne=>ne.isDevMode),{setSelectedTableName:f,setIsDevMode:g,setCardSql:j}=s.useEditorActions(),{connectionItems:x,modelItems:y,schemaItems:p,databaseItems:b,tableItems:T,columns:R,isConnectionsLoading:N,isModelsLoading:w,isConnectionsError:v,isModelsError:D,isDatabasesLoadingOrFetching:C,isDatabaseError:I,isSchemaLoadingOrFetching:S,isSchemaError:O,isColumnsError:k,isColumnsLoadingOrFetching:E,isTableLoadingOrFetching:M,isTableError:B,connectionType:L,isNonDbConnection:F,refetchDatabases:V,refetchModels:z,refetchSchemas:J,refetchTables:X,refetchColumns:K,refetchConnections:$,handleConnectionChange:Y,handleDatabaseChange:U,handleSchemaChange:Z,handleDatamodelChange:q,handleTableChange:P,tableName:W,schemaName:te}=s.useEditorAside(),{data:_,refetch:ee}=s.useDashboardCardQuery(l);function le(){return t?t(te,W,R):e.jsx(Tr,{schemaName:te,tableName:W,columns:R,status:E?"Loading...":k?"Error":"Success"})}function H(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function Q(ne){ne===!0?_&&(j(_.userSql),setTimeout(()=>{ee()},100)):j(""),g(ne)}function re(){if(!o||L==="S3"||L==="API")return null;if(!i||i==="none")return e.jsx(He,{refetch:V,showNone:!0,onChange:U,isError:I,isLoading:C,items:b,value:u||"",title:"Database",type:"combobox"})}function de(){if(o&&!F&&(!u||u==="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 Se(){if(!o||L==="S3"||L==="API")return null;if(!u||u==="none")return e.jsx(He,{refetch:z,showNone:!0,onChange:q,isError:D,isLoading:w,items:y,value:i||"",title:"Model",type:"combobox"})}function ve(){return!o||L==="S3"||L==="API"||!u||u==="none"?null:e.jsx(He,{refetch:J,onChange:Z,isError:O,isLoading:S,items:p,value:d||"",title:"Schema",type:"combobox"})}function fe(){function ne(){let ue=!1;return L==="API"?(ue=!1,ue):((L==="S3"||o&&u&&u!=="none"&&d)&&(ue=!0),ue)}return ne()?e.jsx(He,{refetch:X,onChange:P,isError:B,items:T,isLoading:M,value:m||"",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]":!c}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":a,"px-4 py-4":!a}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!a),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:a?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!a&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(He,{refetch:$,items:x,title:"Connection",value:o||"",onChange:Y,isLoading:N,isError:v,type:"combobox",connectionTooltip:((se=x==null?void 0:x.find(ne=>ne.id===o))==null?void 0:se.type)||""}),re(),de(),Se(),ve(),fe()]})]}),le(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="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:h,onCheckedChange:Q,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:H,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(ta,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function Yt({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,o]=A.useState(!1),c=A.useRef(null),i=A.useRef(!1);function u(){t&&!i.current&&navigator.clipboard.writeText(t)}function d(f){(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),u())}function m(){const f=window.getSelection();if(f&&f.toString().trim()!==""){const g=f.toString();navigator.clipboard.writeText(g),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:u,onKeyDown:d,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function Gt({sql:t,error:n,onDebugWithAssistant:a}){const r=s.useEditorStore(u=>u.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:[n&&e.jsx(Yt,{error:n}),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(Vn,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&a&&e.jsxs(s.Button,{onClick:a,size:"sm",variant:"secondary",children:[e.jsx(Kn,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Kt({sql:t,error:n,onDebugWithAssistant:a}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(yt,{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(Gt,{sql:t,error:n,onDebugWithAssistant:a})})]})}function Er(t){return s.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function Ht(t){const{theme:n}=s.useTheme(),a=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:u,setRunSql:d}=s.useEditorActions(),m=A.useRef(),h=A.useRef({}),f=r.cards.find(x=>x.id===o),g=A.useCallback(()=>{let x="";return t==="python"&&(x=(f==null?void 0:f.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(f==null?void 0:f.sql)||""),x},[t,f]);A.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const x=m.current.getModel();x&&(h.current[l.id]=x);let y=h.current[o];if(!y){const p=g();y=c.editor.createModel(p,t),h.current[o]=y}m.current.setModel(y)}u(o,l),d(!0)}},[o,l,u,c,d,t,g]),A.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",y=a==="system"?x:a;c.editor.defineTheme("default",{base:y==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":y==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),A.useEffect(()=>{const x=m.current;x&&c&&l&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function j(x,y){if(m.current=x,!h.current[l.id]){const p=x.getModel(),b=g();h.current[l.id]=p||(y==null?void 0:y.editor.createModel(b,t))||x.getModel()}x.setModel(h.current[l.id])}return{handleEditorDidMount:j}}function Ir(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Ht("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Ar(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Ht("python");function r(l){n(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function Mr({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 Us({variant:t="outline"}){var c;const{setCardSql:n}=s.useEditorActions();s.useEditorStore(i=>i.frame);const a=s.useEditorStore(i=>i.card);zs(((c=a.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),a.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=Vs();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Lr(){const t=s.useQueryClient(),[n,a]=A.useState(!1),r=s.useDashboardStore(d=>d.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=Vs(),c=s.useSelectedVisual(),i=Ha(),u=()=>{const d=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}a(!0),i.mutate({visualId:c.id,data:{frameObject:d}},{onSuccess:()=>{a(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{a(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:u,className:"h-8",size:"sm",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!n&&e.jsxs(e.Fragment,{children:[e.jsx(Ms,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function $s(){const{setTempQueryData:t,setSqlGen:n}=s.useEditorActions(),a=s.useQueryClient(),r=s.useEditorStore(u=>u.tempQueryData),l=s.useEditorStore(u=>u.onClose),o=s.useEditorStore(u=>u.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:u,queryData:d}=r;u&&d&&a.setQueryData(u,d)}n({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function js(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(y=>y.isDevMode),r=s.useEditorStore(y=>y.tempQueryData),l=s.useEditorStore(y=>y.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:u,setCardCustomCfg:d,setCardPreferences:m,updateDataSource:h,clearQueryConfig:f,setCardConfig:g,setCardType:j}=s.useEditorActions();function x(){const y=n.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:y}),n.setQueryData(o,null),n.removeQueries({queryKey:o,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),f(),g(void 0),u(""),d(""),m({}),j("bar")}return e.jsxs(s.Button,{onClick:x,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Rr(){const t=s.useQueryClient(),[n,a]=A.useState(!1),[r,l]=A.useState(!1);s.useEditorStore(z=>z.frame);const o=s.useEditorStore(z=>z.card);s.useEditorStore(z=>z.isShowingVisual),s.useEditorStore(z=>z.selectedConnectionId),s.useEditorStore(z=>z.tempQueryData),s.useEditorStore(z=>z.selectedDatabaseName),s.useEditorStore(z=>z.selectedDatamodelId),s.useEditorStore(z=>z.selectedSchemaName);const c=s.useEditorStore(z=>z.showAIDialog);s.useEditorStore(z=>z.selectedTableName);const i=s.useEditorStore(z=>{var J;return(J=z==null?void 0:z.card)==null?void 0:J.sql}),u=s.useEditorStore(z=>{var J;return(J=z==null?void 0:z.card)==null?void 0:J.python}),{sheetFilterValues:d}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:f,setTempQueryData:g,setPythonStdOut:j,setCardPreferences:x,setCardType:y,setCardPython:p,runAssistant:b,setShowAIDialog:T}=s.useEditorActions();s.useEditorStore(z=>z.onSave),s.useEditorStore(z=>z.onClose),s.useEditorStore(z=>z.actions.setSqlGen);const R=s.useEditorStore(z=>z.runSql),N=s.useEditorStore(z=>z.actions.setRunSql),w=s.useEditorStore(z=>z.actions.setIsSqlRunning),{data:v,isLoading:D,isFetching:C,isSuccess:I,isError:S,error:O,queryKey:k,refetch:E,errorMessage:M}=s.useDashboardCardQuery(o);A.useEffect(()=>{if(v&&(v.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((v==null?void 0:v.output)||""),v.records.length>0)){const{dimensionKeys:z}=s.getKeys(v.records);h(z)}},[v,h,j]),A.useEffect(()=>{(D||C)&&w(!0),(S||I)&&w(!1),S&&(h([]),j(""))},[D,C,v,j,S,I,w,h,O]),A.useEffect(()=>{R&&(t.getQueryData(k)||E(),N(!1))},[R,E,N,k,t]);async function B(){const z=`Can you help me debug this query in the current table scope?
|
|
341
|
+
*/const ja=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function ya(){const{setTheme:t}=s.useTheme(),n=s.useDashboardStore(a=>a.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(pa,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(aa,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function xs(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>St(c))}})}})}}function St(t){return{...t,customCfg:va(t.customCfg),data:[]}}function va(t){var n,a;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(a=(n=t==null?void 0:t.data)==null?void 0:n.datasets)==null?void 0:a.map(r=>({...r,data:[]}))}}:null}async function ba(t,n,a,r){if(!r)return null;const l=JSON.stringify(n);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:l,filterValues:a,operation:"create"})}async function Ls(t,n){if(!n)return null;const{id:a,template:r,filterValues:l,isDefault:o,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",n,{lensId:a,template:r,filterValues:l,isDefault:o,shared:c,operation:"update"})}async function Na(t,n){return n?await s.postRequest("https://semaphor.cloud/api/v1/lens",n,{operation:"delete",lensId:t}):null}function Ca(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),l=s.useDashboardStore(x=>x.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,u]=A.useState(!1),[d,m]=A.useState(!1),h=s.useDashboardStore(x=>x.dashboard),f=s.useDashboardStore(x=>x.filterValues),{authToken:g}=s.useSemaphorContext();async function j(){u(!0);const x=xs(h),y=await ba(t,x,f,g==null?void 0:g.accessToken);y&&(o([...l||[],y]),c(y.id),m(!1)),u(!1)}return e.jsxs(s.Dialog,{open:d,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:x=>{n(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:j,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Sa(){const[t,n]=A.useState(!1),a=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(m){o(m)}async function u(m){if(await Na(m,c==null?void 0:c.accessToken)){const f=a==null?void 0:a.filter(g=>g.id!==m);l(f||[]),o("original")}}async function d(m){const h=a==null?void 0:a.map(j=>j.id===m.id?{...j,isDefault:!m.isDefault}:{...j,isDefault:!1});l(h||[]);const f={...m,isDefault:!m.isDefault};await Ls(f,c==null?void 0:c.accessToken);const g=a==null?void 0:a.find(j=>j.isDefault);if(g&&g.id!==m.id){const j={...g,isDefault:!1};await Ls(j,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Yn,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(m=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:m.id,children:[e.jsx("p",{children:m.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),d(m)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!m.isDefault,"text-green-500":m.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),u(m.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},m.id))]})]})]})}function wa({iconClassName:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(""),[o,c]=A.useState(!1),i=s.useDashboardStore(m=>m.isDownloadingPdf);async function u(){const m=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(),s.ue.dismiss(m),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",h)}}async function d(){if(!r)return;a(!1),l(""),c(!1);const m=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(r),s.ue.dismiss(m),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",h)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(Bs,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:n,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:m=>l(m.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:m=>{m.key==="Enter"&&r&&d()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:d,disabled:!r,children:"Download"})]})]})})]})}function je({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(u=>e.jsx(s.SelectItem,{value:u.value,children:u.label},u.value))]})})]})}const at=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function wt({triggerButtonClassName:t}){const{data:n,handleScheduleSubscription:a,handleDeleteSubscription:r,status:l,error:o,isDeleting:c}=Da(),[i,u]=A.useState(""),[d,m]=A.useState(at[0].value),[h,f]=A.useState("06:00"),[g,j]=A.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=>u(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=>{j(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(je,{className:"col-span-2 h-8",label:"Select Frequency",options:at,value:d,onValueChange:x=>m(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:h,onChange:x=>f(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 a({email:i,frequency:d,time:h,subject:g}),f("00:00"),u(""),j("")},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(yt,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:o})})]}),"Schedule"]})}),n&&n.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:n==null?void 0:n.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(rt,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Rn,{className:"size-3.5"})}),e.jsx(rt,{tooltip:`${x.endUserEmail}`,children:e.jsx(sa,{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 rt=({children:t,tooltip:n})=>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:n})]})});function Da(){const[t,n]=A.useState("idle"),[a,r]=A.useState(""),[l,o]=A.useState(null),c=s.useDashboardStore(T=>T.authToken),i=s.useDashboardStore(T=>T.dashboard.id),u=s.useDashboardStore(T=>T.dashboard.title),{endUserId:d}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),m="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:i,endUserId:d},{data:f,isLoading:g,isError:j,isFetching:x,refetch:y}=s.useQuery({queryKey:["subscriptions",i,d],queryFn:()=>s.getRequest(m,(c==null?void 0:c.accessToken)||"",h),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!d});async function p({email:T,subject:R,frequency:b,time:w}){const{authToken:v,...D}=s.getParamsForPrint(),C=Intl.DateTimeFormat().resolvedOptions().timeZone,I={email:T,frequency:b,time:w,timezone:C,endUserId:d,endUserEmail:T,subject:R||u||"Scheduled Dashboard",dashboardId:i,dashboardParams:D};n("loading");const S="https://semaphor.cloud/api/v1/subscriptions/create";try{const O=await s.postRequestRegular(S,(v==null?void 0:v.accessToken)||"",{...I});n("success"),r(""),y(),setTimeout(()=>{n("idle")},2e3)}catch(O){console.error(O),n("error"),r(O.message)}}async function N(T){const R="https://semaphor.cloud/api/v1/subscriptions/delete";o(T);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:T}),y(),setTimeout(()=>{o(null)},2e3)}catch(b){console.error(b),o(null),n("error"),r(b.message)}}return{data:f,isLoading:g,isFetching:x,isError:j,isDeleting:l,refetch:y,handleScheduleSubscription:p,handleDeleteSubscription:N,status:t,error:a}}function Ie(){const{authToken:t,tokenProps:n}=s.useSemaphorContext();let a=null;n&&(n.endUserId&&n.endUserEmail&&n.tenantId?a={id:n.endUserId,name:n.endUserEmail?String(n.displayName):"",email:n.endUserEmail?String(n.endUserEmail):"",type:"tenant",tenantId:n.tenantId}:n.orgUserId&&n.orgUserEmail&&(a={id:n.orgUserId,name:n.orgUserEmail?String(n.displayName):"",email:n.orgUserEmail?String(n.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:l,isError:o}=s.useQuery({queryKey:["userInfo",a==null?void 0:a.id],queryFn:async()=>{if(!(a!=null&&a.id))return;const i=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${a.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)&&!!(a!=null&&a.id)});return{currentUser:a?{...a,...r||{}}:null,isLoading:l,isError:o}}function Dt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,n)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},n))})]})})}var ae=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(ae||{});const ka=async(t,n,a,r,l,o)=>{const c={},i={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${i[n]}`,t,c)},Ta=async(t,n,a)=>{const r={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[n]}`,t,a)},Ea=async(t,n,a,r)=>{const l={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${l[n]}/${a}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${o.status}`)}return o.json()},Ia=async(t,n,a)=>{const r={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!l.ok){const o=await l.json();throw new Error((o==null?void 0:o.error)||`HTTP error! status: ${l.status}`)}return l.json()},Aa=async(t,n,a)=>{const r={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}/duplicate`,t,{})},Ma=async(t,n,a,r)=>{const l={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${l[n]}/${a}/share`,t,r)},La=async(t,n,a,r)=>{const l={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${l[n]}/${a}/share`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${o.status}`)}return o.json()},Ra=async(t,n,a)=>{const r={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}/shares`,t)},Oa=async(t,n,a)=>{const r={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[n]}/${a}`,t)};function Fa(t){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(n==null?void 0:n.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(n!=null&&n.accessToken):!!(n!=null&&n.accessToken)})}function Ba(t,n,a,r,l){const{authToken:o}=s.useSemaphorContext(),{currentUser:c}=Ie();return s.useQuery({queryKey:[t,n,a,r,l],queryFn:()=>ka((o==null?void 0:o.accessToken)||"",t),enabled:!!(o!=null&&o.accessToken)&&!!c})}function Pa(t,n){const{authToken:a}=s.useSemaphorContext(),r=s.useQueryClient();return $e({mutationFn:l=>Ta((a==null?void 0:a.accessToken)||"",t,l),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} created successfully`),n==null||n()},onError:l=>{s.ue.error(`Failed to create ${s.toTitleCase(t)}: ${l.message}`)}})}function kt(t){const{authToken:n}=s.useSemaphorContext(),a=s.useQueryClient();return $e({mutationFn:({resourceId:r,data:l})=>Ea((n==null?void 0:n.accessToken)||"",t,r,l),onMutate:async()=>{await a.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await a.invalidateQueries({queryKey:[t]})},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function za(t,n){const{authToken:a}=s.useSemaphorContext(),r=s.useQueryClient();return $e({mutationFn:l=>Ia((a==null?void 0:a.accessToken)||"",t,l),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} deleted successfully`),n==null||n()},onError:l=>{s.ue.error(`Failed to delete ${s.toTitleCase(t)}: ${l.message}`)}})}function Va(t){const{authToken:n}=s.useSemaphorContext(),a=s.useQueryClient();return $e({mutationFn:r=>Aa((n==null?void 0:n.accessToken)||"",t,r),onMutate:async()=>{await a.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await a.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} duplicated successfully`)},onError:r=>{s.ue.error(`Failed to duplicate ${s.toTitleCase(t)}: ${r.message}`)}})}function _a(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return $e({mutationFn:({resourceType:a,resourceId:r,data:l})=>Ma((t==null?void 0:t.accessToken)||"",a,r,l),onMutate:async a=>{await n.cancelQueries({queryKey:["resource-shares",a.resourceType,a.resourceId]})},onSuccess:async(a,r)=>{await n.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),n.invalidateQueries({queryKey:[r.resourceType]})},onError:a=>{s.ue.error(`Failed to share resource: ${a.message}`)}})}function Ua(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return $e({mutationFn:({resourceType:a,resourceId:r,data:l})=>La((t==null?void 0:t.accessToken)||"",a,r,l),onMutate:async a=>{await n.cancelQueries({queryKey:["resource-shares",a.resourceType,a.resourceId]})},onSuccess:async(a,r)=>{await n.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),n.invalidateQueries({queryKey:[r.resourceType]})},onError:a=>{s.ue.error(`Failed to remove resource shares: ${a.message}`)}})}function $a(t,n){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,n],queryFn:()=>Ra((a==null?void 0:a.accessToken)||"",t,n),enabled:!!(a!=null&&a.accessToken)&&!!n})}function qa(t,n,a){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,n],queryFn:()=>Oa((r==null?void 0:r.accessToken)||"",t,n),enabled:(a==null?void 0:a.enabled)!==void 0?a.enabled&&!!(r!=null&&r.accessToken)&&!!n:!!(r!=null&&r.accessToken)&&!!n})}function Ya(t,n){return qa(ae.VISUAL,t,n)}function Tt(){const[t,n]=A.useState(new Map),a=A.useCallback((o,c)=>{n(i=>{const u=new Map(i),d=new Set(u.get(o)||[]);return c?d.add(c):(d.add("title"),d.add("description")),u.set(o,d),u})},[]),r=A.useCallback((o,c)=>{n(i=>{const u=new Map(i),d=new Set(u.get(o)||[]);return c?d.delete(c):d.clear(),d.size===0?u.delete(o):u.set(o,d),u})},[]),l=A.useCallback((o,c)=>{const i=t.get(o);return i?c?i.has(c):i.size>0:!1},[t]);return{startUpdating:a,stopUpdating:r,isUpdating:l}}function Ps(t,n,a){var h;const r=Ba(t),l=Pa(t,a),o=kt(t),c=za(t,n),i=Va(t),u=_a(),d=Ua(),m={[ae.DASHBOARD]:"dashboards",[ae.VISUAL]:"visuals"};return{resources:((h=r.data)==null?void 0:h[m[t]])||[],isLoading:r.isLoading,isError:r.isError,isFetching:r.isFetching,error:r.error,createResource:l.mutate,updateResource:o.mutate,deleteResource:c.mutate,duplicateResource:i.mutate,shareResource:u.mutate,removeResourceShares:d.mutate,isCreating:l.isPending,isUpdating:o.isPending,isDeleting:c.isPending,isDuplicating:i.isPending,isSharing:u.isPending,isRemovingShares:d.isPending,isUpdatingShares:u.isPending,refetch:r.refetch}}function Ga(t,n){return Ps(ae.DASHBOARD,t,n)}function Ka(t,n){return Ps(ae.VISUAL,t,n)}function Ha(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return $e({mutationFn:async({visualId:a,data:r})=>{const l=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t==null?void 0:t.accessToken}`},body:JSON.stringify(r)});if(!l.ok)throw new Error("Failed to update visual");return l.json()},onSuccess:()=>{s.ue.success("Visual updated successfully"),n.invalidateQueries({queryKey:["visuals"]})},onError:()=>{s.ue.error("Failed to update visual")}})}function Qa({visual:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:u,onDuplicateVisual:d,onShareVisual:m,formatDate:h}){var v,D,C;const{selectVisual:f}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),x=s.useDashboardStore(I=>I.actions.setIsDashboardPanelOpen),[y,p]=A.useState(!1),[N,T]=A.useState(!1);A.useEffect(()=>{a?(p(!0),T(!0)):N&&(p(!1),T(!1))},[a,N]);const R=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Bs,{className:"h-3 w-3 text-purple-500"}):e.jsx(Ee,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Fe,{className:"h-3.5 w-3.5 text-slate-500"}),b=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),w=()=>{f(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:w,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:b()})}),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:I=>i==null?void 0:i(t.id,{title:I}),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:R()})]}),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:I=>i==null?void 0:i(t.id,{description:I}),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:I=>{I.stopPropagation(),o(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:y,onOpenChange:p,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:I=>I.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:I=>{I.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.preventDefault(),I.stopPropagation(),d(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),c==null||c(t)},children:[e.jsx(oa,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),m(t)},children:[e.jsx(Ee,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),u(t),x(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((v=t.ownership.createdBy)==null?void 0:v.type)==="tenant"||((D=t.ownership.createdBy)==null?void 0:D.type)==="organization"&&j)&&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:h(t.lastModified)})]})]})]})]})]})})]})]},t.id)}function Et({value:t,onChange:n,placeholder:a="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:a,value:t,onChange:r=>n(r.target.value),className:"pl-9"})]})}function ps({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:o=!0}){var u;const c=((u=a.find(d=>d.value===t))==null?void 0:u.label)||t,i=a.filter(d=>d.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(d=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:d.value,disabled:r}),n(d.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:d.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:d.description})]})},d.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function It({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>a(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(o=>{const c=t.find(u=>u.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(ps,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:u=>r(o.id,u),roleOptions:i}),e.jsx("button",{onClick:()=>a(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function At({usersToRemove:t,allUsers:n,onRemove:a}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>a(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>a(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function Mt({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const u=n.find(d=>d.id===i);return(u==null?void 0:u.name)||"Unknown User"},c=i=>{const u=l.find(d=>d.value===i);return(u==null?void 0:u.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(Ee,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function Lt(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=A.useRef(null);return A.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function Ne(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function Wa(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Rt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function Ja(t,n,a){const r=Rt(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function Xa({user:t}){return Rt(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 Za({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=Wa((r==null?void 0:r.type)||""),i=a.some(h=>h.id===t.id),u=a.find(h=>h.id===t.id),d=u?u.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(ps,{currentRole:d,onRoleChange:h=>{o(t.id,n.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:Ne(d,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function er({hasAccess:t,isUserRemoving:n,isSelected:a,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!n&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),n&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),a&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(ts,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function sr({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function tr({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],u=c.specificTenantUsers||[],d=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((f,g)=>{var p,N;const j=((p=n.find(T=>T.id===f.orgUserId))==null?void 0:p.name)||"Unknown User",x=((N=n.find(T=>T.id===f.orgUserId))==null?void 0:N.type)||"",y=Ne(f.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:y})]},g)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",u.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[u.slice(0,3).map((f,g)=>{var p,N;const j=((p=n.find(T=>T.id===f.tenantUserId))==null?void 0:p.name)||"Unknown User",x=((N=n.find(T=>T.id===f.tenantUserId))==null?void 0:N.type)||"",y=Ne(f.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:y})]},g)}),u.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",u.length-3," more users"]})]})]}),d.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:d.map((f,g)=>{const j=Ne(f.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((f,g)=>{const j=Ne(f.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((f,g)=>{const j=Ne(f.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)})})]}),!i.length&&!u.length&&!d.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((u,d)=>{var g,j;const m=((g=n.find(x=>x.id===u.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((j=n.find(x=>x.id===u.tenantUserId))==null?void 0:j.type)||"",f=Ne(u.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:f})]},d)}),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((u,d)=>{const m=Ne(u.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},d)})})]}),!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,u)=>{var f,g;const d=((f=n.find(j=>j.id===i.tenantUserId))==null?void 0:f.name)||"Unknown User",m=((g=n.find(j=>j.id===i.tenantUserId))==null?void 0:g.type)||"",h=Ne(i.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:d}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},u)}),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,u)=>{const d=Ne(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:d})]},u)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function nr({isInitialLoading:t,searchQuery:n,availableUsers:a}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):a.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:n?"No users found matching your search.":"No users available to share with."}):null}function ar({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:u,usersToUpdate:d,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:f,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:o,disabled:t.id===(u==null?void 0:u.id),onCheckedChange:()=>{l?a?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(Xa,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(ps,{currentRole:n==null?void 0:n.role,onRoleChange:j=>f(t.id,n.role,j),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(Za,{user:t,userShare:n,usersToUpdate:d,currentUser:u,getRoleOptions:()=>i,handleUpdateAccess:f}),o&&!l&&e.jsx("div",{onClick:j=>j.stopPropagation(),children:e.jsx(ps,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:j=>g(t.id,j),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(er,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(sr,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Ot({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:u,handleUpdateAccess:d}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),j=s.useShareManagementActions(),x=c||(b=>{const w=m.some(D=>D.id===b),v=h.includes(b);w?j.removeSelectedUser(b):v?j.removeUserFromRemove(b):j.addSelectedUser({id:b,role:"VIEWER"})}),y=i||j.updateSelectedUserRole,p=u||j.addUserToRemove,N=d||((b,w,v)=>{j.addUserToUpdate({id:b,currentRole:w,newRole:v})}),T=l,R=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(T??[]).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(tr,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(T==null?void 0:T.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===T.length?j.setSelectedUsers([]):j.setSelectedUsers(T.map(b=>({id:b.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===T.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(nr,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:T||[]}),!n&&!a&&(T==null?void 0:T.length)>0&&T.map(b=>{const w=t?Ja(b,t,o):void 0,v=R.includes(b.id),D=!!w,C=D&&!v,I=m.some(k=>k.id===b.id),S=m.find(k=>k.id===b.id),O=r(b.type);return e.jsx(ar,{user:b,userShare:w,isUserRemoving:v,hasAccess:C,hasAccessFromAPI:D,isSelected:I,selectedUser:S,roleOptions:O,currentUser:o,usersToUpdate:f,handleUserToggle:x,handleRemoveAccess:p,handleUpdateAccess:N,handleUserRoleChange:y},b.id)})]})]})}function Ft({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(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 Pe=()=>[{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 rr({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const u=s.useShareCurrentMode(),d=Pe().filter(N=>N.value==="VIEWER"||N.value==="EDITOR"||N.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",h=l?l.newRole:m,f=n.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,j=o,x=m==="NONE"||!m,y=N=>{switch(N){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(da,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},p=N=>{r(m,N)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!j&&!x?"border-orange-300 bg-orange-50":f?"border-green-300 bg-green-50":j||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(Ee,{className:"h-5 w-5"}),"Share with All"," ",u==="allOrgUsers"?"Organization":u==="allTenantUsers"?"Tenant":u==="specificOrgUsers"?"Org":"Tenant"," ","Users",f&&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"}),(j||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:j||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:d.map(N=>e.jsxs(s.Button,{variant:h===N.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>p(N.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[y(N.value),e.jsx("span",{className:"font-medium",children:N.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:N.description})]},N.value))})]})})]})})}function Bt({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:u}){const d=x=>x==="OWNER"?"CONTRIBUTOR":x,h=n?{role:d(n.role)}:{role:"NONE"},f=i?{currentRole:d(i.currentRole),newRole:d(i.newRole)}:null,g=(x,y)=>{o(x,y)},j=()=>{c()};return e.jsx(rr,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:j,allUsersToUpdate:f,allUsersToRemove:u})}const lr=async(t,n={})=>{const a={};return n.search&&(a.search=n.search),n.type&&(a.type=n.type),n.active!==void 0&&(a.active=n.active.toString()),n.tenantId&&(a.tenantId=n.tenantId),n.limit&&(a.limit=n.limit.toString()),n.offset&&(a.offset=n.offset.toString()),n.page&&(a.page=n.page.toString()),n.pageSize&&(a.pageSize=n.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,a)};function or(t={}){var o,c,i;const{authToken:n,tokenProps:a}=s.useSemaphorContext(),r=(a==null?void 0:a.endUserId)||(a==null?void 0:a.orgUserId),l=s.useQuery({queryKey:["unified-users",t],queryFn:()=>lr((n==null?void 0:n.accessToken)||"",t),enabled:!!(n!=null&&n.accessToken)&&!!r,retry:(u,d)=>d instanceof Error&&d.message.includes("401")||d instanceof Error&&d.message.includes("403")?!1:u<2,retryDelay:u=>Math.min(1e3*2**u,3e4)});return{users:((o=l.data)==null?void 0:o.users)||[],userContext:(c=l.data)==null?void 0:c.userContext,total:((i=l.data)==null?void 0:i.total)||0,isLoading:l.isLoading,isError:l.isError,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function Be(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=ae.DASHBOARD,userType:l,tenantId:o}=t,c=A.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading:u,isError:d}=or(c),m=$a(r,a);return{allUsers:i,isLoadingUsers:u,isErrorLoadingUsers:d,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function ir({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var X,K;const i=s.useShareSelectedTab(),u=s.useShareSelectedTenant(),{searchQuery:d,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),f=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),j=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),y=s.useShareOrgWideRole(),p=s.useShareManagementActions(),[N,T]=A.useState("specific_users"),R=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},b=()=>{if(i==="tenant"&&u)return u},{allUsers:w,existingShares:v,isLoadingUsers:D}=Be({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:R(),tenantId:b()});A.useEffect(()=>{p.setCurrentContext("org-tab"),p.setCurrentMode(N==="all_users"?"allOrgUsers":"specificOrgUsers")},[p,N]);const C=$=>{var U,Z;const Y=$;if(T(Y),r==null||r(Y),p.setCurrentContext("org-tab"),Y==="specific_users")p.setCurrentMode("specificOrgUsers");else if(Y==="all_users"){p.setCurrentMode("allOrgUsers");const q=(Z=(U=v==null?void 0:v.shares)==null?void 0:U.orgUsersOnly)==null?void 0:Z[0];q&&q.role!==void 0&&p.setOrgWideRole(q.role)}},I=w.filter($=>$.name.toLowerCase().includes(d.toLowerCase())||$.email.toLowerCase().includes(d.toLowerCase())),S=w.filter($=>f.some(Y=>Y.id===$.id)),O=$=>{var q,P;const Y=f.some(W=>W.id===$),U=g.includes($),Z=(P=(q=v==null?void 0:v.shares)==null?void 0:q.specificOrgUsers)==null?void 0:P.some(W=>W.orgUserId===$);Y?p.removeSelectedUser($):U?p.removeUserFromRemove($):Z||p.addSelectedUser({id:$,role:"VIEWER"})},k=($,Y)=>{p.updateSelectedUserRole($,Y)},E=$=>{p.addUserToRemove($),p.removeSelectedUser($)},M=$=>{p.removeUserFromRemove($)},B=$=>{p.removeUserFromUpdate($)},L=($,Y)=>{p.setOrgWideRole(Y)},F=()=>{p.setOrgWideRole((V==null?void 0:V.role)||"NONE")},V=(K=(X=v==null?void 0:v.shares)==null?void 0:X.orgUsersOnly)==null?void 0:K[0];A.useEffect(()=>{N==="all_users"&&V&&V.role!==void 0&&p.setOrgWideRole(V.role)},[N,V,p]);const z=D,J=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(Ft,{shareType:N,onShareTypeChange:C,currentUser:a,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 ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(Ee,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),N==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Et,{value:d,onChange:m}),e.jsx(It,{selectedUsers:f,selectedUserObjects:S,onRemove:O,onRoleChange:k,getRoleOptions:Pe}),e.jsx(At,{usersToRemove:g,allUsers:I,onRemove:M}),e.jsx(Mt,{usersToUpdate:j,allUsers:I,onRemove:B,getRoleOptions:Pe}),e.jsx(Ot,{existingShares:v,isInitialLoading:z,isSearching:J,resource:t,onShare:()=>{},getRoleOptions:Pe,allUsers:I,currentUser:a,handleUserToggle:O,handleUserRoleChange:k,handleRemoveAccess:E,handleUpdateAccess:($,Y,U)=>{p.addUserToUpdate({id:$,currentRole:Y,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Bt,{currentUser:a,currentShare:V,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:L,onRemoveAccess:F,allUsersToUpdate:x==="allOrgUsers"&&y!==((V==null?void 0:V.role)||"NONE")?{currentRole:(V==null?void 0:V.role)||"NONE",newRole:y}:null,allUsersToRemove:x==="allOrgUsers"&&(V==null?void 0:V.role)===void 0})})]}):null}function lt({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var q;const{searchQuery:i,debouncedSearchQuery:u,setSearchQuery:d}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareCurrentMode(),j=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),y=s.useShareSelectedTenant(),p=s.useShareManagementActions(),{data:N,isLoading:T}=Fa({enabled:(a==null?void 0:a.type)==="organization"}),[R,b]=A.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(p.setCurrentContext("tenant-dialog"),p.setCurrentMode("specificTenantUsers")):(p.setCurrentContext("tenant-tab"),p.setCurrentMode("allTenants"))},[p,a==null?void 0:a.type]);const w=P=>{var te,_,ee,le;b(P);let W;if(P==="specific_tenant_users"?W="specific_users":P==="all_tenant_users"||P==="all_tenants"?W="all_users":W="specific_users",r==null||r(W),(a==null?void 0:a.type)==="tenant"?(p.setCurrentContext("tenant-dialog"),P==="specific_tenant_users"?p.setCurrentMode("specificTenantUsers"):P==="all_tenant_users"&&(p.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&p.setSelectedTenant(a.tenantId))):(p.setCurrentContext("tenant-tab"),P==="specific_tenant_users"?p.setCurrentMode("specificTenantUsers"):P==="all_tenant_users"?p.setCurrentMode("allTenantUsers"):P==="all_tenants"&&p.setCurrentMode("allTenants")),P==="all_tenant_users"){const H=(_=(te=C==null?void 0:C.shares)==null?void 0:te.tenantWide)==null?void 0:_[0];H&&H.role!==void 0&&p.setTenantWideRole(H.role)}else if(P==="all_tenants"){const H=(le=(ee=C==null?void 0:C.shares)==null?void 0:ee.allTenantsOnly)==null?void 0:le[0];H&&H.role!==void 0&&p.setAllTenantsRole(H.role)}},v=P=>{p.setSelectedTenant(P)},{allUsers:D,existingShares:C,isLoadingUsers:I,isErrorLoadingUsers:S,isLoadingShares:O,isErrorLoadingShares:k}=Be({debouncedSearchQuery:u,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:y}),E=P=>{var ee,le;const W=m.some(H=>H.id===P),te=h.includes(P),_=(le=(ee=C==null?void 0:C.shares)==null?void 0:ee.specificTenantUsers)==null?void 0:le.some(H=>H.tenantUserId===P);W?p.removeSelectedUser(P):te?p.removeUserFromRemove(P):_||p.addSelectedUser({id:P,role:"VIEWER"})},M=(P,W)=>{p.updateSelectedUserRole(P,W)},B=P=>{p.addUserToRemove(P),p.removeSelectedUser(P)},L=P=>{p.removeUserFromRemove(P)},F=P=>{p.removeUserFromUpdate(P)},V=(P,W,te)=>{p.addUserToUpdate({id:P,currentRole:W,newRole:te})},z=(P,W)=>{R==="all_tenant_users"?p.setTenantWideRole(W):R==="all_tenants"&&p.setAllTenantsRole(W)},J=()=>{R==="all_tenant_users"?p.setTenantWideRole("VIEWER"):R==="all_tenants"&&p.setAllTenantsRole("VIEWER")},K=(()=>{var P,W,te,_;return g==="allTenants"?(W=(P=C==null?void 0:C.shares)==null?void 0:P.allTenantsOnly)==null?void 0:W[0]:g==="allTenantUsers"?(_=(te=C==null?void 0:C.shares)==null?void 0:te.tenantWide)==null?void 0:_[0]:null})();A.useEffect(()=>{var P,W,te,_;if(R==="all_tenant_users"){const ee=(W=(P=C==null?void 0:C.shares)==null?void 0:P.tenantWide)==null?void 0:W[0];ee&&ee.role!==void 0&&p.setTenantWideRole(ee.role)}else if(R==="all_tenants"){const ee=(_=(te=C==null?void 0:C.shares)==null?void 0:te.allTenantsOnly)==null?void 0:_[0];ee&&ee.role!==void 0&&p.setAllTenantsRole(ee.role)}},[R,C,p]);const $=D.filter(P=>m.some(W=>W.id===P.id)),Y=I||O,U=S||k,Z=()=>(a==null?void 0:a.type)==="tenant"||R==="all_tenants"?!0:y&&(R==="specific_tenant_users"||R==="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&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Ft,{shareType:R,onShareTypeChange:w,currentUser:a,options:(a==null?void 0:a.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(Ee,{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(st,{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"})}]}),(a==null?void 0:a.type)==="organization"&&(R==="specific_tenant_users"||R==="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:y||"",onValueChange:v,disabled:T,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:T?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(q=N==null?void 0:N.tenants)==null?void 0:q.map(P=>e.jsx(s.SelectItem,{value:P.id,children:P.name},P.id))})]})]}),Z()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Et,{value:i,onChange:d}),e.jsx(It,{selectedUsers:m,selectedUserObjects:$,onRemove:P=>E(P),onRoleChange:M,getRoleOptions:Pe}),e.jsx(At,{usersToRemove:h,allUsers:D,onRemove:L}),e.jsx(Mt,{usersToUpdate:f,allUsers:D,onRemove:F,getRoleOptions:Pe}),e.jsx(Ot,{existingShares:C,isInitialLoading:!!Y,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Pe,allUsers:D,currentUser:a,handleUserToggle:E,handleUserRoleChange:M,handleRemoveAccess:B,handleUpdateAccess:V})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Bt,{currentUser:a,currentShare:K,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:z,onRemoveAccess:J,allUsersToUpdate:g==="allTenantUsers"&&((K==null?void 0:K.role)===void 0||j!==K.role)||g==="allTenants"&&((K==null?void 0:K.role)===void 0||x!==K.role)?{currentRole:(K==null?void 0:K.role)||"VIEWER",newRole:g==="allTenantUsers"?j:x}:null,allUsersToRemove:g==="allTenantUsers"&&(K==null?void 0:K.role)===void 0||g==="allTenants"&&(K==null?void 0:K.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(R==="specific_tenant_users"||R==="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(st,{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 Pt=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),u=s.useShareTenantWideRole(),d=A.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:u}),[t,n,a,r,l,o,c,i,u]),m=A.useMemo(()=>f=>s.validateShareData(f),[]),h=A.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!o)return!1}else if(n==="specificTenantUsers")return o?a.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||l.length>0:!0}return!1},[t,n,a,r,l,o]);return{buildShareData:d,validateShareData:m,isCurrentStateValid:h,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:u}};function ot({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:u,onRemoveAccess:d}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const g=s.useShareSelectedTenant();s.useShareSelectedTab();const j=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),y=s.useShareTenantWideRole(),{buildShareData:p,validateShareData:N,isCurrentStateValid:T}=Pt(),R=a||r||l,b=()=>{var I,S,O,k;if(R)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const E=m.length+h.length+f.length;return E===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${E} user${E!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}else if(i==="all_users"){if(!u||u.role===void 0)return"Share with All Users";const E=u.role;return j===E?"Remove Access":"Update Access"}else if(i==="all_tenants"){const E=(S=(I=n==null?void 0:n.shares)==null?void 0:I.allTenantsOnly)==null?void 0:S[0];if(!E||E.role===void 0)return"Share with All Tenants";const M=E.role;return x===M?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const E=(k=(O=n==null?void 0:n.shares)==null?void 0:O.tenantWide)==null?void 0:k[0];if(!E||E.role===void 0)return"Share with All Tenant Users";const M=E.role;return y===M?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const E=m.length+h.length+f.length;return E===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${E} user${E!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}return"Share"},w=()=>R||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!T,v=()=>{const I=p();I&&N(I)&&o(I)},D=()=>{var I,S,O,k;if(i==="all_users")if(!u||u.role===void 0){const E=p();E&&N(E)&&o(E)}else{const E=u.role;if(j===E)d==null||d();else{const B=p();if(B&&N(B)){const L={...B,updateAccess:!0};o(L)}}}else if(i==="all_tenants"){const E=(S=(I=n==null?void 0:n.shares)==null?void 0:I.allTenantsOnly)==null?void 0:S[0];if(!E||E.role===void 0){const M=p();M&&N(M)&&o(M)}else{const M=E.role;if(x===M)d==null||d();else{const L=p();if(L&&N(L)){const F={...L,updateAccess:!0};o(F)}}}}else if(i==="all_tenant_users"){const E=(k=(O=n==null?void 0:n.shares)==null?void 0:O.tenantWide)==null?void 0:k[0];if(!E||E.role===void 0){const M=p();M&&N(M)&&o(M)}else{const M=E.role;if(y===M)d==null||d();else{const L=p();if(L&&N(L)){const F={...L,updateAccess:!0};o(F)}}}}},C=()=>{var I,S,O,k;if(i==="all_users"){if(!u||u.role===void 0)return"default";const E=u.role;return j===E?"destructive":"default"}else if(i==="all_tenants"){const E=(S=(I=n==null?void 0:n.shares)==null?void 0:I.allTenantsOnly)==null?void 0:S[0];if(!E||E.role===void 0)return"default";const M=E.role;return x===M?"destructive":"default"}else if(i==="all_tenant_users"){const E=(k=(O=n==null?void 0:n.shares)==null?void 0:O.tenantWide)==null?void 0:k[0];if(!E||E.role===void 0)return"default";const M=E.role;return y===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:R,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||f.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||R,variant:"default",children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ts,{className:"mr-2 h-4 w-4"}),!R&&b()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:D,disabled:w(),variant:C(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ee,{className:"mr-2 h-4 w-4"}),!R&&b()]})]})}function cr({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const u=s.useShareSelectedUsers(),d=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:g,isCurrentStateValid:j}=Pt(),x=n||a||r,y=()=>{if(x)return"Updating...";if(c==="specific_users"){if(u.length===0&&d.length===0&&m.length===0)return"Select users to share with";const b=u.length+d.length+m.length;return b===0?"Select users to share with":u.length>0&&d.length>0?`Update access for ${b} user${b!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Remove access for ${d.length} user${d.length!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Share with ${u.length} user${u.length!==1?"s":""}`:m.length>0&&u.length===0&&d.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${b} user${b!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const b=i.role;return h===b?"Remove Access":"Update Access"}return"Share"},p=()=>x||!t?!0:!j,N=()=>{const b=f();b&&g(b)&&l(b)},T=()=>{if(!i||i.role==="NONE"){const b=f();b&&g(b)&&l(b)}else{const b=i.role;if(h===b){const v=f();if(v&&g(v)){const D={...v,removeAccess:!0};l(D)}}else{const v=f();if(v&&g(v)){const D={...v,updateAccess:!0};l(D)}}}},R=()=>!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:(u.length>0||d.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:N,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(ts,{className:"mr-2 h-4 w-4"}),!x&&y()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:T,disabled:p(),variant:R(),children:[x?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ts,{className:"mr-2 h-4 w-4"}),!x&&y()]})]})}function zt({resource:t,resourceType:n,isSharing:a,isRemoving:r,isUpdating:l,onClose:o,onShare:c,onRemoveAccess:i}){var v,D,C,I;const{currentUser:u}=Ie(),[d,m]=A.useState("specific_users"),[h,f]=A.useState("specific_users"),g=s.useShareManagementActions(),j=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:y}=Be({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:p}=Be({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),N=(D=(v=y==null?void 0:y.shares)==null?void 0:v.tenantWide)==null?void 0:D[0],T=(I=(C=p==null?void 0:p.shares)==null?void 0:C.orgUsersOnly)==null?void 0:I[0],R=()=>{if(j==="org")return h;switch(x){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},b=A.useCallback(()=>{g.resetShareState(),o()},[g,o]),w=(u==null?void 0:u.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:b,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(ts,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:w?"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."})]}),w?e.jsxs(s.Tabs,{value:j,onValueChange:S=>{const O=S;g.setSelectedTab(O),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(ir,{resource:t,resourceType:n,currentUser:u,onShareTabTypeChange:f,isSharing:a,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(lt,{resource:t,resourceType:n,currentUser:u,onShareTabTypeChange:S=>m(S),isSharing:a,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(lt,{resource:t,resourceType:n,currentUser:u,onShareTabTypeChange:S=>m(S),isSharing:a,isUpdating:l,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:w?j==="org"?e.jsx(ot,{resource:t,existingShares:p,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:h,currentAllUsersShare:T,onRemoveAccess:i}):e.jsx(ot,{resource:t,existingShares:y,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:R(),currentAllUsersShare:N,onRemoveAccess:i}):e.jsx(cr,{resource:t,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:d,currentAllUsersShare:N,onRemoveAccess:i})})]})})}function ge(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Oe(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Vt(t,n,a){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:u}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=ge(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(d,{onSuccess:()=>{u()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h}=t;if(d&&d.length>0){const f=ge(r,l,d.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{u()}})}if(m&&m.length>0){const f=Oe(r,l,m.map(g=>{var x,y;const j=(y=(x=i==null?void 0:i.shares)==null?void 0:x.specificOrgUsers)==null?void 0:y.find(p=>p.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(f,{onSuccess:()=>{u()}})}h&&h.length>0&&h.forEach(f=>{const g=ge(r,l,[{scope:"specific_org_user",orgUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{u()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=ge(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(d,{onSuccess:()=>{u()}})}else if(t.mode==="allTenantUsers"){const d=ge(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{u()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h,tenantId:f}=t;if(m&&m.length>0){const g=Oe(r,l,m.map(j=>{var y,p;const x=(p=(y=i==null?void 0:i.shares)==null?void 0:y.specificTenantUsers)==null?void 0:p.find(N=>N.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,tenantId:f,role:(x==null?void 0:x.role)||"VIEWER"}}));c(g,{onSuccess:()=>{u()}})}if(h&&h.length>0&&h.forEach(g=>{const j=ge(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:f,role:g.newRole}]);o(j,{onSuccess:()=>{u()}})}),d&&d.length>0){const g=ge(r,l,d.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,tenantId:f,role:j.role})));o(g,{onSuccess:()=>{u()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=Oe(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(d,{onSuccess:()=>{u()}})}else if(t.updateAccess){const d=ge(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{u()}})}else{const d=ge(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{u()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:m,usersToUpdate:h}=t;if(d&&d.length>0){const f=ge(r,l,d.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{u()}})}if(m&&m.length>0){const f=Oe(r,l,m.map(g=>{var x,y;const j=(y=(x=i==null?void 0:i.shares)==null?void 0:x.specificTenantUsers)==null?void 0:y.find(p=>p.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(f,{onSuccess:()=>{u()}})}h&&h.length>0&&h.forEach(f=>{const g=ge(r,l,[{scope:"specific_tenant_user",tenantUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{u()}})})}break}}function _t(t,n,a,r){var d,m,h,f,g,j;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:u}=r;if(o)if(t.length>0){const x=Oe(l,o,t.map(y=>{var N,T;const p=(T=(N=i==null?void 0:i.shares)==null?void 0:N.specificTenantUsers)==null?void 0:T.find(R=>R.tenantUserId===y);return{scope:"specific_tenant_user",tenantUserId:y,role:(p==null?void 0:p.role)||"VIEWER"}}));c(x,{onSuccess:()=>{u()},onError:y=>{console.error("Remove access failed:",y)}})}else{const x=n==="tenant"&&a==="allTenants",y=n==="tenant"&&a==="allTenantUsers";if(x){const p=(m=(d=i==null?void 0:i.shares)==null?void 0:d.allTenantsOnly)==null?void 0:m[0];if(p){const N=Oe(l,o,[{scope:"all_tenants_only",role:p.role}]);c(N,{onSuccess:()=>{u()},onError:T=>{console.error("Remove all-tenants access failed:",T)}})}}else if(y){const p=(f=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:f[0];if(p){const N=Oe(l,o,[{scope:"all_tenant_users",role:p.role}]);c(N,{onSuccess:()=>{u()},onError:T=>{console.error("Remove all-tenant-users access failed:",T)}})}}else{const p=(j=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:j[0];if(p){const N=Oe(l,o,[{scope:"org_users_only",role:p.role}]);c(N,{onSuccess:()=>{u()},onError:T=>{console.error("Remove org-wide access failed:",T)}})}}}}function dr(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=Ie(),{existingShares:u}=Be({debouncedSearchQuery:"",resourceId:t||"",resourceType:ae.DASHBOARD,userType:"tenant"}),d=A.useCallback(()=>{r.resetUserSelections()},[r]),m=A.useCallback(f=>{if(!t)return;const g={resourceType:ae.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:u,resetUserSelections:d};Vt(f,g,i)},[t,n,a,u,d,i]),h=A.useCallback(()=>{if(!t)return;const f={resourceType:ae.DASHBOARD,resourceId:t,removeMutation:a,existingShares:u,resetUserSelections:d};_t(l,o||"",c||"",f)},[t,n,a,u,d,l,o,c]);return{handleShareSubmit:m,handleRemoveAccess:h}}function ur(t,n,a){const{currentUser:r}=Ie(),l=s.useShareManagementActions(),o=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),i=s.useShareCurrentMode(),{existingShares:u}=Be({debouncedSearchQuery:"",resourceId:t||"",resourceType:ae.VISUAL,userType:"tenant"}),d=A.useCallback(()=>{l.resetUserSelections()},[l]),m=A.useCallback(f=>{if(!t)return;const g={resourceType:ae.VISUAL,resourceId:t,shareMutation:n,removeMutation:a,existingShares:u,resetUserSelections:d};Vt(f,g,r)},[t,n,a,u,d,r]),h=A.useCallback(()=>{if(!t)return;const f={resourceType:ae.VISUAL,resourceId:t,removeMutation:a,existingShares:u,resetUserSelections:d};_t(o,c||"",i||"",f)},[t,n,a,u,d,o,c,i]);return{handleShareSubmit:m,handleRemoveAccess:h}}function mr(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function zs(t){const[n,a]=A.useState(null),[r,l]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const u=await import(i);if(typeof u.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>u.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),a(null)}})()},[t]),n}function hr(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return n}}return t[0].id}async function it(t,n,a){if(!t||!n)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",n],l=a.getQueryData(r);if(l)return console.log("Using cached visual data for:",n),{data:l,fromCache:!0};console.log("Fetching visual data from network for:",n);const o=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return a.setQueryData(r,i),s.ue.dismiss(o),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(o),c}}function xr(t,n,a,r,l){const o=t.frameObject;n(o);const c=o.cards.find(i=>i.id===o.activeCardId);c&&a(c),r(!0),l(!0)}function pr(){var f;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=zs(((f=a.customCardPreferences)==null?void 0:f.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),u=s.useEditorStore(g=>g.selectedConnectionId),d=s.useEditorStore(g=>g.isShowingVisual),m=a.sql;return{getUpdatedFrame:A.useCallback(()=>{var p;let g=m;m&&!m.includes("{{")&&(g=mr(m),t(g));const j=(p=r==null?void 0:r.getState())==null?void 0:p.settings,x={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:u,sql:g,customCfg:d?a.customCfg:null,preferences:a.preferences,...j&&{customCardPreferences:{...a.customCardPreferences,settings:j}}},y=n.cards.map(N=>N.id===a.id?x:N);return{...n,cards:y,activeCardId:hr(y,n.activeCardId)}},[a,n,d,l,o,c,i,u,t,r,m])}}function Vs(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient(),a=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:l,setCard:o}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:u,addFrame:d,setIsDashboardPanelOpen:m}=s.useDashboardActions(),h=s.useDashboardStore(x=>x.selectedSheetId),f=Ya((a==null?void 0:a.id)||"",{enabled:!!(a!=null&&a.id)&&!!(t!=null&&t.accessToken)}),g=A.useCallback(async x=>{try{r(x);const{data:y,fromCache:p}=await it((t==null?void 0:t.accessToken)||"",x.id,n);return xr(y,l,o,c,i),{success:!0,fromCache:p}}catch(y){return console.error("Error editing visual:",y),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n,r,l,o,c,i]),j=A.useCallback(async x=>{try{if(r(x),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:y,fromCache:p}=await it((t==null?void 0:t.accessToken)||"",x.id,n),N=y.frameObject;if(!N)return{success:!1,error:"Visual has no frame data"};const T={...N,id:s.v4()};return d(h,T,"end"),c(!0),u(T.id),m(!1),{success:!0,fromCache:p}}catch(y){return console.error("Error adding visual:",y),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n,r,h,d,c,u,m]);return{visual:f.data,isLoading:f.isLoading,isError:f.isError,error:f.error,handleEditLibraryVisual:g,handleAddLibraryVisual:j,getUpdatedFrame:pr().getUpdatedFrame,refetch:f.refetch}}function fr(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),[l,o]=A.useState(""),[c,i]=A.useState(""),[u,d]=A.useState(!1),[m,h]=A.useState(null),[f,g]=A.useState(!1),[j,x]=A.useState(null),[y,p]=A.useState(null),{setIsDashboardEditing:N,setIsVisualEditing:T}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:b}=Vs(),{resources:w,isLoading:v,isError:D,createResource:C,updateResource:I,deleteResource:S,duplicateResource:O,shareResource:k,isCreating:E,isDeleting:M,removeResourceShares:B,isSharing:L,isRemovingShares:F,isUpdatingShares:V}=Ka(()=>{g(!1),x(null)},()=>{r(!1),o(""),i("")}),{handleShareSubmit:z,handleRemoveAccess:J}=ur((m==null?void 0:m.id)||null,k,B);Ie();const X=w.filter(Q=>{var re,de;return((re=Q==null?void 0:Q.title)==null?void 0:re.toLowerCase().includes(t.toLowerCase()))||((de=Q==null?void 0:Q.description)==null?void 0:de.toLowerCase().includes(t.toLowerCase()))}),K=Q=>new Date(Q).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{l.trim()&&C({title:l,description:c,isPrivate:!1})},Y=Q=>{x(Q),g(!0)},U=()=>{j&&S(j.id)},{startUpdating:Z,stopUpdating:q,isUpdating:P}=Tt(),W=(Q,re)=>{const de=re.title!==void 0?"title":"description";Z(Q,de),I({resourceId:Q,data:re},{onSuccess:()=>{q(Q,de)},onError:()=>{q(Q,de)}})},te=Q=>{p(Q),O(Q,{onSettled:()=>p(null)})},_=Q=>{R(Q)},ee=Q=>{b(Q)},le=Q=>{const re=w.find(de=>de.id===Q);re&&I({resourceId:Q,data:{isPrivate:!re.isPrivate}})},H=Q=>{h(Q),d(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),Be({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:ae.VISUAL,userType:"tenant"}),v?e.jsx(Dt,{}):D?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:a?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:Q=>o(Q.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:Q=>i(Q.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||E,children:E?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:E,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:E,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),E?"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:Q=>n(Q.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:X.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(s.ChartPie,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):X.map(Q=>e.jsx(Qa,{visual:Q,onAddVisual:ee,onEditVisual:_,onUpdateVisual:W,onDeleteClick:Y,onDuplicateVisual:te,onTogglePrivacy:le,onShareVisual:H,isDeleting:M,isDuplicating:y===Q.id,isTitleUpdating:P(Q.id,"title"),isDescriptionUpdating:P(Q.id,"description"),formatDate:K},Q.id))})}),u&&m&&e.jsx(zt,{resource:m,resourceType:ae.VISUAL,onShare:z,isSharing:L,isRemoving:F,isUpdating:V,onClose:()=>{d(!1),h(null)},onRemoveAccess:J}),e.jsx(s.AlertDialog,{open:f,onOpenChange:Q=>{!Q&&M||(g(Q),Q||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 "',j==null?void 0:j.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:M,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:M,children:M?"Deleting...":"Delete"})]})]})})]})}function gr({dashboard:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:u,onShareDashboard:d,formatDate:m,onDashboardItemClick:h}){var v,D,C;const{selectDashboard:f}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),[x,y]=A.useState(!1),[p,N]=A.useState(!1),T=s.useDashboardStore(I=>I.actions.setIsDashboardPanelOpen);A.useEffect(()=>{a?(y(!0),N(!0)):p&&(y(!1),N(!1))},[a,p]);const R=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Bs,{className:"h-3 w-3 text-purple-500"}):e.jsx(Ee,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Fe,{className:"h-3.5 w-3.5 text-slate-500"}),b=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),w=()=>{f(t),o(t.id),h==null||h(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:w,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:b()})}),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:I=>c==null?void 0:c(t.id,{title:I}),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:R()})]}),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:I=>c==null?void 0:c(t.id,{description:I}),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:x,onOpenChange:y,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:I=>I.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:I=>{I.preventDefault(),I.stopPropagation(),u(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),d(t)},children:[e.jsx(Ee,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),i(t),T(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((v=t.ownership.createdBy)==null?void 0:v.type)==="tenant"||((D=t.ownership.createdBy)==null?void 0:D.type)==="organization"&&j)&&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:m(t.lastModified)})]})]})]})]})})})]})]},t.id)}function jr({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 yr(t){const[n,a]=A.useState(""),[r,l]=A.useState(!1),[o,c]=A.useState(""),[i,u]=A.useState(""),[d,m]=A.useState(!1),[h,f]=A.useState(null),[g,j]=A.useState(!1),[x,y]=A.useState(null),[p,N]=A.useState(null),T=s.useManagementStore(H=>H.lastSelectedDashboard),R=s.useManagementStore(H=>H.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:b,isLoading:w,isError:v,createResource:D,updateResource:C,deleteResource:I,duplicateResource:S,isCreating:O,isDeleting:k,isSharing:E,isRemovingShares:M,isUpdatingShares:B,shareResource:L,removeResourceShares:F}=Ga(()=>{j(!1),y(null),T&&R(T)},()=>{l(!1),c(""),u("")}),{handleShareSubmit:V,handleRemoveAccess:z}=dr((h==null?void 0:h.id)||null,L,F),{currentUser:J}=Ie(),X=b.filter(H=>{var Q,re;return((Q=H==null?void 0:H.title)==null?void 0:Q.toLowerCase().includes(n.toLowerCase()))||((re=H==null?void 0:H.description)==null?void 0:re.toLowerCase().includes(n.toLowerCase()))}),K=H=>new Date(H).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{o.trim()&&D({title:o,description:i,isPrivate:!1})},Y=H=>{var Q;(Q=t.onLoadDashboard)==null||Q.call(t,H)},U=H=>{y(H),j(!0)},Z=()=>{x&&I(x.id)},q=H=>{N(H),S(H,{onSettled:()=>N(null)})},{startUpdating:P,stopUpdating:W,isUpdating:te}=Tt(),_=(H,Q)=>{const re=Q.title!==void 0?"title":"description";P(H,re),C({resourceId:H,data:Q},{onSuccess:()=>{W(H,re)},onError:()=>{W(H,re)}})},ee=H=>{const Q=b.find(re=>re.id===H);Q&&C({resourceId:H,data:{isPrivate:!Q.isPrivate}})},le=H=>{f(H),J==null||J.type,m(!0)};return Be({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ae.DASHBOARD,userType:"tenant"}),w?e.jsx(Dt,{}):v?e.jsx(jr,{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:H=>c(H.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:H=>u(H.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||O,children:O?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),u("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:O,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"h-8 w-full",size:"sm",disabled:O,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),O?"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:n,onChange:H=>a(H.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:X.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx($n,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):X.map(H=>e.jsx(gr,{dashboard:H,isDeleting:k,isDuplicating:p===H.id,isTitleUpdating:te(H.id,"title"),isDescriptionUpdating:te(H.id,"description"),onLoadDashboard:Y,onEditDashboard:t.onEditDashboard,onUpdateDashboard:_,onDeleteClick:U,onDuplicateDashboard:q,onTogglePrivacy:ee,onShareDashboard:le,formatDate:K,onDashboardItemClick:t.onDashboardItemClick},H.id))})}),d&&h&&e.jsx(zt,{resource:h,resourceType:ae.DASHBOARD,onShare:V,isSharing:E,isRemoving:M,isUpdating:B,onClose:()=>{m(!1),f(null)},onRemoveAccess:z}),e.jsx(s.AlertDialog,{open:g,onOpenChange:H=>{!H&&k||(j(H),H||y(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:k,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:H=>{H.preventDefault(),H.stopPropagation(),Z()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:k,children:k?"Deleting...":"Delete"})]})]})})]})}function Ut({isOpen:t,onClose:n,className:a,onDashboardItemClick:r}){s.useDashboardStore(g=>g.dashboard);const{setDashboard:l,addSheet:o}=s.useDashboardStore(g=>g.actions),{currentUser:c}=Ie(),i=c,[u,d]=s.useLocalStorageState("resource-management-active-tab","dashboards"),m=Lt(n,{enabled:t}),h=g=>{},f=g=>{console.log("Editing dashboard:",g)};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":"hidden -translate-x-full",a),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:i&&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:i.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:i.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:i.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:i.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.email}),i.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(i.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",i.id]})]})})]})})}),e.jsx(s.IconButton,{className:"h-6 p-1 text-muted-foreground hover:text-foreground",onClick:n,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:u,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(yr,{onLoadDashboard:h,onEditDashboard:f,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(fr,{})})]})})]})})}function vr(){var Z,q;const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{isLocalDev:a}=s.useDashboardPreferences();s.useDashboardStore(P=>P.theme);const r=s.useDashboardStore(P=>P.lenses),l=s.useDashboardStore(P=>P.selectedLensId),o=r==null?void 0:r.find(P=>P.id===l),c=s.useDashboardStore(P=>P.dashboard);s.useDashboardStore(P=>P.selectedSheetId);const i=s.useDashboardStore(P=>P.isDashboardEditing),u=s.useEditorStore(P=>P.card),d=s.useEditorStore(P=>P.selectedConnectionId),[m,h]=A.useState(!1),f=s.useDashboardStore(P=>P.isDashboardPanelOpen),g=s.useDashboardStore(P=>P.actions.setIsDashboardPanelOpen),j=s.useDashboardStore(P=>P.filterValues),x=s.useDashboardStore(P=>P.isVisualEditing),y=s.useManagementStore(P=>P.selectedDashboard),p=s.useManagementStore(P=>P.initialDashboard),N=y?(q=y==null?void 0:y.permissions)==null?void 0:q.canEdit:(Z=p==null?void 0:p.permissions)==null?void 0:Z.canEdit,T=s.useDashboardStore(P=>P.showFilters),R=s.useDashboardStore(P=>P.showDashboardJSON),b=s.useDashboardStore(P=>P.onSaveFunction),w=s.useDashboardStore(P=>P.actions.setShowFilters),{addFrame:v,setSelectedFrameId:D}=s.useDashboardStore(P=>P.actions),{getSelectedSheet:C,setIsDashboardEditing:I,setShowDashboardJSON:S}=s.useDashboardStore(P=>P.actions),O=C(),{setInitialDashboard:k}=s.useManagementStore(P=>P.actions),{resources:E}=Ps(ae.DASHBOARD);A.useEffect(()=>{if(E&&E.length>0){const P=c==null?void 0:c.id;if(P){const W=E.find(te=>te.id===P);W&&k(W)}}},[E,c==null?void 0:c.id,k]);const M=n.orgUserId||n.tenantId,B=i&&!x&&M&&N;function L(){var _,ee;const P=u.dataSource;if(P)return P;const W=(ee=(_=c.aiContext)==null?void 0:_.selectedEntities)==null?void 0:ee[0],te=W==null?void 0:W.type;if(W)return{connectionId:W.connectionId,connectionType:W.connectionType,type:te,selectedEntities:[W]}}const F=()=>{if(!i||!O)return;const W={dataSource:L(),mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},te={id:s.v4(),cards:[W],activeCardId:W.id};v(O.id,te),D(te.id)},V=()=>{I(!0)},[z,J]=A.useState(!1),X=kt(ae.DASHBOARD);async function K(){const P=xs(c);J(!0);const W={template:P};X.mutate({resourceId:P.id,data:W},{onSuccess:()=>{J(!1),s.ue.success("Dashboard saved!")},onError:()=>{J(!1),s.ue.error("Failed to save dashboard")}})}async function $(){if(h(!0),!l||!o)return;const P=xs(c),W=JSON.stringify(P),te={...o,template:W,filterValues:j};await Ls(te,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),b==null||b(P),h(!1)}if(x)return null;const Y=(o==null?void 0:o.name)||c.title,U=n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[U&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>g(!0),className:"h-7 p-2",children:e.jsx(Hn,{className:"h-4 w-4"})}),!x&&e.jsx(s.Label,{children:Y})]}),e.jsxs("div",{className:"flex gap-2",children:[a&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:s.invalidateToken,className:"h-7 p-2",children:e.jsx(ua,{className:"h-4 w-4"})}),!x&&e.jsx(wa,{}),!x&&e.jsx(wt,{}),i&&!x&&M&&a&&e.jsx(Ca,{}),!x&&M&&a&&e.jsx(Sa,{}),i&&!x&&M&&o&&a&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:m,onClick:$,size:"sm",children:[e.jsx(Ms,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),i&&!x&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!i,onClick:F,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!x&&!i&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:V,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),i&&!x&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{I(!1),S(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),B&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:z,onClick:K,size:"sm",children:[z?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ms,{className:"mr-2 h-4 w-4"}),z?"Saving...":"Save"]}),!T&&!x&&i&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>w(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!x&&i&&a&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>S(!R),size:"sm",variant:"ghost",children:e.jsx(Qe,{className:"h-4 w-4"})})}),!x&&a&&e.jsx(ya,{}),!x&&e.jsx(Ut,{isOpen:f,onClose:()=>g(!1)})]})]})}function br({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:u,showNone:d=!1}){const m=pe.useRef(null),[h,f]=pe.useState(!1),[g,j]=pe.useState("100%"),x=d?[...n||[],{id:"none",name:"None"}]:n;pe.useLayoutEffect(()=>{m.current&&j(m.current.offsetWidth)},[]);function y(){var N;return l?"Loading...":o?"Error":a?(N=n==null?void 0:n.find(T=>T.id===a))==null?void 0:N.name:`Select ${t}`}function p(N,T){r(T),f(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:f,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[u&&e.jsx("div",{className:"mr-2",children:u}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:y()})]}),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(bt,{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(N=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:N.name,onSelect:T=>p(T,N.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===N.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:N.name,children:N.name})]})},N.id))})]})]})})]})}function He({title:t,items:n,value:a,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:u,disabled:d=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":a;function f(){if(t==="Connection")return e.jsx(ia,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(ra,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(Mn,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:d,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",u),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(bt,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((x,y)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},y))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function j(){return e.jsx(br,{icon:f(),items:n,value:h,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:m==="select"?g():j()})})}function Nr({column:t}){const[n,a]=A.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:u,connectionType:d}=s.useEditorAside(),m=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),f=s.useEditorStore(x=>x.actions.setRunSql);function g(x,y){var R;const p=s.createSqlGenConfig(x,i,y),N=(R=u==null?void 0:u.find(b=>b.id===c))==null?void 0:R.name;m(p);const T=s.getSql(p,s.fmt(l||""),s.fmt(r),N||"",d,o||"");T&&(h(T),f(!0)),a(!1)}function j(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>g(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>g(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>g(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>g(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>g(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:j()})]})}function Cr({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Te,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(es,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(as,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})}function Ns({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",n),children:[e.jsx(Cr,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Sr({id:t,children:n,type:a="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:a}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:n})}function wr({onClick:t,column:n}){const a=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||u(m)||d(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function u(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function d(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(n),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(Ns,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(Ns,{column:n})}),e.jsx(Sr,{id:n.column_name,type:"column",children:e.jsx(Ns,{column:n})})]})}const Cs={id:"__placeholder__",role:"groupby",type:"string"},Ss={id:"__placeholder__",role:"groupby",type:"string"},ws={id:"__placeholder__",role:"metric",type:"number"},Ds={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},$t={id:"__placeholder__"},ze="droppable-group-by",Ve="droppable-metrics",_e="droppable-pivot-by",fs="sortable-group-by",Rs="sortable-metrics",gs="sortable-pivot-by",Os="droppable-filters",Fs="sortable-filters",_s="sortable-order-by";function Dr(){const t=s.useDndStore(E=>E.insertIndex),n=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.groupByColumns)||[]}),a=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.metricColumns)||[]}),r=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.filterColumns)||[]}),l=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.orderBy)||[]}),o=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:u,setPreviewMetricColumns:d,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:f,setMetricColumns:g,setFilterColumns:j,setOrderByColumns:x,setPivotByColumns:y}=s.useEditorActions(),{columns:p}=s.useDataColumns(),{formattedTableName:N}=s.useEditorAside(),T=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=E=>{var L;const{active:M,over:B}=E;if(((L=M.data.current)==null?void 0:L.type)==="column"&&B){const F=B.id,V=p.find(K=>K.column_name===M.id);if(!V)return;const z=s.isNumberDataType(V.data_type),J=s.isTextDataType(V.data_type),X=s.isDateDataType(V.data_type);if(J||X){if(n.some($=>$.id===F)){const $=n.findIndex(U=>U.id===F);c($);const Y=n.filter(U=>U.id!==Cs.id);Y.splice($,0,Cs),u(Y)}else if(B.id===ze){c(n.length);const $=[...n,Cs];u($),d(a),m(r)}}if(J||X){if(o.some($=>$.id===F)){const $=o.findIndex(U=>U.id===F);c($);const Y=o.filter(U=>U.id!==Ss.id);Y.splice($,0,Ss),h(Y)}else if(B.id===_e){c(o.length);const $=[...o,Ss];h($),u(n),d(a),m(r)}}if(z||J){if(a.some($=>$.id===F)){console.log("isOverMetricSortable",F);const $=a.findIndex(U=>U.id===F);c($);const Y=a.filter(U=>U.id!==ws.id);Y.splice($,0,ws),d(Y)}else if(B.id===Ve){c(a.length);const $=[...a,ws];d($),m(r),u(n),h(o)}}if(w(V)){if(r.some($=>$.id===F)){const $=r.findIndex(U=>U.id===F);c($);const Y=r.filter(U=>U.id!==Ds.id);Y.splice($,0,Ds),m(Y)}else if(B.id===Os){c(r.length);const $=[...r,Ds];m($),d(a),u(n),h(o)}}}else u(n),d(a),m(r),h(o)};function b(E){i(E.active.id),c(null),u(n),d(a),m(r),h(o)}function w(E){return!r.some(M=>M.name===E.column_name)}function v(E,M="SUM"){const{column_name:B,data_type:L}=E,F=[...a],V=t!==null?t:a.length,z={...E,id:Ce(B),name:B,label:ns(B,M),type:L,role:"metric",aggregate:M};F.splice(V,0,z),g(F)}function D(E){const M=s.isTextDataType(E.data_type);s.isDateDataType(E.data_type);const B=[...o],L=t!==null?t:o.length;let F;M?F={...E,id:Ce(E.column_name),name:E.column_name,type:E.data_type,role:"groupby"}:F={...E,id:Ce(E.column_name),name:E.column_name,type:E.data_type,role:"groupby",label:We(E.column_name,"month"),granularity:"month"},B.splice(L,0,F),y(B)}function C(E){const M=s.isTextDataType(E.data_type);s.isDateDataType(E.data_type);const B=[...n],L=t!==null?t:n.length;let F;M?F={...E,id:Ce(E.column_name),name:E.column_name,type:E.data_type,role:"groupby"}:F={...E,id:Ce(E.column_name),name:E.column_name,type:E.data_type,role:"groupby",label:We(E.column_name,"month"),granularity:"month"},B.splice(L,0,F),f(B)}function I(E){const M=[...r],B=t!==null?t:r.length,L={...E,id:Ce(E.column_name),name:E.column_name,type:E.data_type,sql:s.getDefaultFilterSql(E.data_type,N,s.fmt(E.column_name)),role:"filter"};M.splice(B,0,L),j(M)}function S(E){var F,V,z,J,X,K,$,Y;const{active:M,over:B}=E,L=M.data.current;if((L==null?void 0:L.type)==="column"&&B){const U=p.find(W=>W.column_name===M.id);if(!U)return;const Z=s.isNumberDataType(U.data_type),q=s.isTextDataType(U.data_type),P=s.isDateDataType(U.data_type);(q||P)&&(B.id===ze||((F=B.data.current)==null?void 0:F.type)===fs)&&C(U),(q||P)&&(B.id===_e||((V=B.data.current)==null?void 0:V.type)===gs)?D(U):(Z||q)&&(B.id===Ve||((z=B.data.current)==null?void 0:z.type)===Rs)?(Z&&v(U),q&&v(U,"COUNT")):w(U)&&(B.id===Os||((J=B.data.current)==null?void 0:J.type)===Fs)&&I(U)}if(B&&((X=B.data.current)==null?void 0:X.type)===fs&&n.some(U=>U.id===M.id)){const U=n.findIndex(q=>q.id===M.id),Z=n.findIndex(q=>q.id===B.id);if(U!==-1&&Z!==-1&&U!==Z){const q=[...n],[P]=q.splice(U,1);q.splice(Z,0,P),f(q)}}if(B&&((K=B.data.current)==null?void 0:K.type)===gs&&o.some(U=>U.id===M.id)){const U=o.findIndex(q=>q.id===M.id),Z=o.findIndex(q=>q.id===B.id);if(U!==-1&&Z!==-1&&U!==Z){const q=[...o],[P]=q.splice(U,1);q.splice(Z,0,P),y(q)}}if(B&&(($=B.data.current)==null?void 0:$.type)===Rs&&a.some(U=>U.id===M.id)){const U=a.findIndex(q=>q.id===M.id),Z=a.findIndex(q=>q.id===B.id);if(U!==-1&&Z!==-1&&U!==Z){const q=[...a],[P]=q.splice(U,1);q.splice(Z,0,P),g(q)}}if(B&&((Y=B.data.current)==null?void 0:Y.type)===Fs&&r.some(U=>U.id===M.id)){const U=r.findIndex(q=>q.id===M.id),Z=r.findIndex(q=>q.id===B.id);if(U!==-1&&Z!==-1&&U!==Z){const q=[...r],[P]=q.splice(U,1);q.splice(Z,0,P),j(q)}}O(E),i(null),c(null),u(n),d(a),m(r),h(o)}function O(E){const{active:M,over:B}=E,L=M.data.current;if((L==null?void 0:L.type)===_s&&B){const F=l.findIndex(z=>Ze(z.columnId)===M.id),V=l.findIndex(z=>Ze(z.columnId)===B.id);if(F!==-1&&V!==-1&&F!==V){const z=[...l],[J]=z.splice(F,1);z.splice(V,0,J),x(z)}}}function k(){i(null),c(null),u(n),d(a),m(r)}return{handleDragOver:R,handleDragEnd:S,handleDragStart:b,handleDragCancel:k,sensors:T}}function Ce(t){return`${t}-${s.v4()}`}function ns(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"SUM":return`Sum of ${a}`;case"COUNT":return`Count of ${a}`;case"DISTINCT":return`Unique ${a}`;case"AVG":return`Average of ${a}`;case"MIN":return`Min of ${a}`;case"MAX":return`Max of ${a}`;default:return a}}function Ze(t){return`${_s}-${t}`}function We(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function kr({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Te,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(es,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(as,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})}function Tr({schemaName:t,tableName:n,columns:a,status:r}){const[l,o]=A.useState(""),[c,i]=A.useState("all"),u=s.useEditorStore(F=>F.sqlGen),d=s.useEditorStore(F=>F.isDevMode);s.useEditorStore(F=>F.selectedConnectionId);const m=s.useEditorStore(F=>{var V,z;return(z=(V=F.card)==null?void 0:V.queryConfig)==null?void 0:z.metricColumns});s.useEditorStore(F=>{var V,z;return(z=(V=F.card)==null?void 0:V.queryConfig)==null?void 0:z.groupByColumns});const h=s.useEditorStore(F=>F.selectedDatabaseName);s.useEditorStore(F=>F.selectedSchemaName),s.useEditorStore(F=>F.selectedTableName);const f=s.useEditorStore(F=>F.selectedDatamodelId);s.useDashboardStore(F=>F.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:j}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:y,setCardSql:p,setRunSql:N,setSqlGen:T,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:b,modelItems:w,selectedDatamodelName:v}=s.useEditorAside();function D(F){var V;if(d){const z=s.createSqlGenConfig(F,u);T(z);const J=(V=w==null?void 0:w.find(K=>K.id===f))==null?void 0:V.name,X=s.getSql(z,s.fmt(t),s.fmt(n),J||"",b,h||"");X&&(p(X),N(!0))}if(!d){if(s.isTextDataType(F.data_type))if(m&&m.length>0){const z={...F,role:"groupby",id:Ce(F.column_name),name:F.column_name,type:F.data_type};y(z)}else{const z={...F,role:"metric",id:Ce(F.column_name),name:F.column_name,label:ns(F.column_name,"COUNT"),type:F.data_type,aggregate:"COUNT"};x(z)}if(s.isDateDataType(F.data_type)){const z={...F,role:"groupby",id:Ce(F.column_name),name:F.column_name,type:F.data_type,label:We(F.column_name,"month"),granularity:"month"};y(z)}if(s.isNumberDataType(F.data_type)){const z={...F,role:"metric",id:Ce(F.column_name),name:F.column_name,label:ns(F.column_name,"SUM"),type:F.data_type,aggregate:"SUM"};x(z)}}}function C(){const F=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:b,databaseName:h||""});R(!1);const V=b==="MSSQL"?`SELECT top 10 * FROM ${F}`:`SELECT * FROM ${F} LIMIT 10`;p(V),N(!0)}function I(){const F=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:b,databaseName:h||""});p(`SELECT COUNT(*) as count FROM ${F}`),N(!0)}const S=(a==null?void 0:a.filter(F=>F.column_name.toLowerCase().includes(l.toLowerCase())))||[],O=F=>s.isNumberDataType(F.data_type)?"number":"text",k=c==="all"?S:S.filter(F=>O(F)===c),E=S.filter(F=>O(F)==="text").length,M=S.filter(F=>O(F)==="number").length;function B(F){return d?e.jsxs("div",{className:"group flex cursor-pointer items-center justify-between border border-dashed border-background px-2 py-[6px] text-sm transition-colors hover:bg-muted/50",onClick:()=>D(F),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kr,{dataType:F.data_type}),e.jsx("span",{children:F.column_name})]}),e.jsx("div",{onClick:V=>V.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(F.data_type)&&e.jsx(Nr,{column:F})})]}):e.jsx(wr,{onClick:D,column:F})}function L(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:C,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(ea,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:I,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Nt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-4",children:Array.from({length:3}).map((F,V)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},V))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[d&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:L()}),a&&a.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:F=>o(F.target.value)})]}),S.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:F=>i(F),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:S.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:E})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:M})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[k.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),k.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:k==null?void 0:k.map(F=>e.jsx("div",{children:B(F)},F.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function qt({ColumnsComponent:t,type:n}){var se;const[a,r]=A.useState(!1),l=s.useEditorStore(ne=>ne.card),o=s.useEditorStore(ne=>ne.selectedConnectionId),c=s.useDashboardStore(ne=>ne.showFilters),i=s.useEditorStore(ne=>ne.selectedDatamodelId),u=s.useEditorStore(ne=>ne.selectedDatabaseName),d=s.useEditorStore(ne=>ne.selectedSchemaName),m=s.useEditorStore(ne=>ne.selectedTableName),h=s.useEditorStore(ne=>ne.isDevMode),{setSelectedTableName:f,setIsDevMode:g,setCardSql:j}=s.useEditorActions(),{connectionItems:x,modelItems:y,schemaItems:p,databaseItems:N,tableItems:T,columns:R,isConnectionsLoading:b,isModelsLoading:w,isConnectionsError:v,isModelsError:D,isDatabasesLoadingOrFetching:C,isDatabaseError:I,isSchemaLoadingOrFetching:S,isSchemaError:O,isColumnsError:k,isColumnsLoadingOrFetching:E,isTableLoadingOrFetching:M,isTableError:B,connectionType:L,isNonDbConnection:F,refetchDatabases:V,refetchModels:z,refetchSchemas:J,refetchTables:X,refetchColumns:K,refetchConnections:$,handleConnectionChange:Y,handleDatabaseChange:U,handleSchemaChange:Z,handleDatamodelChange:q,handleTableChange:P,tableName:W,schemaName:te}=s.useEditorAside(),{data:_,refetch:ee}=s.useDashboardCardQuery(l);function le(){return t?t(te,W,R):e.jsx(Tr,{schemaName:te,tableName:W,columns:R,status:E?"Loading...":k?"Error":"Success"})}function H(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function Q(ne){ne===!0?_&&(j(_.userSql),setTimeout(()=>{ee()},100)):j(""),g(ne)}function re(){if(!o||L==="S3"||L==="API")return null;if(!i||i==="none")return e.jsx(He,{refetch:V,showNone:!0,onChange:U,isError:I,isLoading:C,items:N,value:u||"",title:"Database",type:"combobox"})}function de(){if(o&&!F&&(!u||u==="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 Se(){if(!o||L==="S3"||L==="API")return null;if(!u||u==="none")return e.jsx(He,{refetch:z,showNone:!0,onChange:q,isError:D,isLoading:w,items:y,value:i||"",title:"Model",type:"combobox"})}function ve(){return!o||L==="S3"||L==="API"||!u||u==="none"?null:e.jsx(He,{refetch:J,onChange:Z,isError:O,isLoading:S,items:p,value:d||"",title:"Schema",type:"combobox"})}function fe(){function ne(){let ue=!1;return L==="API"?(ue=!1,ue):((L==="S3"||o&&u&&u!=="none"&&d)&&(ue=!0),ue)}return ne()?e.jsx(He,{refetch:X,onChange:P,isError:B,items:T,isLoading:M,value:m||"",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]":!c}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":a,"px-4 py-4":!a}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!a),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:a?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!a&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(He,{refetch:$,items:x,title:"Connection",value:o||"",onChange:Y,isLoading:b,isError:v,type:"combobox",connectionTooltip:((se=x==null?void 0:x.find(ne=>ne.id===o))==null?void 0:se.type)||""}),re(),de(),Se(),ve(),fe()]})]}),le(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="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:h,onCheckedChange:Q,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:H,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(ta,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function Yt({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,o]=A.useState(!1),c=A.useRef(null),i=A.useRef(!1);function u(){t&&!i.current&&navigator.clipboard.writeText(t)}function d(f){(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),u())}function m(){const f=window.getSelection();if(f&&f.toString().trim()!==""){const g=f.toString();navigator.clipboard.writeText(g),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:u,onKeyDown:d,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function Gt({sql:t,error:n,onDebugWithAssistant:a}){const r=s.useEditorStore(u=>u.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:[n&&e.jsx(Yt,{error:n}),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(Vn,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&a&&e.jsxs(s.Button,{onClick:a,size:"sm",variant:"secondary",children:[e.jsx(Kn,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Kt({sql:t,error:n,onDebugWithAssistant:a}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(yt,{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(Gt,{sql:t,error:n,onDebugWithAssistant:a})})]})}function Er(t){return s.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function Ht(t){const{theme:n}=s.useTheme(),a=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:u,setRunSql:d}=s.useEditorActions(),m=A.useRef(),h=A.useRef({}),f=r.cards.find(x=>x.id===o),g=A.useCallback(()=>{let x="";return t==="python"&&(x=(f==null?void 0:f.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(f==null?void 0:f.sql)||""),x},[t,f]);A.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const x=m.current.getModel();x&&(h.current[l.id]=x);let y=h.current[o];if(!y){const p=g();y=c.editor.createModel(p,t),h.current[o]=y}m.current.setModel(y)}u(o,l),d(!0)}},[o,l,u,c,d,t,g]),A.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",y=a==="system"?x:a;c.editor.defineTheme("default",{base:y==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":y==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),A.useEffect(()=>{const x=m.current;x&&c&&l&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function j(x,y){if(m.current=x,!h.current[l.id]){const p=x.getModel(),N=g();h.current[l.id]=p||(y==null?void 0:y.editor.createModel(N,t))||x.getModel()}x.setModel(h.current[l.id])}return{handleEditorDidMount:j}}function Ir(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Ht("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Ar(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Ht("python");function r(l){n(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function Mr({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 Us({variant:t="outline"}){var c;const{setCardSql:n}=s.useEditorActions();s.useEditorStore(i=>i.frame);const a=s.useEditorStore(i=>i.card);zs(((c=a.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),a.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=Vs();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Lr(){const t=s.useQueryClient(),[n,a]=A.useState(!1),r=s.useDashboardStore(d=>d.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=Vs(),c=s.useSelectedVisual(),i=Ha(),u=()=>{const d=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}a(!0),i.mutate({visualId:c.id,data:{frameObject:d}},{onSuccess:()=>{a(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{a(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:u,className:"h-8",size:"sm",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!n&&e.jsxs(e.Fragment,{children:[e.jsx(Ms,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function $s(){const{setTempQueryData:t,setSqlGen:n}=s.useEditorActions(),a=s.useQueryClient(),r=s.useEditorStore(u=>u.tempQueryData),l=s.useEditorStore(u=>u.onClose),o=s.useEditorStore(u=>u.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:u,queryData:d}=r;u&&d&&a.setQueryData(u,d)}n({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function js(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(y=>y.isDevMode),r=s.useEditorStore(y=>y.tempQueryData),l=s.useEditorStore(y=>y.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:u,setCardCustomCfg:d,setCardPreferences:m,updateDataSource:h,clearQueryConfig:f,setCardConfig:g,setCardType:j}=s.useEditorActions();function x(){const y=n.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:y}),n.setQueryData(o,null),n.removeQueries({queryKey:o,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),f(),g(void 0),u(""),d(""),m({}),j("bar")}return e.jsxs(s.Button,{onClick:x,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Rr(){const t=s.useQueryClient(),[n,a]=A.useState(!1),[r,l]=A.useState(!1);s.useEditorStore(z=>z.frame);const o=s.useEditorStore(z=>z.card);s.useEditorStore(z=>z.isShowingVisual),s.useEditorStore(z=>z.selectedConnectionId),s.useEditorStore(z=>z.tempQueryData),s.useEditorStore(z=>z.selectedDatabaseName),s.useEditorStore(z=>z.selectedDatamodelId),s.useEditorStore(z=>z.selectedSchemaName);const c=s.useEditorStore(z=>z.showAIDialog);s.useEditorStore(z=>z.selectedTableName);const i=s.useEditorStore(z=>{var J;return(J=z==null?void 0:z.card)==null?void 0:J.sql}),u=s.useEditorStore(z=>{var J;return(J=z==null?void 0:z.card)==null?void 0:J.python}),{sheetFilterValues:d}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:f,setTempQueryData:g,setPythonStdOut:j,setCardPreferences:x,setCardType:y,setCardPython:p,runAssistant:N,setShowAIDialog:T}=s.useEditorActions();s.useEditorStore(z=>z.onSave),s.useEditorStore(z=>z.onClose),s.useEditorStore(z=>z.actions.setSqlGen);const R=s.useEditorStore(z=>z.runSql),b=s.useEditorStore(z=>z.actions.setRunSql),w=s.useEditorStore(z=>z.actions.setIsSqlRunning),{data:v,isLoading:D,isFetching:C,isSuccess:I,isError:S,error:O,queryKey:k,refetch:E,errorMessage:M}=s.useDashboardCardQuery(o);A.useEffect(()=>{if(v&&(v.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((v==null?void 0:v.output)||""),v.records.length>0)){const{dimensionKeys:z}=s.getKeys(v.records);h(z)}},[v,h,j]),A.useEffect(()=>{(D||C)&&w(!0),(S||I)&&w(!1),S&&(h([]),j(""))},[D,C,v,j,S,I,w,h,O]),A.useEffect(()=>{R&&(t.getQueryData(k)||E(),b(!1))},[R,E,b,k,t]);async function B(){const z=`Can you help me debug this query in the current table scope?
|
|
342
342
|
|
|
343
343
|
Error:
|
|
344
344
|
|
|
@@ -350,12 +350,12 @@
|
|
|
350
350
|
|
|
351
351
|
${u?`Python:
|
|
352
352
|
${u}`:""}
|
|
353
|
-
`;b(z)}function L(){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(Mr,{jsonString:JSON.stringify(d,null,2)})})}),d&&d.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 F(){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:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Ir,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Ar,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function V(){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:D||C,onClick:()=>{E()},className:"h-8 shrink-0",size:"sm",children:[D||C?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(Kt,{sql:v==null?void 0:v.sql,error:M,onDebugWithAssistant:B}),e.jsx(js,{}),e.jsx(s.Toggle,{pressed:n,onPressedChange:z=>a(z),className:"h-8",size:"sm",variant:"outline",children:e.jsx(Er,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{T(!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,{}),e.jsx(Us,{})]})]})}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:[F(),L()]}),V()]})}function Or({card:t}){var b,T,R,N,w,v,D,C,I,S,O;const[n,a]=A.useState(!1),[r,l]=A.useState([]),{authToken:o}=s.useSemaphorContext(),c=s.getTokenParams(o==null?void 0:o.accessToken),i=s.useDashboardStore(k=>k.themeStyle),u={colors:((T=(b=i==null?void 0:i.chart)==null?void 0:b.dataset)==null?void 0:T.backgroundColor)||[]};(R=t.customCardPreferences)!=null&&R.inputData;const{getCard:d}=s.useCustomVisual(((N=t.customCardPreferences)==null?void 0:N.url)||""),m=((w=t.customCardPreferences)==null?void 0:w.visualType)||"single",h=s.useEditorStore(k=>k.frame),{setCustomCardPreferences:f}=s.useEditorActions(),{data:g}=s.useDashboardCardQuery(t),j=A.useCallback((k,E)=>{l(M=>({...M,[k]:E}))},[]);if(!((v=t.customCardPreferences)!=null&&v.componentName))return null;const x=d((D=t.customCardPreferences)==null?void 0:D.componentName);function y(k){a(k)}const p=Object.keys(((C=t.customCardPreferences)==null?void 0:C.dataInputCardIds)||{}).map(k=>{var B,L,F;const E=(L=(B=t.customCardPreferences)==null?void 0:B.dataInputCardIds)==null?void 0:L[k].cardId,M=(F=h==null?void 0:h.cards)==null?void 0:F.find(V=>V.id===E);return M||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(A.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[x&&m==="single"&&e.jsx(x,{editing:!0,params:c,theme:u,settings:(I=t.customCardPreferences)==null?void 0:I.settings,onDataChange:j,data:(g==null?void 0:g.records)||[]}),x&&m==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((S=t.customCardPreferences)==null?void 0:S.dataInputCardIds)||{}).map(k=>{var B,L,F;const E=(L=(B=t.customCardPreferences)==null?void 0:B.dataInputCardIds)==null?void 0:L[k].cardId,M=(F=h==null?void 0:h.cards)==null?void 0:F.find(V=>V.id===E);if(M)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:y,onDataChange:j,dataInputIndex:k,card:M},M.id+k)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:u,onDataChange:j,settings:p.map(k=>{var E;return(E=k==null?void 0:k.customCardPreferences)==null?void 0:E.settings}),data:p.map(k=>k!=null&&k.id?r==null?void 0:r[k.id]:[])})})]})]},(O=t.customCardPreferences)==null?void 0:O.componentName)})}function Qt({className:t,...n}){var D;const a=s.useEditorStore(C=>C.card),r=s.isExplorerCard(a),l=((D=a.customCardPreferences)==null?void 0:D.showCardHeader)??!0,o=s.useEditorStore(C=>C.frame),c=s.useDashboardStore(C=>C.dashboard.filters),i=s.useEditorStore(C=>C.actions.setRunSql),{updateFilter:u}=s.useDashboardActions(),d=c==null?void 0:c.find(C=>C.id===o.filterId),{data:m,isLoading:h,isFetching:f,errorMessage:g,pagination:j}=s.useDashboardCardQuery(a),{setCard:x,updateCardInFrame:y}=s.useEditorActions(),{data:p}=s.useTopoJson(a),b=A.useMemo(()=>{var C;return a.type!=="pivotTable"||!((C=m==null?void 0:m.records)!=null&&C.length)?null:{records:m.records,columnSubtotalMeta:m.columnSubtotalMeta,subtotalColumns:m.subtotalColumns||[],pivotSchema:m.pivotSchema||[],groupByColumns:m.groupByColumns}},[a.type,m==null?void 0:m.records,m==null?void 0:m.columnSubtotalMeta,m==null?void 0:m.subtotalColumns,m==null?void 0:m.pivotSchema,m==null?void 0:m.groupByColumns]),T=s.usePivotTableConfig(a,b),R=(C,I)=>{var O,k;const S={...a,paginationConfig:{page:C+1,pageSize:I}};x(S),y(S),a.sql&&((k=(O=a.preferences)==null?void 0:O.tablePrefs)!=null&&k.enableDevModePagination)&&i(!0)},N=A.useMemo(()=>!a.id||!(m!=null&&m.records)?null:s.createChartConfig({card:a,data:m==null?void 0:m.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:p}),[a.id,m==null?void 0:m.records,a.type,a.queryConfig,a.customCfg,a.preferences,p]);function w(C){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Or,{card:C})})}function v(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!f)return g?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||f)&&a.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return w(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&N)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:h||f?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:N})});if(a.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:a,data:(m==null?void 0:m.records)||[],paginationMetadata:j,onPaginationChange:R,isLoading:h||f})});if(a.type==="pivotTable"&&T)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.PivotTableVisual,{card:a,data:T.data,options:T.options,onAggregationChange:C=>{const I=s.handleAggregationChange(C,a.config),S={...a,config:I};x(S),y(S)},onAggregationLabelChange:C=>{const I=s.handleAggregationLabelChange(C,a.config),S={...a,config:I};x(S),y(S)}})});if(a.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:a,data:(m==null?void 0:m.records)||[],groupByColumns:m==null?void 0:m.groupByColumns,pivotSchema:m==null?void 0:m.pivotSchema,paginationMetadata:j,onPaginationChange:R,onAggregationChange:C=>{const I=s.handleAggregationChange(C,a.config),S={...a,config:I};x(S),y(S)},isLoading:h||f})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:C=>x({...a,title:C}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})})}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:C=>x({...a,description:C}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:d.title||d.column,onSave:C=>u({...d,title:C}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:d})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:v()})]})}const ks=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:n,onChange:a}),Fr=()=>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."})]})]}),Br=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ks,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ks,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ks,{language:"javascript",value:t,onChange:l})})]}),Pr=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function zr(){const[t,n]=A.useState(!1),[a,r]=A.useState(""),[l,o]=A.useState(""),[c,i]=A.useState(""),[u,d]=A.useState(""),m=s.useEditorStore(N=>N.card),h=s.useEditorStore(N=>N.card.customCfg),f=h?JSON.stringify(h,null,2):"",{data:g}=s.useDashboardCardQuery(m),{data:j}=s.useTopoJson(m),{setCardCustomCfg:x,setCustomVisualCode:y}=s.useEditorActions(),p=N=>{var w,v;return JSON.stringify({...N,data:{...N.data,datasets:(v=(w=N.data)==null?void 0:w.datasets)==null?void 0:v.map(D=>({...D,data:[]}))}},null,2)},b=()=>{var w,v;if(!((w=g==null?void 0:g.records)!=null&&w.length))return;const N=s.createChartConfig({card:m,data:g.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:j});if(N){r(p(N)),i(((v=m.preferences)==null?void 0:v.customVisualCode)||"");const D=s.merge(N,h);o(p(D))}},T=()=>{try{if(c&&y(c),l){const N=JSON.parse(l),w=s.getObjectDiff(JSON.parse(a),N);x(w),d("")}}catch{d("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:b,className:R?"":"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(Fr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Qt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Br,{customCode:c,cardCustomCfgString:f,mergedConfig:l,onConfigChange:N=>o(N??""),onCodeChange:N=>i(N??"")})]}),e.jsx(Pr,{error:u,hasCardCustomConfig:!!h,onReset:()=>{o(a),x(null)},onApply:T,onClose:()=>n(!1)})]})]})}function ys(t){const[n,a]=A.useState(null);return n}function Wt(){const{authToken:t}=s.useSemaphorContext(),{data:n,isLoading:a,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:n,isLoading:a,isFetching:r,isError:l}}function Jt(){const{data:t,isLoading:n,isError:a}=Wt(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:u=>Math.min(1e3*2**u,3e4)}))}),l=[];let o=n,c=a;return r.forEach((i,u)=>{var d;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((d=t==null?void 0:t.plugins)!=null&&d[u])){const m=t.plugins[u],h=i.data.visuals.map(f=>({name:f.name,pluginName:m.label,componentType:f.componentType,pluginType:m.type,icon:f.icon,chartType:f.chartType,url:m.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function Vr({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=Jt(),u=A.useCallback((d,m)=>{n(null),a({}),r(d),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[n,a,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((d,m)=>e.jsx(_r,{text:d.name,onClick:()=>u("custom",d),icon:d.icon},`${d.url}-${d.name}-${m}`))})]})}const _r=({text:t,icon:n,onClick:a})=>{const r=ys(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:a,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function Xt({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function u(m,h){o(null),r({}),a(m),["custom","text","map"].includes(m)&&(l(!0),i(void 0)),t==null||t()}const d=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:d,tooltip:"Table",onClick:()=>u("table"),className:"h-10 p-4",children:e.jsx(s.Table2,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Bar Chart",onClick:()=>u("bar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnIncreasing,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Line Chart",onClick:()=>u("line"),className:"h-10 p-4",children:e.jsx(s.ChartLine,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Stacked Bar Chart",onClick:()=>u("stackedBar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnStacked,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Stacked Line Chart",onClick:()=>u("stackedLine"),className:"h-10 p-4",children:e.jsx(s.MdStackedLineChart,{className:s.cn("size-5",n),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Scatter Chart",onClick:()=>u("scatter"),className:"h-10 p-4",children:e.jsx(s.ChartScatter,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Bubble Chart",onClick:()=>u("bubble"),className:"h-10 p-4",children:e.jsx(s.TbChartBubble,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Pie Chart",onClick:()=>u("pie"),className:"h-10 p-4",children:e.jsx(s.ChartPie,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Doughnut Chart",onClick:()=>u("doughnut"),className:"h-10 p-4",children:e.jsx(s.Donut,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Funnel Chart",onClick:()=>u("funnel"),className:"h-10 p-4",children:e.jsx(s.TbChartFunnel,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Radar Chart",onClick:()=>u("radar"),className:"h-10 p-4",children:e.jsx(s.Radar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Polar Area Chart",onClick:()=>u("polarArea"),className:"h-10 p-4",children:e.jsx(s.PiChartPolar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Tornado Chart",onClick:()=>u("tornado"),className:"h-10 p-4",children:e.jsx(s.Tornado,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>u("range"),className:"h-10 p-4",children:e.jsx(s.ChartNoAxesGantt,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"KPI",onClick:()=>u("kpi"),className:"h-10 p-4",children:e.jsx(s.TiSortNumerically,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Text",onClick:()=>u("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>u("map"),className:"h-10 p-4",children:e.jsx(s.Map,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Custom",onClick:()=>u("custom"),className:"h-10 p-4",children:e.jsx(ss,{className:s.cn("size-5",n)})})]})}function Ur({chartType:t,className:n,customIcon:a,componentName:r}){const l=ys();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:n});case"line":return e.jsx(s.ChartLine,{className:n});case"pie":return e.jsx(s.ChartPie,{className:n});case"radar":return e.jsx(s.Radar,{className:n});case"scatter":return e.jsx(s.ChartScatter,{className:n});case"bubble":return e.jsx(s.TbChartBubble,{className:n});case"doughnut":return e.jsx(s.Donut,{className:n});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:n});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:n});case"polarArea":return e.jsx(s.PiChartPolar,{className:n});case"funnel":return e.jsx(s.TbChartFunnel,{className:n});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:n});case"range":return e.jsx(s.ChartNoAxesGantt,{className:n});case"kpi":return e.jsx(s.TiSortNumerically,{className:n});case"text":return e.jsx(ye,{className:n});case"map":return e.jsx(s.Map,{className:n});case"custom":return a&&l?e.jsx(l,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(ss,{className:n});default:return e.jsx(s.Table2,{className:n})}}function Zt({variant:t="ghost"}){var o,c;const[n,a]=A.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(Ur,{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(Xt,{onChartTypeChange:()=>a(!1)}),e.jsx(Vr,{onChartTypeChange:()=>a(!1)})]})]})}function $r(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(nt,{className:"size-4"}):e.jsx(tt,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(nt,{className:"size-4"}):e.jsx(tt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function en(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.isShowingVisual),a=s.useEditorStore(c=>{var i,u;return(u=(i=c.card)==null?void 0:i.preferences)==null?void 0:u.chartOptions}),r=s.getChartGridStyle(a),{setChartGrid:l}=s.useEditorActions();function o(){const c=["xy","none","x","y"],u=(c.indexOf(r)+1)%c.length;l(c[u])}return n?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($r,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:o,children:[(r==="xy"||!r)&&e.jsx(Gn,{className:"size-4"}),r==="x"&&e.jsx(On,{className:"size-4"}),r==="y"&&e.jsx(ca,{className:"size-4"}),r==="none"&&e.jsx(xa,{className:"size-4"})]})]}):null}function qr(){const t=s.useEditorStore(j=>j.frame),n=s.useEditorStore(j=>j.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(j,x)=>{j.dataTransfer.setData("tabIndex",x.toString())},i=j=>{j.preventDefault()},u=(j,x)=>{const y=j.dataTransfer.getData("tabIndex");if(y===x.toString())return;const p=Array.from(t.cards),[b]=p.splice(parseInt(y),1);p.splice(x,0,b),a({...t,cards:p})};function d(j){const x=t.cards.filter(b=>b.id!==j),y=x[0],p={...t,cards:x,activeCardId:y.id};a(p),r(y.id),l(y)}function m(j,x){const y={...t,cards:[...t.cards,x],activeCardId:j.id};a(y),r(x.id)}function h(){const j={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};m(n,j)}function f(j){const x={dataSource:j.dataSource,connectionId:j.connectionId,lastSelectedDatabase:j.lastSelectedDatabase,lastSelectedSchema:j.lastSelectedSchema,lastSelectedTable:j.lastSelectedTable,lastSelectedDatamodelId:j.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(j,x)}function g(j,x){return j.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||j.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const y=x.displayTab===void 0?!1:!x.displayTab;l({...x,displayTab:y}),o({...x,displayTab:y})},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(zn,{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((j,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:y=>c(y,x),onDragOver:i,onDrop:y=>u(y,x),className:"",value:j.id,children:[g(t,j),e.jsx(s.Editable,{enabled:t.activeCardId===j.id,text:j.tabTitle||j.title,onSave:y=>{l({...n,tabTitle:y}),o({...n,tabTitle:y})},children:j.tabTitle||j.title},j.id),t.activeCardId===j.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>d(j.id)})]},j.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>f(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(Bn,{className:"h-4 w-4"})})]})})}function sn(){const t=s.useEditorStore(x=>x.frame),n=s.useEditorStore(x=>x.card),a=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:u}=s.useEditorActions(),{data:d,isLoading:m,isFetching:h}=s.useDashboardCardQuery(n);function f(x){const y=t.cards.find(p=>p.id===x);if(y!=null&&y.sql){r||i(!0),o(x);return}if(y!=null&&y.queryConfig){r&&i(!1),g(x),o(x);return}r||g(x),o(x)}function g(x){const y={...t,cards:t.cards.map(b=>b.id===n.id?n:b),activeCardId:x};l(y);const p=y.cards.find(b=>b.id===x);p.sql&&u(!0),c(p)}function j(){return n.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:d==null?void 0:d.records,isPending:m||h})})}):n.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:d==null?void 0:d.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Qt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:f,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:j()},x.id)),e.jsx(qr,{})]})}function cs({children:t}){var R,N;s.useEditorStore(w=>w.frame);const n=s.useEditorStore(w=>w.card),a=s.useEditorStore(w=>w.isDevMode),r=s.useEditorStore(w=>w.isShowingVisual),l=s.useDashboardStore(w=>w.isVisualEditing),o=s.useEditorStore(w=>w.pythonStdOut);s.useEditorStore(w=>w.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:u,runAssistant:d,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:f,isLoading:g,isFetching:j,errorMessage:x,refetch:y}=s.useDashboardCardQuery(n);function p(){const w=JSON.stringify(f==null?void 0:f.records,null,2),v=new Blob([w],{type:"application/json"}),D=URL.createObjectURL(v),C=document.createElement("a");C.href=D,C.download=`${n.title}.json`,C.click()}function b(){const v=[Object.keys(f==null?void 0:f.records.reduce((S,O)=>({...S,...O}),{})).join(","),...((f==null?void 0:f.records)||[]).map(S=>Object.values(S).join(","))].join(`
|
|
354
|
-
`),D=new Blob([v],{type:"text/csv"}),C=URL.createObjectURL(D),I=document.createElement("a");I.href=C,I.download=`${n.title}.csv`,I.click()}function T(){const w=`Can you get the documentation for ${n.type} chart?`;d(w)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Zt,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:T,children:e.jsx(An,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(zr,{})]}),!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:b,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:p,children:e.jsx(_n,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(f==null?void 0:f.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(en,{})]}),n.type==="table"&&n.sql&&!s.hasValidCardConfig(n.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((N=(R=n.preferences)==null?void 0:R.tablePrefs)==null?void 0:N.enableDevModePagination)??!1,onCheckedChange:w=>{var v;h({...n.preferences,tablePrefs:{...(v=n.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:w}}),y()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(Gr,{})]}),r?e.jsx(sn,{}):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(Yr,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":o}),children:[(f==null?void 0:f.records)&&(f==null?void 0:f.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(f==null?void 0:f.records)||[]}),x&&e.jsx(Yt,{error:x})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Yr(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Gr(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Kr(){var x,y;const t=s.useEditorStore(p=>p.card.customCardPreferences),{data:n}=Wt(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(p=>p.card),l=s.useEditorStore(p=>p.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:u}=s.useCustomVisual((t==null?void 0:t.url)||""),d=(x=u==null?void 0:u.visuals)==null?void 0:x.find(p=>p.name===(t==null?void 0:t.componentName));function m(p,b){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[p]:{cardId:b,hookRef:null}};c({...t,dataInputCardIds:R})}function h(p){var T,R;const b=(T=l==null?void 0:l.cards)==null?void 0:T.filter(N=>{var w;return((w=N==null?void 0:N.customCardPreferences)==null?void 0:w.visualType)!=="multiple"}).map(N=>({value:N.id,label:N.tabTitle||N.title}));return e.jsx("div",{className:"space-y-2",children:(R=p==null?void 0:p.dataInputs)==null?void 0:R.map((N,w)=>{var v,D;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:N}),e.jsx(je,{className:"col-span-6 h-8 w-full justify-between",label:"",options:b||[],value:((D=(v=t==null?void 0:t.dataInputCardIds)==null?void 0:v[w])==null?void 0:D.cardId)||"",onValueChange:C=>m(w,C)})]},w+Math.random())})})}function f(p,b,T=[],R=""){var N,w;return t?p==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((N=t==null?void 0:t.settings)==null?void 0:N[b])||R,onChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:v.target.value}})}},b):p==="select"?e.jsx(je,{className:"h-8 w-full",label:"",options:T,value:((w=t==null?void 0:t.settings)==null?void 0:w[b])||R,onValueChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[b]:v}})}}):null:null}function g(p){const b=Object.entries((p==null?void 0:p.settings)||{});return e.jsx("div",{className:"space-y-3",children:b.map(([T,R])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:R.title}),f(R.ui,T,R.options,R.defaultValue)]},T))})}function j(p){t&&c({...t,visualType:p,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(je,{icon:e.jsx(In,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:p=>c({...t||{url:"",componentName:""},url:p})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:j,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(je,{icon:e.jsx(Fn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(p=>p.type===o).map(p=>({value:p.name,label:p.name})))||[],value:t.componentName,onValueChange:p=>{console.log("changing value",p),c({...t,componentName:p})}})})]})})]}),((y=r==null?void 0:r.customCardPreferences)==null?void 0:y.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[d&&d.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(d)})]}),d&&d.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(d)})})]})]})]})}function qe(){const[t,n]=A.useState([]),a=s.useEditorStore(d=>d.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(d=>d.actions),o=s.useEditorStore(d=>d.queryResultColumns);s.useEditorStore(d=>{var m;return(m=d.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),A.useEffect(()=>{o&&n(new Array(o.length).fill(!1))},[o]);function c(d,m){var h,f;m?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:d,expression:""}]}):l({...a,onClickFilter:[{columnIndex:d,expression:""}]}):(l({...a,onClickFilter:(f=a==null?void 0:a.onClickFilter)==null?void 0:f.filter(g=>g.columnIndex!==d)}),n(g=>{const j=[...g];return j[d]=!1,j}))}function i(d,m){var f;const h=(f=a==null?void 0:a.onClickFilter)==null?void 0:f.map(g=>g.columnIndex===d?{...g,expression:m.target.value}:g);l({...a,onClickFilter:h})}function u(d){var m,h,f,g;if(t!=null&&t[d]||(h=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(j=>j.columnIndex===d))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(f=a==null?void 0:a.onClickFilter)==null?void 0:f.find(j=>j.columnIndex===d))==null?void 0:g.expression,onChange:j=>i(d,j),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:o==null?void 0:o.map((d,m)=>{var h,f;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(g=>g.columnIndex===m)),onCheckedChange:g=>c(m,g)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:d}),e.jsx("div",{className:"flex items-center gap-2",children:((f=a==null?void 0:a.onClickFilter)==null?void 0:f.find(g=>g.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{n(g=>{const j=[...g];return j[m]=!g[m],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),u(m)]})},d)})})}function Hr({idx:t}){var i;const n=s.useEditorStore(u=>{var d;return(d=u.card)==null?void 0:d.preferences}),a=s.useEditorStore(u=>{var d;return(d=u.card.preferences)==null?void 0:d.datasetOptions}),r=s.useEditorStore(u=>u.actions.setCardPreferences),l=(i=n==null?void 0:n.chartOptions)==null?void 0:i.indexAxis,o=a==null?void 0:a.find(u=>u.idx===t);function c(u,d){(u==="end"||u==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:u!=="none",align:u,anchor:u,clamp:!0};if(!o)r({...n,datasetOptions:[...a||[],{idx:d,datalabels:m}]});else{const h={...o};h.datalabels=m;const f=a==null?void 0:a.map(g=>g.idx===d?h:g);r({...n,datasetOptions:f})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Ct,{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(Wn,{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(Xn,{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(Jn,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function Qr(){const t=s.useEditorStore(o=>o.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function vs({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function tn(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var d,m,h;return(h=(m=(d=u==null?void 0:u.card)==null?void 0:d.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=Qr();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(u=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:u,children:nn(u)},u))})]}),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((u,d)=>e.jsx(an,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:u,idx:d},u))})]})]})}function nn(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function an({col:t,idx:n,className:a,iconClassName:r,children:l}){const o=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,f;return(f=(h=m.card)==null?void 0:h.preferences)==null?void 0:f.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===n),{setCardPreferences:u}=s.useEditorStore(m=>m.actions);function d(m){if(!i)u({...o,datasetOptions:[...c||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const f=c==null?void 0:c.map(g=>g.idx===n?h:g);u({...o,datasetOptions:f})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(vs,{className:"max-w-[100px]",title:t,children:nn(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>d("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>d("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>d("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Hr,{idx:n})]})]})}function qs(){const t=s.useEditorStore(g=>g.selectedConnectionId),n=s.useEditorStore(g=>g.selectedDatamodelId),a=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),l=s.useEditorStore(g=>g.selectedTableName),o=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:u}=s.useDashboardActions(),{modelItems:d,tableName:m,connectionType:h}=s.useEditorAside();function f(g,j="dashboard",x){var D;const y=s.fmt(g.column_name),p=s.fmt(a||""),b=s.fmt(r||""),T=s.fmt(m);let R=s.getQualifiedTableName({schemaName:b,tableName:T,connectionType:h,databaseName:p}),N=`${R}.${y}`;const w=(D=d==null?void 0:d.find(C=>C.id===n))==null?void 0:D.name;n&&n!=="none"&&(N=`${s.DATAMODEL_NAMESPCACE}.${w}.${y}`,R=`${s.DATAMODEL_NAMESPCACE}.${w}`),x!=null&&x.qualifiedFieldName&&(N=x.qualifiedFieldName),x!=null&&x.entityName&&(R=x.entityName);const v=o==null?void 0:o.find(C=>C.column===N&&C.table===T&&(C.database===p||C.database===a));if(v)u(v.id),i(v.id);else{const C=s.v4();return m==="api"&&t?(c({location:j,id:C,column:N,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,R,y)}),C):(c({id:C,location:j,column:N,title:g.column_name,dataType:g.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,R,y)}),C)}}return{assignFilter:f}}function Je(){const t=s.useDashboardStore(i=>i.dashboard.filters),n=s.useEditorStore(i=>i.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=qs();function o(i){const u=l(i,"frame");a({...n,filterId:u})}const c=t==null?void 0:t.find(i=>i.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(Wr,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function Wr({columns:t,onSelect:n}){var c;const[a,r]=pe.useState(!1),[l,o]=pe.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:u=>{const d=u===l?"":u;o(d),r(!1),d&&n(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function 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:n=>n.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(tn,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(qe,{}),e.jsx(Je,{})]})]})]})})}function Xr({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(qe,{}),e.jsx(Je,{})]})]})]})})}function rn(){const t=s.useEditorStore(i=>i.card.type),n=s.useEditorStore(i=>i.isDevMode),a=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var m;const u={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},d={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(m=a==null?void 0:a.chartOptions)==null?void 0:m.plugins,...u}}};r(d)}function o(){var i,u,d;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((d=(u=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:u.datalabels)==null?void 0:d.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,u,d;return e.jsx("div",{children:e.jsxs(s.Select,{value:((d=(u=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:u.datalabels)==null?void 0:d.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?o():c()})}const Zr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},el={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function sl(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:tl(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(rn,{}),e.jsx(qe,{}),e.jsx(Je,{})]})]})}function tl(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(Zr,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(el,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 nl({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(c,i,u){const d=[...t];d[c]={...d[c],[i]:u},n(d)}function l(c){const i=[...t];i.splice(c,1),n(i)}function o(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:o,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:u=>r(i,"start",u.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:u=>r(i,"end",u.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:u=>r(i,"color",u.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function al(){var m,h,f,g,j;const t=s.useEditorStore(x=>x.card.preferences),n=s.useEditorStore(x=>x.actions.setCardPreferences),a=s.useEditorStore(x=>x.card),r=s.isExplorerCard(a),l=s.useEditorStore(x=>x.actions.setNumberFormat);s.useEditorStore(x=>{var y,p;return(p=(y=x.card.preferences)==null?void 0:y.formatNumber)==null?void 0:p.decimalPlaces});const o=s.useEditorStore(x=>{var y,p;return(p=(y=x.card.preferences)==null?void 0:y.formatNumber)==null?void 0:p.locale}),c=s.useEditorStore(x=>{var y,p;return(p=(y=x.card.preferences)==null?void 0:y.formatNumber)==null?void 0:p.currency});s.useEditorStore(x=>x.actions.setFilterOnClickField);const i=s.useEditorStore(x=>{var y,p;return(p=(y=x.card.preferences)==null?void 0:y.formatNumber)==null?void 0:p.colorRanges})||[],u=s.useEditorStore(x=>x.actions.setColorRanges),d=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(x=>x.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:x=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:x}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:x=>{var y,p,b;return l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,((p=t==null?void 0:t.formatNumber)==null?void 0:p.currency)||"",x,((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(x=>e.jsx(s.SelectItem,{value:x.locale,children:x.locale},x.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:x=>{var y,p,b;console.log("currency",x),l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,x==="none"?"":x,((p=t==null?void 0:t.formatNumber)==null?void 0:p.locale)||"",((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),d.map(x=>e.jsx(s.SelectItem,{value:x,children:x},x))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((g=(f=t==null?void 0:t.formatNumber)==null?void 0:f.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:x=>{var y,p,b;return l(Number(x),((y=t==null?void 0:t.formatNumber)==null?void 0:y.currency)||"",((p=t==null?void 0:t.formatNumber)==null?void 0:p.locale)||"",((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(x=>e.jsx(s.SelectItem,{value:x,children:x},x))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((j=t==null?void 0:t.formatNumber)==null?void 0:j.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:x=>{var y,p,b;return l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,((p=t==null?void 0:t.formatNumber)==null?void 0:p.currency)||"",((b=t==null?void 0:t.formatNumber)==null?void 0:b.locale)||"",x.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(nl,{colorRanges:i,setColorRanges:u})]})]})}function rl(){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(al,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function Ts({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const ll=[{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"}],ol=["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"],il=ol.map(t=>({label:t,value:t}));function cl(){var u,d,m,h,f,g,j,x,y,p,b,T,R,N,w,v,D,C;const t=s.useEditorStore(I=>I.card),n=(d=(u=t==null?void 0:t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:d.topoJsonUrl,[a,r]=A.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(I=>({label:I,value:I}))||[],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(Ts,{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(Ts,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(je,{className:"h-9",options:i,onValueChange:I=>{console.log("value",I),l({...t.preferences,mapVisualOptions:{topoJsonUrl:I}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:I=>{r(I.target.value)},onBlur:()=>{var I;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(je,{className:"h-9",options:c,value:((g=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:I=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,objectKey:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(je,{className:"h-9",options:ll,value:((x=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:I=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projection:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(je,{className:"h-9",options:il,value:((p=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:p.colorScale)||"",label:"Select Color Scale",onValueChange:I=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,colorScale:I}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ts,{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:((T=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:T.projectionScale)||1,onChange:I=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionScale:Number(I.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(N=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:N.projectionOffset)==null?void 0:w[0])||0,onChange:I=>{var S,O,k,E;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[Number(I.target.value),((E=(k=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:E[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((C=(D=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:C[1])||0,onChange:I=>{var S,O,k,E;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[((E=(k=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:E[0])||0,Number(I.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(qe,{})]})}function dl(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:n}=s.useEditorStore(l=>l.actions);function a(l){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function ds({cardType:t,docContent:n,suffix:a="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${a}`}),e.jsx(s.AccordionContent,{children:n||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(dl,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(qe,{}),e.jsx(Je,{})]})]})]})})}function ul(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(je,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{n(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[a(),e.jsx(tn,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(qe,{}),e.jsx(Je,{})]})]})]})})}function ml({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(qe,{}),e.jsx(Je,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function ln({color:t,onColorChange:n,onClose:a}){const[r,l]=A.useState(0),[o,c]=A.useState(100),[i,u]=A.useState(50),[d,m]=A.useState(t);A.useEffect(()=>{const y=ct(t);if(y){const p=dt(y.r,y.g,y.b);l(p.h),c(p.s),u(p.l),m(t)}},[t]);const h=y=>{l(y),g(y,o,i)},f=y=>{const p=y.currentTarget.getBoundingClientRect(),b=Math.max(0,Math.min(1,(y.clientX-p.left)/p.width)),T=Math.max(0,Math.min(1,(y.clientY-p.top)/p.height)),R=b*100,N=(1-T)*100;c(R),u(N),g(r,R,N)},g=(y,p,b)=>{const T=xl(y,p,b),R=hl(T.r,T.g,T.b);m(R)},j=y=>{if(m(y),/^#[0-9A-Fa-f]{6}$/.test(y)){const p=ct(y);if(p){const b=dt(p.r,p.g,p.b);l(b.h),c(b.s),u(b.l)}}},x=()=>{/^#[0-9A-Fa-f]{6}$/.test(d)&&(n(d),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:f,onMouseMove:y=>{y.buttons===1&&f(y)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:d}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:y=>h(Number(y.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:d,onChange:y=>j(y.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:d}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:x,children:"OK"})]})]})}function ct(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function hl(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function dt(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let o=0,c=0;const i=(r+l)/2;if(r!==l){const u=r-l;switch(c=i>.5?u/(2-r-l):u/(r+l),r){case t:o=((n-a)/u+(n<a?6:0))/6;break;case n:o=((a-t)/u+2)/6;break;case a:o=((t-n)/u+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function xl(t,n,a){t/=360,n/=100,a/=100;let r,l,o;if(n===0)r=l=o=a;else{const c=(d,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?d+(m-d)*6*h:h<.5?m:h<.6666666666666666?d+(m-d)*(.6666666666666666-h)*6:d),i=a<.5?a*(1+n):a+n-a*n,u=2*a-i;r=c(u,i,t+1/3),l=c(u,i,t),o=c(u,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const pl=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function on(){var T,R,N,w,v,D,C,I,S,O;const t=s.useEditorStore(k=>k.card),n=s.useEditorStore(k=>{var E;return(E=k.card)==null?void 0:E.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=A.useState({}),[i,u]=A.useState(null),[d,m]=A.useState(null),h=A.useMemo(()=>{var B,L,F,V,z,J,X;if(!(l!=null&&l.records)||l.records.length===0)return[];const k=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",E=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",M=((B=t==null?void 0:t.config)==null?void 0:B.pivotByColumns)&&t.config.pivotByColumns.length>0;if((k||E)&&M){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const K=new Set;return l.pivotSchema.forEach($=>{$.alias&&K.add($.alias)}),Array.from(K)}if(l.records.length>0){const K=l.records[0],$=Object.keys(K),Y=new Set;(L=t==null?void 0:t.config)!=null&&L.groupByColumns&&t.config.groupByColumns.forEach(q=>{Y.add(q.label||q.name),Y.add(q.alias||q.name)});const U=new Set;return(F=t==null?void 0:t.config)!=null&&F.metricColumns&&t.config.metricColumns.forEach(q=>{const P=q.alias||q.name;U.add(P),U.add(`${P}_count`),U.add(`${P}_sum`),U.add(`${P}_avg`),U.add(`${P}_min`),U.add(`${P}_max`);const W=q.entityName||q.qualifiedEntityName;W&&(U.add(`${W}_${P}`),U.add(`${W}_${P}_count`))}),$.filter(q=>!Y.has(q)&&!U.has(q))}}if((E||k)&&!M&&((z=(V=t==null?void 0:t.config)==null?void 0:V.metricColumns)!=null&&z.length))return t.config.metricColumns.map(K=>K.alias||K.label||K.name);if((X=(J=t==null?void 0:t.config)==null?void 0:J.groupByColumns)!=null&&X.length){const K=t.config.groupByColumns[0],$=K.label||K.name,Y=new Set;return l.records.forEach(U=>{const Z=U[$];Z!=null&&Y.add(String(Z))}),Array.from(Y)}return[]},[l,(T=t==null?void 0:t.config)==null?void 0:T.groupByColumns,(R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns,(N=t==null?void 0:t.config)==null?void 0:N.metricColumns,t==null?void 0:t.type]),f=A.useMemo(()=>s.getDefaultChartColors(),[]);A.useEffect(()=>{const k={};h.forEach((E,M)=>{k[E]=s.getColorForValue(E,M,n==null?void 0:n.colorConfig)}),c(k)},[h,n==null?void 0:n.colorConfig,f]);const g=(k,E)=>{const M={...o,[k]:E};c(M);const B={...n||{},colorConfig:{segments:M}};a(B);const L={...t,preferences:B};r(L)},j=(k,E)=>{var z;const M=f[E%f.length],{[k]:B,...L}=((z=n==null?void 0:n.colorConfig)==null?void 0:z.segments)||{},F={...n||{},colorConfig:{segments:L}};a(F);const V={...t,preferences:F};r(V),c(J=>({...J,[k]:M}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((v=(w=t==null?void 0:t.config)==null?void 0:w.groupByColumns)==null?void 0:v.length)||((C=(D=t==null?void 0:t.config)==null?void 0:D.pivotByColumns)==null?void 0:C.length):(S=(I=t==null?void 0:t.config)==null?void 0:I.groupByColumns)==null?void 0:S.length)||["table","kpi","text","custom"].includes(t.type))return null;const p=()=>{const k={...n||{},colorConfig:{segments:{}}};a(k);const E={...t,preferences:k};r(E);const M={};h.forEach((B,L)=>{M[B]=s.getColorForValue(B,L,void 0)}),c(M)},b=Object.keys(((O=n==null?void 0:n.colorConfig)==null?void 0:O.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(la,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:b&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:p,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((k,E)=>{const M=s.isDefaultColor(o[k],E),B=!M;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===k,onOpenChange:L=>u(L?k:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[k]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:f.slice(0,10).map((L,F)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[k]===L?"border-gray-900":"border-transparent"),style:{backgroundColor:L},onClick:()=>{g(k,L),u(null)},children:[F===E%f.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:L})]},`default-${F}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:pl.map((L,F)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[k]===L?"border-2 border-gray-900":L==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:L},onClick:()=>{g(k,L),u(null)},children:e.jsx("span",{className:"sr-only",children:L})},`preset-${F}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{m({value:k,color:o[k]}),u(null)},children:"Custom color"}),!M&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(k,E),u(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:k}),B&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},k)})}),d&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(ln,{color:d.color,onColorChange:k=>{g(d.value,k),m(null)},onClose:()=>m(null)})})]})]})})]})}function De({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[o,c]=A.useState(t??""),[i,u]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const d=()=>{n(o),u(!1)},m=()=>{c(t??""),u(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),u(!0)},onFocus:()=>u(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?d():h.key==="Escape"&&m()},"aria-label":a||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:d,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const fl=["auto","number","currency","percent","scientific","date"],gl=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"KRW",label:"KRW - South Korean Won"}],jl=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],yl=t=>t.charAt(0).toUpperCase()+t.slice(1);function Ys({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,u)=>{n({...t,[i]:u})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:fl.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":yl(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:gl.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:jl.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function ut({axis:t,label:n,type:a,config:r,onChange:l}){var h,f,g,j,x,y,p,b,T,R,N,w;const o=(v,D)=>{l({...r,[v]:D})},c=(v,D)=>{var C,I;l({...r,name:{enabled:v==="enabled"?D:((C=r==null?void 0:r.name)==null?void 0:C.enabled)??!1,text:v==="text"?D:(I=r==null?void 0:r.name)==null?void 0:I.text}})},i=(v,D)=>{var C,I;l({...r,labels:{enabled:v==="enabled"?D:((C=r==null?void 0:r.labels)==null?void 0:C.enabled)??!0,rotation:v==="rotation"?D:(I=r==null?void 0:r.labels)==null?void 0:I.rotation}})},u=(v,D)=>{l({...r,scale:{...r==null?void 0:r.scale,[v]:D===""?"auto":Number(D)}})},d=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:v=>o("enabled",v),onClick:v=>v.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:v=>c("enabled",v)})]}),((f=r==null?void 0:r.name)==null?void 0:f.enabled)&&e.jsx(De,{placeholder:`${n} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:v=>c("text",v),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:v=>o("position",v),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":s.titleCase(v)},v))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((j=r==null?void 0:r.labels)==null?void 0:j.enabled)!==!1,onCheckedChange:v=>i("enabled",v)})]}),((x=r==null?void 0:r.labels)==null?void 0:x.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((y=r==null?void 0:r.labels)==null?void 0:y.rotation)||"auto"),onValueChange:v=>i("rotation",v==="auto"?"auto":Number(v)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":`${v}°`},v))})]})]})]}),a==="value"&&e.jsx(Ys,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:v=>l({...r,formatOptions:v}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(De,{type:"number",placeholder:"auto",value:((p=r==null?void 0:r.scale)==null?void 0:p.min)==="auto"||((b=r==null?void 0:r.scale)==null?void 0:b.min)===void 0?"":String(r.scale.min),onSave:v=>u("min",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(De,{type:"number",placeholder:"auto",value:((T=r==null?void 0:r.scale)==null?void 0:T.max)==="auto"||((R=r==null?void 0:r.scale)==null?void 0:R.max)===void 0?"":String(r.scale.max),onSave:v=>u("max",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(De,{type:"number",placeholder:"auto",value:((N=r==null?void 0:r.scale)==null?void 0:N.stepSize)==="auto"||((w=r==null?void 0:r.scale)==null?void 0:w.stepSize)===void 0?"":String(r.scale.stepSize),onSave:v=>u("stepSize",v),className:""})})]})]})]})]})]})}function cn(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const d={...n||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};a(d);const m={...t,preferences:d};r(m)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(ut,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(ut,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function dn(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var m,h,f,g;return(g=(f=(h=(m=d.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:f.plugins)==null?void 0:g.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(d,m)=>{const h={...n,[d]:m};a(h)},i=["top","bottom","left","right"],u=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??o,onCheckedChange:d=>c("display",d)})]}),((n==null?void 0:n.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||r,onValueChange:d=>c("position",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(d=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:s.titleCase(d)},d))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||l,onValueChange:d=>c("align",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(d=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:s.titleCase(d)},d))})]})]})]})]})})]})}function un(){var D,C,I,S,O,k,E,M,B;const t=s.useEditorStore(L=>L.card),n=s.useEditorStore(L=>{var F,V;return(V=(F=L.card)==null?void 0:F.preferences)==null?void 0:V.dataLabelsConfig}),a=s.useEditorStore(L=>{var F;return(F=L.card)==null?void 0:F.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((D=a==null?void 0:a.chartOptions)==null?void 0:D.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",u=!i,d=(I=(C=a==null?void 0:a.chartOptions)==null?void 0:C.plugins)==null?void 0:I.datalabels,m=(d==null?void 0:d.display)!==!1&&((d==null?void 0:d.anchor)||(d==null?void 0:d.align)),h=(n==null?void 0:n.enabled)!==void 0?n.enabled:m,f=(L,F)=>{const V={...n,[L]:F},z={...t.preferences||{},dataLabelsConfig:V};r(z);const J={...t,preferences:z};l(J)},g=(L,F)=>{const V={...n,font:{...n==null?void 0:n.font,[L]:F}},z={...t.preferences||{},dataLabelsConfig:V};r(z);const J={...t,preferences:z};l(J)},j=(L,F)=>{const V={...n,formatOptions:{...n==null?void 0:n.formatOptions,[L]:F}},z={...t.preferences||{},dataLabelsConfig:V};r(z);const J={...t,preferences:z};l(J)},y=(()=>{const L=t.type;return L==="stackedBar"||L==="stackedLine"||L==="pie"||L==="doughnut"?"center":o?"right":"top"})();let p=[];c||i?p=["center"]:p=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(F=>F!==y),"custom"];const b=()=>s.titleCase(y),T=["center","start","end"],R=["center","start","end","top","bottom"],N=u?["auto","number","currency","percent","none"]:["number","currency","percent","none"],w=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],v=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:L=>f("enabled",L)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:L=>f("position",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:p.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:L==="auto"?b():L==="custom"?"Custom (Advanced)":s.titleCase(L)},L))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:L=>f("showTotal",L)})]}),(n==null?void 0:n.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(n==null?void 0:n.anchor)||"center",onValueChange:L=>f("anchor",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:T.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:s.titleCase(L)},L))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((n==null?void 0:n.align)||"center"),onValueChange:L=>f("align",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:R.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:s.titleCase(L)},L))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(u?"auto":"none"),onValueChange:L=>f("format",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:L==="auto"&&u?"Auto (Use Axis)":L==="none"?"None (Raw Value)":s.titleCase(L)},L))})]})]}),(n==null?void 0:n.format)&&!["auto","none"].includes(n.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(n.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(De,{type:"number",placeholder:"0",value:String(((S=n==null?void 0:n.formatOptions)==null?void 0:S.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:L=>j("decimalPlaces",Number(L)),className:""})})]}),n.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((O=n==null?void 0:n.formatOptions)==null?void 0:O.currency)||"USD",onValueChange:L=>j("currency",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:w.map(L=>e.jsx(s.SelectItem,{value:L.value,className:"text-xs",children:L.label},L.value))})]})]}),["number","currency"].includes(n.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((k=n==null?void 0:n.formatOptions)==null?void 0:k.useSuffix)??!1,onCheckedChange:L=>j("useSuffix",L)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((E=n==null?void 0:n.formatOptions)==null?void 0:E.locale)||"en-US",onValueChange:L=>j("locale",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(L=>e.jsx(s.SelectItem,{value:L.value,className:"text-xs",children:L.label},L.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(De,{type:"number",placeholder:"12",value:String(((M=n==null?void 0:n.font)==null?void 0:M.size)||12),onSave:L=>g("size",Number(L)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((B=n==null?void 0:n.font)==null?void 0:B.weight)||"normal",onValueChange:L=>g("weight",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(n==null?void 0:n.color)==="auto"||!(n!=null&&n.color)?"auto":"custom",onValueChange:L=>{L==="auto"&&f("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(De,{type:"number",placeholder:"0",value:String((n==null?void 0:n.rotation)||0),onSave:L=>f("rotation",Number(L)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function vl(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[e.jsx(on,{}),e.jsx(cn,{}),e.jsx(dn,{}),e.jsx(un,{})]})]})}const bl=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."]})]}),Nl=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."]})]}),Cl=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 Sl(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=o=>r.includes(a)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(vl,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(ul,{}));case"tornado":case"pyramid":return l(e.jsx(ds,{docContent:bl,cardType:a}));case"kpi":return e.jsx(rl,{});case"line":case"bar":return l(e.jsx(Jr,{cardType:a}));case"range":return l(e.jsx(ds,{docContent:Nl,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(ds,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(Xr,{cardType:a}));case"table":return e.jsx(ml,{cardType:a});case"text":return e.jsx(ds,{docContent:Cl,cardType:a,suffix:"Visual"});case"map":return e.jsx(cl,{});case"custom":return e.jsx(Kr,{});default:return l(e.jsx(sl,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function mn({label:t,column:n,functions:a,onFunctionChange:r}){let l=a[0];"aggregate"in n?l=a.find(c=>c.value===n.aggregate)||a[0]:"granularity"in n&&(l=a.find(c=>c.value===n.granularity)||a[0]);function o(c){r(c)}return e.jsx(je,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:a,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const wl=[{label:"Sum",value:"SUM",logo:e.jsx(Nt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Te,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(Un,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(kn,{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 Dl({column:t}){const{updateMetricColumnOld:n}=s.useEditorActions();let a=wl;s.isTextDataType(t.type)&&(a=a.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(a=a.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:ns(t.name,l)};n(t.id,o)}return e.jsx(mn,{column:t,functions:a,onFunctionChange:l=>r(l),label:"Aggregation"})}const kl=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function Tl({column:t}){const{updateGroupByColumnOld:n}=s.useEditorActions();function a(r){const l={...t,granularity:r,label:We(t.name,r)};n(t.id,l)}return e.jsx(mn,{column:t,functions:kl,onFunctionChange:r=>a(r),label:"Granularity"})}function El({col:t,onChange:n,droppableId:a}){const{columns:r}=s.useDataColumns(),l=A.useMemo(()=>{let i=[];(a===ze||a===Ve||a===_e)&&(i=r);const u=i==null?void 0:i.filter(d=>d.column_name!==t.name);return u==null?void 0:u.map(d=>({id:d.column_name,value:d.column_name}))},[r,a,t.name]),o=[{id:t.name,value:t.name}];function c(i){const u=r==null?void 0:r.find(d=>{var m;return d.column_name===((m=i[0])==null?void 0:m.id)});u&&n(u)}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 hn({column:t}){const n=s.useEditorStore(u=>u.card.type),a=s.useEditorStore(u=>{var d,m;return(m=(d=u.card)==null?void 0:d.config)==null?void 0:m.metricColumns}),r=(a==null?void 0:a.map(u=>u.label))||[],l=r==null?void 0:r.find(u=>u===t.label||u===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(an,{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(rn,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&i()]})}function Il({column:t,type:n,onRemoveColumn:a,droppableId:r}){const[l,o]=A.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:u}=s.useEditorActions(),{attributes:d,listeners:m,setNodeRef:h,transform:f,transition:g,isDragging:j}=s.useSortable({id:t.id,data:{type:n}}),x=f?{opacity:j?.5:void 0,transform:s.CSS.Translate.toString(f),transition:g}:void 0,y=s.isTextDataType(t.type);function p(w){const v=s.isNumberDataType(w.data_type),D=s.isTextDataType(w.data_type),C=s.isDateDataType(w.data_type),I=v?"number":D?"string":C?"date":"string";if(r===ze){if(D){const S={id:t.id,name:w.column_name,type:I,role:"groupby"};c(t.id,S)}if(C){const S={id:t.id,name:w.column_name,type:I,role:"groupby",label:We(w.column_name,"month"),granularity:"month"};c(t.id,S)}}if(r===_e){if(D){const S={id:t.id,name:w.column_name,type:I,role:"groupby"};u(t.id,S)}if(C){const S={id:t.id,name:w.column_name,type:I,label:We(w.column_name,"month"),granularity:"month",role:"groupby"};u(t.id,S)}}if(r===Ve){const S={id:t.id,name:w.column_name,type:I,role:"metric",label:ns(w.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};i(t.id,S)}}function b(){if(r===Ve)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(hn,{column:t})})}function T(){const w=s.isDateDataType(t.type);if(r===Ve)return e.jsx(Dl,{column:t});if((r===ze||r===_e)&&w)return e.jsx(Tl,{column:t})}function R(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===ze||r===_e)&&y}),children:e.jsx(El,{col:t,onChange:p,droppableId:r})})}function N(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>o(!l),children:l?e.jsx(ma,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(vt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...d,ref:h,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:[N(),T(),R()]}),l&&b()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>a(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function Es({id:t,label:n,columns:a,previewColumns:r,sortableType:l,onRemoveColumn:o}){var x,y;const{setNodeRef:c,isOver:i,over:u}=s.useDroppable({id:t}),d=s.useDndStore(p=>p.activeId),m=s.useEditorStore(p=>{var b;return(b=p.card)==null?void 0:b.type}),h=i||((y=(x=u==null?void 0:u.data)==null?void 0:x.current)==null?void 0:y.type)===l,f=d?r:a,g=l===fs?"Rows":l===gs?"Pivot Columns":"Columns";function j(){if(!f||f.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(p=>p.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:n}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),j(),e.jsx("div",{className:"space-y-2",children:f==null?void 0:f.map(p=>p.id===$t.id?e.jsx(Al,{},p.id):e.jsx(Il,{droppableId:t,type:l,column:p,onRemoveColumn:o},p.id))})]})})}function Al(){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 xn({children:t,id:n,type:a}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:u}=s.useSortable({id:n,data:{type:a}}),d=c?{opacity:u?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...l,...r,ref:o,style:d,children:t})}function Ml(){const t=s.useEditorStore(p=>{var b;return(b=p.card.queryConfig)==null?void 0:b.orderBy})||[],n=s.useEditorStore(p=>{var b;return(b=p.card.queryConfig)==null?void 0:b.groupByColumns})||[],a=s.useEditorStore(p=>{var b;return(b=p.card.queryConfig)==null?void 0:b.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...n,...a];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(En,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(Dn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(Tn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(wn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(p=>!t.some(b=>b.columnId===p.id)).map(p=>({id:p.id,value:p.label||p.name}));function f(p,b){const T=g(p);return T?T.role==="metric"?b==="asc"?d:m:b==="asc"?i:u:null}function g(p){return c.find(b=>b.id===p)}function j(p){const b=t.find(T=>T.columnId===p);if(b){const T={...b,direction:b.direction==="asc"?"desc":"asc"};o(T)}}const x=p=>{r({columnId:p.id,direction:"asc"})};function y(p){const b=t.find(T=>T.columnId===p);b&&l(b)}return e.jsx(s.SortableContext,{items:t.map(p=>Ze(p.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:p=>x(p[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(p=>{var b,T;return e.jsx(xn,{id:Ze(p.columnId),type:_s,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(vt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(vs,{className:"w-[175px] text-sm",children:((b=g(p.columnId))==null?void 0:b.label)||((T=g(p.columnId))==null?void 0:T.name)})]}),e.jsx("button",{title:p.direction==="asc"?"Ascending":"Descending",onClick:()=>j(p.columnId),className:"rounded-sm p-0",children:f(p.columnId,p.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>y(p.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"})})})]})},p.columnId)},Ze(p.columnId))})]})})}function Ll(){const t=s.useEditorStore(y=>{var p;return((p=y.card.queryConfig)==null?void 0:p.groupByColumns)||[]}),n=s.useEditorStore(y=>y.card.type),a=s.useDndStore(y=>y.previewGroupByColumns),r=s.useEditorStore(y=>{var p;return((p=y.card.queryConfig)==null?void 0:p.metricColumns)||[]}),l=s.useDndStore(y=>y.previewMetricColumns),o=s.useEditorStore(y=>{var p;return((p=y.card.queryConfig)==null?void 0:p.pivotColumns)||[]}),c=s.useDndStore(y=>y.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:u,removeColumnFromPivotBy:d}=s.useEditorActions();function m(y){i(y)}function h(y){u(y)}function f(y){d(y)}let g="Group By",j="Metrics",x="Stack By";return n==="table"&&(g="Rows",j="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(Xt,{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(Es,{onRemoveColumn:m,sortableType:fs,id:ze,label:g,columns:t,previewColumns:a}),e.jsx(Es,{onRemoveColumn:f,sortableType:gs,id:_e,label:x,columns:o,previewColumns:c}),e.jsx(Es,{onRemoveColumn:h,sortableType:Rs,id:Ve,label:j,columns:r,previewColumns:l}),e.jsx(Ml,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Gs({children:t,column:n,id:a,sortableType:r,className:l}){const[o,c]=A.useState(!1),{removeEditorFilter:i,clearEditorFilter:u}=s.useEditorActions(),d=s.useEditorStore(h=>{var f,g;return(g=(f=h.card.queryConfig)==null?void 0:f.filters)==null?void 0:g.some(j=>j.filterColumnName===n.name)});function m(h){i(h)}return e.jsx(xn,{id:a,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":o}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:n.name}),d&&e.jsx("button",{onClick:()=>u(n),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>m(n),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!o&&"rounded-b-md",o&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",l),children:t})]})]})})}function Rl({column:t,sortableType:n}){const a=s.useDashboardStore(T=>T.themeStyle),r=s.useEditorStore(T=>{var R,N;return(N=(R=T.card)==null?void 0:R.queryConfig)==null?void 0:N.filters}),l=s.useEditorStore(T=>{var R,N;return(N=(R=T.card.queryConfig)==null?void 0:R.filterColumns)==null?void 0:N.find(w=>w.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),u=A.useMemo(()=>{var T;return(T=r==null?void 0:r.find(R=>R.filterColumnName===t.name))==null?void 0:T.filterValue},[r,t.name]),d=A.useMemo(()=>Array.isArray(u)?u.map(T=>({id:T,value:T})):[],[u]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:f,isLoading:g,isFetching:j,isError:x}=s.useFilterQuery(h),y=A.useMemo(()=>{var R;return h.column?(R=f==null?void 0:f.records)==null?void 0:R.map(N=>{let w=h.column.split(".").slice(-1)[0].replace(/"/g,"");return N[w]===void 0&&(w=w.toLowerCase()),{id:N[w],value:N[w]}}):[]},[f,h.column]);function p(T){const R=T.map(N=>N.id);m(t.name,R)}function b(){return g||j?e.jsx(s.Skeleton,{style:{borderRadius:a==null?void 0:a.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(Ol,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:y,onChange:p,selectedOptions:d,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Gs,{className:"w-60",id:t.id,sortableType:n,column:t,children:b()})}function Ol({columnName:t}){const{setEditorFilterMode:n}=s.useEditorActions(),a=s.useEditorStore(l=>{var o,c;return(c=(o=l.card.queryConfig)==null?void 0:o.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(a==null?void 0:a.mode)==="exclude"?n(t,"include"):n(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((a==null?void 0:a.mode)==="exclude"?"exclude":"include")})}function Fl({open:t,setOpen:n,dateRange:a,setDateRange:r,containerClassName:l,inputClassName:o,title:c,onApply:i,onClear:u}){const d=s.useDashboardStore(m=>m.themeStyle);return e.jsx("div",{className:s.cn("grid gap-2",l),children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{style:{borderRadius:d==null?void 0:d.controlInputRadius},asChild:!0,children:e.jsxs(s.Button,{size:"sm",id:"date",variant:"outline",className:s.cn("h-9 w-full justify-start rounded-sm text-left font-normal",!a&&"text-muted-foreground",o),children:[e.jsx(s.Calendar,{className:"mr-2 h-4 w-4"}),a!=null&&a.from?a.to?e.jsxs(e.Fragment,{children:[s.format(a.from,"LLL dd, y")," -"," ",s.format(a.to,"LLL dd, y")]}):s.format(a.from,"LLL dd, y"):e.jsx("span",{children:"Pick a date"})]})}),e.jsxs(s.PopoverContent,{style:{borderRadius:d==null?void 0:d.controlInputRadius},className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsx(s.Label,{children:c})}),e.jsx(s.Calendar$1,{initialFocus:!0,mode:"range",defaultMonth:a==null?void 0:a.from,selected:a,onSelect:r,numberOfMonths:2}),e.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3",children:[e.jsx(s.Button,{style:{borderRadius:d==null?void 0:d.controlInputRadius},size:"sm",variant:"outline",onClick:m=>{m.stopPropagation(),i(a),n(!1)},children:"Apply"}),e.jsx(s.Button,{style:{borderRadius:d==null?void 0:d.controlInputRadius},size:"sm",variant:"outline",onClick:u,children:"Clear"})]})]})]})})}function Bl({column:t,sortableType:n}){const[a,r]=A.useState(!1),{selectedConnectionId:l,selectedDatabaseName:o,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:l,title:"",dataType:t.type},{isLoading:u,isFetching:d,isError:m,data:h}=s.useFilterQuery(i),f=h==null?void 0:h.records,{dateRange:g,setDateRange:j,initialDateRange:x}=s.useDateRangeFromRecords(f),{updateEditorFilterValue:y}=s.useEditorActions();function p(R){var w,v;const N={gte:(w=R==null?void 0:R.from)==null?void 0:w.toISOString(),lte:(v=R==null?void 0:R.to)==null?void 0:v.toISOString()};y(t.name,N)}function b(){y(t.name,null,!0),j(x)}function T(){return u||d?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):m?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):f?e.jsx(Fl,{title:i.title,open:a,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:j,onApply:p,onClear:b}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Gs,{className:"w-72",id:t.id,sortableType:n,column:t,children:T()})}function Pl({id:t,label:n,columns:a,previewColumns:r,sortableType:l}){var j,x;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),u=s.useDndStore(y=>y.activeId),d={},m=c||((x=(j=i==null?void 0:i.data)==null?void 0:j.current)==null?void 0:x.type)===l;function h(){if(!g||g.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function f(y){const p=s.isDateDataType(y.type);return y.id===$t.id?e.jsx(Gs,{id:y.id,sortableType:l,column:y,children:e.jsx(zl,{})},y.id):p?e.jsx(Bl,{droppableId:t,sortableType:l,column:y},y.id):e.jsx(Rl,{droppableId:t,sortableType:l,column:y},y.id)}const g=u?r:a;return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(y=>y.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",m&&"border border-muted-foreground/20"),ref:o,style:d,children:[e.jsx(s.Label,{className:"text-sm",children:n}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(y=>f(y))})]})})}function zl(){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 Vl(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),n=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:a}=s.useEditorActions();function r(l){a(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(Pl,{onRemoveColumn:r,sortableType:Fs,id:Os,label:"Filters",columns:t,previewColumns:n})})}function _l(){const t=s.useEditorStore(o=>o.card),n=s.useEditorStore(o=>o.showAIDialog),{setShowAIDialog:a}=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(js,{}),!n&&e.jsxs(s.Button,{onClick:()=>a(!0),variant:"secondary",size:"sm",children:[e.jsx(na,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(Kt,{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,{}),e.jsx(Us,{variant:"default"})]})]})}function Ul(){const t=A.useRef(null),n=A.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);A.useEffect(()=>{var i,u,d,m;r?((i=t.current)==null||i.resize(0),(u=n.current)==null||u.resize(0)):((d=t.current)==null||d.resize(25),(m=n.current)==null||m.resize(25))},[r]);function o(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Rr,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Sl,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(cs,{})})]}):e.jsx(cs,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:a?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:n,defaultSize:25,maxSize:30,children:e.jsx(Ll,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(_l,{}),e.jsx(Vl,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(cs,{})})]})})]}):e.jsx(cs,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function $l(t){s.useAIInteractionStore(_=>_.currentAIContext);const[n,a]=A.useState(""),[r,l]=A.useState(null),{authToken:o}=s.useSemaphorContext(),c=s.useEditorStore(_=>{var ee;return(ee=_==null?void 0:_.card)==null?void 0:ee.sql}),i=s.useEditorStore(_=>_.isDevMode),u=s.useEditorStore(_=>{var ee;return(ee=_==null?void 0:_.card)==null?void 0:ee.python}),{setCardPython:d,setCardSql:m,setRunSql:h,switchCardType:f,setQueryConfig:g}=s.useEditorActions(),j=s.useEditorStore(_=>_.currentAssitantScope)||[],x=s.useEditorStore(_=>_.userInputForAI),y=s.useEditorStore(_=>_.triggerAIRun),p=s.useEditorStore(_=>_.card),b=s.useEditorStore(_=>_.selectedDatabaseName),T=s.useEditorStore(_=>_.selectedTableName),R=s.useEditorStore(_=>_.selectedConnectionId),N=s.useEditorStore(_=>_.selectedSchemaName),w=s.useDashboardStore(_=>_.dashboard.aiScopeTables),{errorMessage:v,refetch:D,data:C}=s.useDashboardCardQuery(p),{setTriggerAIRun:I,setCurrentAssitantScope:S,setCardConfig:O}=s.useEditorActions(),{selectedDatamodelName:k,connectionType:E,selectedDatamodelId:M}=s.useEditorAside(),{messages:B,setMessages:L,regenerate:F,error:V,sendMessage:z,status:J,addToolResult:X,stop:K,clearError:$}=s.useChat({transport:new s.DefaultChatTransport({api:"https://semaphor.cloud/api/v1/assistant",headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const _=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:i,aiContext:_.currentAIContext,reasoningEffort:_.reasoningEffort,showReasoning:_.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:_,body:ee})=>({body:{...ee,messages:s.cleanupIncompleteMessages(_)}})}),onError:_=>{console.log("on error",_)},onToolCall:Y,onFinish(){a("")}});A.useEffect(()=>{y&&x&&(z({role:"user",parts:[{type:"text",text:x}]}),I(!1))},[y,x,z,I]);async function Y({toolCall:_}){var ee,le,H,Q,re,de,Se,ve,fe,se,ne,ue,be,rs,ls,os;if(["createChartFromSql","createForecast"].includes(_.toolName)){const Xe=((ee=_.input)==null?void 0:ee.sql)??((le=_.args)==null?void 0:le.sql),Ae=((H=_.input)==null?void 0:H.python)??((Q=_.args)==null?void 0:Q.python),me=((re=_.input)==null?void 0:re.chartType)??((de=_.args)==null?void 0:de.chartType);f(me),m(Xe),d(Ae),h(!0),X({tool:_.toolName,toolCallId:_.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(_.toolName==="getUserSql"){if(!c){X({tool:_.toolName,toolCallId:_.toolCallId,output:{status:"error",message:"No SQL found"}});return}X({tool:_.toolName,toolCallId:_.toolCallId,output:{status:"success",sql:c,python:u||""}})}else if(_.toolName==="generateQueryConfig"){a("Generating query config...");const Xe=((Se=_.input)==null?void 0:Se.chartType)??((ve=_.args)==null?void 0:ve.chartType),Ae=((fe=_.input)==null?void 0:fe.queryConfig)??((se=_.args)==null?void 0:se.queryConfig);((ne=_.input)==null?void 0:ne.cardConfig)??((ue=_.args)==null||ue.cardConfig),f(Xe),O(Ae),m(void 0),d(void 0);const me=await D();if((be=me==null?void 0:me.data)!=null&&be.error){X({tool:_.toolName,toolCallId:_.toolCallId,output:{status:"error",queryConfig:Ae,message:(rs=me==null?void 0:me.data)==null?void 0:rs.error.message}});return}if((ls=me==null?void 0:me.data)!=null&&ls.records){X({tool:_.toolName,toolCallId:_.toolCallId,output:{status:"success",queryConfig:Ae,message:"The data has been visualized"}});return}X({tool:_.toolName,toolCallId:_.toolCallId,output:{status:"success",queryConfig:Ae,message:"The data has been visualized",records:(os=me==null?void 0:me.data)==null?void 0:os.records}})}else a("Analyzing...")}function U(_){const ee=s.removeFromScopeArray(j,_);Z(ee)}function Z(_){const ee=s.sanitizeAIScope(_);S(ee),L(le=>[...le,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(ee)}`}]}])}function q(){const _={databaseName:b||"",schemaName:N||"",tableName:T||"",datamodelId:M||"",datamodelName:s.resolveDatamodelName(k),connectionId:R||"",connectionType:E||""},ee=s.dedup([...j,_]);Z(ee)}function P(){const _={databaseName:b||"",schemaName:N||"",tableName:T||"",datamodelName:s.resolveDatamodelName(k),connectionId:R||"",connectionType:E||"",datamodelId:M||""};if(!s.isInAiScopeArray([...w||[],...j],_)||j.length===0){const le=s.dedup([...w||[],...j,_]).filter(H=>H.connectionId===_.connectionId);Z(le)}}const W=!["ready","error"].includes(J),te=s.getErrorMessage(V);return{messages:B,setMessages:L,sendMessage:z,regenerate:F,isLoading:W,handleSetAIScope:P,handleAddCurrentTableToScope:q,removeFromCurrentSelections:U,currentAssitantScope:j,setCurrentAssitantScope:S,stop:K,status:J,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:te,clearError:$}}const ql=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function mt(){const t=A.useRef(null),[n,a]=A.useState(!1),[r,l]=A.useState(s.isDevEnv),[o,c]=A.useState(!1),[i,u]=A.useState(!1),d=s.useCurrentAIContext(),{setCurrentAIContext:m}=s.useAIActions(),{clearQueue:h}=s.useQueueActions(),{clearFileAttachments:f}=s.useFileActions(),g=s.useFileAttachments("editor"),j=s.useDashboardStore(se=>se.dashboard.aiContext),x=s.useEditorStore(se=>se.card.dataSource),y=s.useEditorStore(se=>se.actions.setCardSql),p=s.useEditorStore(se=>se.actions.setRunSql),b=s.useEditorStore(se=>se.showAIDialog),T=s.useDashboardStore(se=>se.handleOpenAssistantProfile),{setShowAIDialog:R,setCardPython:N}=s.useEditorActions(),{setDataSource:w}=s.useEditorActions(),{assistantProfile:v}=s.useAssistantProfile(),{messages:D,setMessages:C,sendMessage:I,isLoading:S,stop:O,status:k,llmUsage:E,errorMessage:M,clearError:B}=$l(),[L,F]=A.useState(""),V=se=>{F(se.target.value)},z=se=>{se.preventDefault();const ne=L.trim();if(!ne&&g.length===0)return;const ue=[];ne&&ue.push({type:"text",text:ne}),g.forEach(be=>{be.data&&ue.push({type:"file",mediaType:be.type,filename:be.name,url:`data:${be.type};base64,${be.data}`})}),I({role:"user",parts:ue}),F(""),f("editor"),W({force:!0})},{visibleMessages:J,hasMoreMessages:X,totalMessageCount:K,loadMoreMessages:$,resetMessageWindow:Y}=s.useMessageWindow(D,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:U,isAtBottom:Z,hasNewMessages:q,newMessageCount:P,scrollToBottom:W,handleScroll:te,resetNewMessageCount:_}=s.useAutoScroll(J,{threshold:50,delay:0,dependencies:[k,D.length]});A.useEffect(()=>{var se;b&&((se=t.current)==null||se.focus(),m({selectedEntities:(x==null?void 0:x.selectedEntities)||[]}))},[b,x,m]),s.useAutoSubmitQueue({assistantType:"editor",status:k,isLoading:S,sendMessage:I});const{hasActiveTools:ee}=s.useActiveToolStatus(D);function le(se,ne){ne==="sql"?(y(se),p(!0)):ne==="python"&&(N(se),p(!0))}function H(){var se;(se=j==null?void 0:j.selectedEntities)==null||se[0],u(!0)}function Q(){d.selectedEntities.length===0&&m({selectedEntities:(j==null?void 0:j.selectedEntities)||[]})}function re(se){Q();const ne={role:"user",parts:[{type:"text",text:se.title+" "+se.subtitle}]};I(ne)}function de(se){Q(),I({role:"user",parts:[{type:"text",text:se}]})}function Se(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:a,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:r,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:c,children:"System Message"})]})]})}function ve(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const fe=(L==null?void 0:L.length)===0&&(D==null?void 0:D.filter(se=>se.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:[ve(),T&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:T,children:(v==null?void 0:v.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Se(),s.isDevEnv,e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:H,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:"New Chat",onClick:()=>{C([]),h("editor"),B(),Y()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",onClick:()=>{R(!1)},children:e.jsx(s.ArrowRightToLine,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:U,className:"mt-2 flex w-full grow basis-0",onScroll:te,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[X&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:$,className:"text-xs",children:["Load ",Math.min(5,K-J.length)," more messages (",K-J.length," hidden)"]})}),e.jsx(s.PrintMessages,{messages:J,showTools:r,handleRun:le,showSystemMessage:o}),!ee&&e.jsx(s.AssistantStatus,{status:k,errorMessage:M})]})}),!Z&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{W({force:!0}),_()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),q&&P>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:P>9?"9+":P})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[fe&&!v&&e.jsx(s.Placeholders,{onClick:re,placeholders:ql}),e.jsx("div",{children:fe&&v&&e.jsx(s.SeedQuestions,{seedQuestions:v.seedQuestions||[],handleSeedQuestionClick:de})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:t,setInput:F,stop:O,input:L,handleInputChange:V,handleSubmit:se=>{Q(),z(se),W({force:!0})},isLoading:S,status:k,assistantType:"editor",onFocus:()=>{}})]}),E&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",E.inputTokens," prompt tokens, ",E.outputTokens," ","completion tokens, ",E.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(x==null?void 0:x.selectedEntities)||[],open:i,onOpenChange:u,dataSource:x||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}const Ks=t=>{var S;const{updateCardConfig:n,updateGroupByColumn:a,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:u,removeSortByColumn:d}=s.useEditorActions(),m=s.useEditorStore(O=>O.card.type),h=t==null?void 0:t.id,f=A.useCallback(O=>{if(!(t!=null&&t.config))return[];switch(O){case"groupBy":return(t.config.groupByColumns||[]).map(k=>({id:k.id,name:k.name,dataType:k.dataType,label:k.label!==void 0?k.label:k.name,qualifiedEntityName:k.qualifiedEntityName,entityId:k.entityId,entityName:k.entityName,entityType:k.entityType,dateFormat:k.dateFormat,customFormat:k.customFormat,granularity:k.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(k=>({id:k.id,name:k.name,dataType:k.dataType,label:k.label!==void 0?k.label:k.name,qualifiedEntityName:k.qualifiedEntityName,entityId:k.entityId,entityName:k.entityName,entityType:k.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(k=>({id:k.id,name:k.name,dataType:k.dataType,label:k.label!==void 0?k.label:k.name,qualifiedEntityName:k.qualifiedEntityName,entityId:k.entityId,entityName:k.entityName,entityType:k.entityType,direction:k.direction}));case"source":return[];default:return[]}},[t]),g=A.useCallback((O,k)=>{if(h)switch(O){case"groupBy":{n(h,{groupByColumns:k});break}case"metrics":{n(h,{metricColumns:k});break}case"pivotBy":{n(h,{pivotByColumns:k});break}case"sortBy":{n(h,{sortByColumns:k});break}}},[h,n]),j=A.useCallback((O,k,E)=>{if(!h)return;const B=f(O)[k];if(B)switch(O){case"groupBy":a(h,B.id,{label:E});break;case"metrics":r(h,B.id,{label:E});break;case"pivotBy":l(h,B.id,{label:E});break;case"sortBy":o(h,B.id,{label:E});break}},[h,f,a,r,l,o]),x=A.useCallback((O,k)=>{if(!h)return;const M=f("metrics")[O];M&&r(h,M.id,{aggregate:k,label:s.getAggregationLabel(M.name,k)})},[h,f,r]),y=A.useCallback((O,k,E)=>{if(!h)return;const B=f("groupBy")[O];if(!B)return;const L={dateFormat:k};k==="custom"&&E?L.customFormat=E:L.customFormat=void 0,a(h,B.id,L)},[h,f,a]),p=A.useCallback((O,k)=>{if(!h)return;const M=f("groupBy")[O];M&&a(h,M.id,{granularity:k})},[h,f,a]),b=A.useCallback((O,k)=>{if(!h)return;const M=f("metrics")[O];M&&r(h,M.id,{aliasTemplate:k})},[h,f,r]),T=A.useCallback((O,k)=>{if(console.log("handleValueAliasesChange",O,k),!h)return;console.log("handleValueAliasesChange",O,k);const M=f("metrics")[O];M&&(console.log("handleValueAliasesChange",k),r(h,M.id,{valueAliases:k}))},[h,f,r]),R=A.useCallback(O=>{h&&n(h,{comparisonType:O})},[h,n]),N=A.useCallback(O=>{h&&n(h,{showTrendline:O})},[h,n]),w=A.useCallback(O=>{h&&n(h,{trendlineWindow:O})},[h,n]),v=A.useCallback(O=>{h&&n(h,{trendlineGranularity:O})},[h,n]),D=A.useCallback(O=>{h&&n(h,{targetValue:O})},[h,n]),C=A.useCallback(O=>{var V;if(!h)return;const k=[...f("groupBy"),...f("pivotBy"),...f("metrics"),...f("sortBy")],E=(V=t==null?void 0:t.config)==null?void 0:V.joinPlan,M=s.validateEntityConsistency(O,k,E);if(!M.isValid){M.showError&&s.showJoinRequiredNotification();return}const B=s.getSmartContainerForField(O,k),L=f(B);if(s.fieldAlreadyExists(O,L))return;const F=s.getNewField(O,B,L);F&&g(B,[...L,F])},[h,(S=t==null?void 0:t.config)==null?void 0:S.joinPlan,f,g]),I=A.useCallback((O,k)=>{if(!h)return;const M=f(O)[k];if(M){if(O!=="sortBy"){const B=f("sortBy"),L=B.filter(F=>!(F.name===M.name&&F.qualifiedEntityName===M.qualifiedEntityName));L.length!==B.length&&n(h,{sortByColumns:L})}switch(O){case"groupBy":c(h,M.id);break;case"metrics":i(h,M.id);break;case"pivotBy":u(h,M.id);break;case"sortBy":d(h,M.id);break}}},[h,f,c,i,u,d,n]);return{getFieldsForContainer:f,setFieldsForContainer:g,updateLabel:j,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:p,handleAliasTemplateChange:b,handleValueAliasesChange:T,removeField:I,handleFieldClick:C,handleKpiComparisonTypeChange:R,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:w,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:D,cardType:m}};function Yl({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function Gl({field:t}){const{attributes:n,listeners:a,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,u]=A.useState(!1),d=s.useEditorStore(j=>j.card),{handleFieldClick:m}=Ks(d),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const f=j=>{const x=(j||"").toLowerCase();switch(s.getDataType(x)){case"number":return Te;case"date":return s.Calendar;case"boolean":return Ue;case"json":return Qe;case"geo":return es;default:return ye}},g=j=>{const x=(j||"").toLowerCase(),y=s.getDataType(x);return y==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):y==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Te,{className:"h-3 w-3"})}):y==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):y==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):y==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):y==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(es,{className:"h-3 w-3"})}):y==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(as,{className:"h-3 w-3"})}):null};return f(t.dataType),e.jsxs("div",{ref:r,style:h,...n,...a,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>m(t),children:[g(t.dataType),e.jsx(s.TooltipProvider$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/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(Yl,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{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(ga,{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 Kl(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useEditorStore(T=>T.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:u}=s.useColumns(),d=o.filter(T=>T.name.toLowerCase().includes(t.toLowerCase())||T.dataType.toLowerCase().includes(t.toLowerCase())||T.qualifiedEntityName&&T.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=T=>{if(T.dataType==="number"||T.dataType==="integer"||T.dataType==="float"||T.dataType==="decimal"||T.dataType==="currency")return"metrics";const R=s.getDataType(T.dataType);return["date","string","boolean"].includes(R)?"dimensions":R==="number"?"metrics":"dimensions"},f=(a==="all"?d:d.filter(T=>m(T)===a)).reduce((T,R)=>{const N=R.qualifiedEntityName||"Other Fields";return T[N]||(T[N]={label:s.toLabel(R.entityName),fields:[]}),T[N].fields.push(R),T},{}),j=Object.keys(f),x=d.filter(T=>m(T)==="dimensions").length,y=d.filter(T=>m(T)==="metrics").length,p=d.filter(T=>m(T)==="calculated").length,b=d.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):u?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:u.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[o.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:T=>n(T.target.value)})]}),b&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:T=>r(T),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:d.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:y})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(as,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:j,className:"space-y-2",children:Object.entries(f).map(([T,R])=>{const N=c.find(w=>w.entityName===T)||{entityName:T,label:R.label};return e.jsxs(s.AccordionItem,{value:T,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-primary",children:N.label||N.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:R.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:R.fields.map(w=>e.jsx(Gl,{field:w},w.id))})})]},T)})}),Object.keys(f).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(f).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 Hl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(Kl,{})," "]})}function Ql({initialJoinPlan:t,availableDataSources:n}){const[a,r]=A.useState(t),[l,o]=A.useState(new Set),c=()=>{const w=a.joins.length>0?Math.max(...a.joins.map(D=>D.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:w,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,v]}),o(new Set([...l,v.id]))},i=w=>{r({...a,joins:a.joins.filter(v=>v.id!==w)}),o(new Set([...l].filter(v=>v!==w)))},u=(w,v)=>{var S,O;const D=a.joins.find(k=>k.id===w);if(!D)return;const C={...D,...v},I=a.joins.map(k=>k.id===w?C:k);if((S=C.source)!=null&&S.name&&((O=C.target)!=null&&O.name)&&C.joinKeyGroups[0].keys.length===0){const k=n.find(L=>{var F;return L.name===((F=C.source)==null?void 0:F.name)}),E=n.find(L=>{var F;return L.name===((F=C.target)==null?void 0:F.name)}),M={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(k==null?void 0:k.name)||"",entityName:(k==null?void 0:k.name)||"",entityType:(k==null?void 0:k.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(E==null?void 0:E.name)||"",entityName:(E==null?void 0:E.name)||"",entityType:(E==null?void 0:E.type)||"table"},operator:"="},B=[...C.joinKeyGroups];B[0]={...B[0],keys:[M]},C.joinKeyGroups=B,I[I.findIndex(L=>L.id===w)]=C}r({...a,joins:I})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:u,moveJoinUp:w=>{const v=a.joins.findIndex(D=>D.id===w);if(v>0){const D=[...a.joins],C={...D[v]},I={...D[v-1]};D[v]=I,D[v-1]=C,D.forEach((O,k)=>{O.sequence=k+1});const S={...a,joins:D};r(S)}},moveJoinDown:w=>{const v=a.joins.findIndex(D=>D.id===w);if(v<a.joins.length-1){const D=[...a.joins],C={...D[v]},I={...D[v+1]};D[v]=I,D[v+1]=C,D.forEach((O,k)=>{O.sequence=k+1});const S={...a,joins:D};r(S)}},toggleJoinExpansion:w=>{const v=new Set(l);v.has(w)?v.delete(w):v.add(w),o(v)},getAvailableSourceEntities:w=>{if(a.joins.length===0)return n;const v=a.joins.findIndex(C=>C.id===w);if(v===0)return n;const D=new Set;return a.baseEntity.name&&D.add(a.baseEntity.name),a.joins.slice(0,v).forEach(C=>{D.add(C.source.name),D.add(C.target.name)}),n.filter(C=>D.has(C.name))},getAvailableTargetEntities:w=>n.filter(v=>v.name!==w),addJoinKeyGroup:w=>{const v=a.joins.find(C=>C.id===w);if(!v)return;const D=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];u(w,{joinKeyGroups:D})},updateGroupOperator:(w,v,D)=>{const C=a.joins.find(S=>S.id===w);if(!C)return;const I=[...C.joinKeyGroups];I[v]={...I[v],operator:D},u(w,{joinKeyGroups:I})},removeJoinKeyGroup:(w,v)=>{const D=a.joins.find(I=>I.id===w);if(!D)return;const C=[...D.joinKeyGroups];C.splice(v,1),u(w,{joinKeyGroups:C})},addJoinKey:(w,v)=>{const D=a.joins.find(k=>k.id===w);if(!D)return;const C=n.find(k=>k.name===D.source.name),I=n.find(k=>k.name===D.target.name),S=[...D.joinKeyGroups],O={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(C==null?void 0:C.name)||"",entityName:(C==null?void 0:C.name)||"",entityType:(C==null?void 0:C.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="};S[v]={...S[v],keys:[...S[v].keys,O]},u(w,{joinKeyGroups:S})},updateJoinKey:(w,v,D,C,I)=>{const S=a.joins.find(B=>B.id===w);if(!S)return;const O=n.find(B=>B.name===S.source.name),k=n.find(B=>B.name===S.target.name),E=[...S.joinKeyGroups],M=E[v].keys[D];C==="sourceColumnName"&&O?E[v].keys[D]={...M,source:{...M.source,name:I}}:C==="targetColumnName"&&k?E[v].keys[D]={...M,target:{...M.target,name:I}}:C==="operator"&&(E[v].keys[D]={...M,operator:I}),u(w,{joinKeyGroups:E})},removeJoinKey:(w,v,D)=>{const C=a.joins.find(S=>S.id===w);if(!C)return;const I=[...C.joinKeyGroups];I[v].keys.splice(D,1),u(w,{joinKeyGroups:I})},generateSQLPreview:()=>{const w=[...a.joins].sort((C,I)=>C.sequence-I.sequence),v=a.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let D=`SELECT *
|
|
353
|
+
`;N(z)}function L(){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(Mr,{jsonString:JSON.stringify(d,null,2)})})}),d&&d.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 F(){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:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Ir,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Ar,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function V(){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:D||C,onClick:()=>{E()},className:"h-8 shrink-0",size:"sm",children:[D||C?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(Kt,{sql:v==null?void 0:v.sql,error:M,onDebugWithAssistant:B}),e.jsx(js,{}),e.jsx(s.Toggle,{pressed:n,onPressedChange:z=>a(z),className:"h-8",size:"sm",variant:"outline",children:e.jsx(Er,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{T(!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,{}),e.jsx(Us,{})]})]})}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:[F(),L()]}),V()]})}function Or({card:t}){var N,T,R,b,w,v,D,C,I,S,O;const[n,a]=A.useState(!1),[r,l]=A.useState([]),{authToken:o}=s.useSemaphorContext(),c=s.getTokenParams(o==null?void 0:o.accessToken),i=s.useDashboardStore(k=>k.themeStyle),u={colors:((T=(N=i==null?void 0:i.chart)==null?void 0:N.dataset)==null?void 0:T.backgroundColor)||[]};(R=t.customCardPreferences)!=null&&R.inputData;const{getCard:d}=s.useCustomVisual(((b=t.customCardPreferences)==null?void 0:b.url)||""),m=((w=t.customCardPreferences)==null?void 0:w.visualType)||"single",h=s.useEditorStore(k=>k.frame),{setCustomCardPreferences:f}=s.useEditorActions(),{data:g}=s.useDashboardCardQuery(t),j=A.useCallback((k,E)=>{l(M=>({...M,[k]:E}))},[]);if(!((v=t.customCardPreferences)!=null&&v.componentName))return null;const x=d((D=t.customCardPreferences)==null?void 0:D.componentName);function y(k){a(k)}const p=Object.keys(((C=t.customCardPreferences)==null?void 0:C.dataInputCardIds)||{}).map(k=>{var B,L,F;const E=(L=(B=t.customCardPreferences)==null?void 0:B.dataInputCardIds)==null?void 0:L[k].cardId,M=(F=h==null?void 0:h.cards)==null?void 0:F.find(V=>V.id===E);return M||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(A.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[x&&m==="single"&&e.jsx(x,{editing:!0,params:c,theme:u,settings:(I=t.customCardPreferences)==null?void 0:I.settings,onDataChange:j,data:(g==null?void 0:g.records)||[]}),x&&m==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((S=t.customCardPreferences)==null?void 0:S.dataInputCardIds)||{}).map(k=>{var B,L,F;const E=(L=(B=t.customCardPreferences)==null?void 0:B.dataInputCardIds)==null?void 0:L[k].cardId,M=(F=h==null?void 0:h.cards)==null?void 0:F.find(V=>V.id===E);if(M)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:y,onDataChange:j,dataInputIndex:k,card:M},M.id+k)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:u,onDataChange:j,settings:p.map(k=>{var E;return(E=k==null?void 0:k.customCardPreferences)==null?void 0:E.settings}),data:p.map(k=>k!=null&&k.id?r==null?void 0:r[k.id]:[])})})]})]},(O=t.customCardPreferences)==null?void 0:O.componentName)})}function Qt({className:t,...n}){var D;const a=s.useEditorStore(C=>C.card),r=s.isExplorerCard(a),l=((D=a.customCardPreferences)==null?void 0:D.showCardHeader)??!0,o=s.useEditorStore(C=>C.frame),c=s.useDashboardStore(C=>C.dashboard.filters),i=s.useEditorStore(C=>C.actions.setRunSql),{updateFilter:u}=s.useDashboardActions(),d=c==null?void 0:c.find(C=>C.id===o.filterId),{data:m,isLoading:h,isFetching:f,errorMessage:g,pagination:j}=s.useDashboardCardQuery(a),{setCard:x,updateCardInFrame:y}=s.useEditorActions(),{data:p}=s.useTopoJson(a),N=A.useMemo(()=>{var C;return a.type!=="pivotTable"||!((C=m==null?void 0:m.records)!=null&&C.length)?null:{records:m.records,columnSubtotalMeta:m.columnSubtotalMeta,subtotalColumns:m.subtotalColumns||[],pivotSchema:m.pivotSchema||[],groupByColumns:m.groupByColumns}},[a.type,m==null?void 0:m.records,m==null?void 0:m.columnSubtotalMeta,m==null?void 0:m.subtotalColumns,m==null?void 0:m.pivotSchema,m==null?void 0:m.groupByColumns]),T=s.usePivotTableConfig(a,N),R=(C,I)=>{var O,k;const S={...a,paginationConfig:{page:C+1,pageSize:I}};x(S),y(S),a.sql&&((k=(O=a.preferences)==null?void 0:O.tablePrefs)!=null&&k.enableDevModePagination)&&i(!0)},b=A.useMemo(()=>!a.id||!(m!=null&&m.records)?null:s.createChartConfig({card:a,data:m==null?void 0:m.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:p}),[a.id,m==null?void 0:m.records,a.type,a.queryConfig,a.customCfg,a.preferences,p]);function w(C){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Or,{card:C})})}function v(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!f)return g?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||f)&&a.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return w(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&b)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:h||f?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:b})});if(a.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:a,data:(m==null?void 0:m.records)||[],paginationMetadata:j,onPaginationChange:R,isLoading:h||f})});if(a.type==="pivotTable"&&T)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.PivotTableVisual,{card:a,data:T.data,options:T.options,onAggregationChange:C=>{const I=s.handleAggregationChange(C,a.config),S={...a,config:I};x(S),y(S)},onAggregationLabelChange:C=>{const I=s.handleAggregationLabelChange(C,a.config),S={...a,config:I};x(S),y(S)}})});if(a.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:a,data:(m==null?void 0:m.records)||[],groupByColumns:m==null?void 0:m.groupByColumns,pivotSchema:m==null?void 0:m.pivotSchema,paginationMetadata:j,onPaginationChange:R,onAggregationChange:C=>{const I=s.handleAggregationChange(C,a.config),S={...a,config:I};x(S),y(S)},isLoading:h||f})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:C=>x({...a,title:C}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})})}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:C=>x({...a,description:C}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:d.title||d.column,onSave:C=>u({...d,title:C}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:d})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:v()})]})}const ks=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:n,onChange:a}),Fr=()=>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."})]})]}),Br=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ks,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ks,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ks,{language:"javascript",value:t,onChange:l})})]}),Pr=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function zr(){const[t,n]=A.useState(!1),[a,r]=A.useState(""),[l,o]=A.useState(""),[c,i]=A.useState(""),[u,d]=A.useState(""),m=s.useEditorStore(b=>b.card),h=s.useEditorStore(b=>b.card.customCfg),f=h?JSON.stringify(h,null,2):"",{data:g}=s.useDashboardCardQuery(m),{data:j}=s.useTopoJson(m),{setCardCustomCfg:x,setCustomVisualCode:y}=s.useEditorActions(),p=b=>{var w,v;return JSON.stringify({...b,data:{...b.data,datasets:(v=(w=b.data)==null?void 0:w.datasets)==null?void 0:v.map(D=>({...D,data:[]}))}},null,2)},N=()=>{var w,v;if(!((w=g==null?void 0:g.records)!=null&&w.length))return;const b=s.createChartConfig({card:m,data:g.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:j});if(b){r(p(b)),i(((v=m.preferences)==null?void 0:v.customVisualCode)||"");const D=s.merge(b,h);o(p(D))}},T=()=>{try{if(c&&y(c),l){const b=JSON.parse(l),w=s.getObjectDiff(JSON.parse(a),b);x(w),d("")}}catch{d("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:N,className:R?"":"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(Fr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Qt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Br,{customCode:c,cardCustomCfgString:f,mergedConfig:l,onConfigChange:b=>o(b??""),onCodeChange:b=>i(b??"")})]}),e.jsx(Pr,{error:u,hasCardCustomConfig:!!h,onReset:()=>{o(a),x(null)},onApply:T,onClose:()=>n(!1)})]})]})}function ys(t){const[n,a]=A.useState(null);return n}function Wt(){const{authToken:t}=s.useSemaphorContext(),{data:n,isLoading:a,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:n,isLoading:a,isFetching:r,isError:l}}function Jt(){const{data:t,isLoading:n,isError:a}=Wt(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:u=>Math.min(1e3*2**u,3e4)}))}),l=[];let o=n,c=a;return r.forEach((i,u)=>{var d;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((d=t==null?void 0:t.plugins)!=null&&d[u])){const m=t.plugins[u],h=i.data.visuals.map(f=>({name:f.name,pluginName:m.label,componentType:f.componentType,pluginType:m.type,icon:f.icon,chartType:f.chartType,url:m.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function Vr({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=Jt(),u=A.useCallback((d,m)=>{n(null),a({}),r(d),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[n,a,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((d,m)=>e.jsx(_r,{text:d.name,onClick:()=>u("custom",d),icon:d.icon},`${d.url}-${d.name}-${m}`))})]})}const _r=({text:t,icon:n,onClick:a})=>{const r=ys(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:a,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function Xt({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function u(m,h){o(null),r({}),a(m),["custom","text","map"].includes(m)&&(l(!0),i(void 0)),t==null||t()}const d=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:d,tooltip:"Table",onClick:()=>u("table"),className:"h-10 p-4",children:e.jsx(s.Table2,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Bar Chart",onClick:()=>u("bar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnIncreasing,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Line Chart",onClick:()=>u("line"),className:"h-10 p-4",children:e.jsx(s.ChartLine,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Stacked Bar Chart",onClick:()=>u("stackedBar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnStacked,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Stacked Line Chart",onClick:()=>u("stackedLine"),className:"h-10 p-4",children:e.jsx(s.MdStackedLineChart,{className:s.cn("size-5",n),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Scatter Chart",onClick:()=>u("scatter"),className:"h-10 p-4",children:e.jsx(s.ChartScatter,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Bubble Chart",onClick:()=>u("bubble"),className:"h-10 p-4",children:e.jsx(s.TbChartBubble,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Pie Chart",onClick:()=>u("pie"),className:"h-10 p-4",children:e.jsx(s.ChartPie,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Doughnut Chart",onClick:()=>u("doughnut"),className:"h-10 p-4",children:e.jsx(s.Donut,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Funnel Chart",onClick:()=>u("funnel"),className:"h-10 p-4",children:e.jsx(s.TbChartFunnel,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Radar Chart",onClick:()=>u("radar"),className:"h-10 p-4",children:e.jsx(s.Radar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Polar Area Chart",onClick:()=>u("polarArea"),className:"h-10 p-4",children:e.jsx(s.PiChartPolar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Tornado Chart",onClick:()=>u("tornado"),className:"h-10 p-4",children:e.jsx(s.Tornado,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>u("range"),className:"h-10 p-4",children:e.jsx(s.ChartNoAxesGantt,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"KPI",onClick:()=>u("kpi"),className:"h-10 p-4",children:e.jsx(s.TiSortNumerically,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Text",onClick:()=>u("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>u("map"),className:"h-10 p-4",children:e.jsx(s.Map,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:d,tooltip:"Custom",onClick:()=>u("custom"),className:"h-10 p-4",children:e.jsx(ss,{className:s.cn("size-5",n)})})]})}function Ur({chartType:t,className:n,customIcon:a,componentName:r}){const l=ys();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:n});case"line":return e.jsx(s.ChartLine,{className:n});case"pie":return e.jsx(s.ChartPie,{className:n});case"radar":return e.jsx(s.Radar,{className:n});case"scatter":return e.jsx(s.ChartScatter,{className:n});case"bubble":return e.jsx(s.TbChartBubble,{className:n});case"doughnut":return e.jsx(s.Donut,{className:n});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:n});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:n});case"polarArea":return e.jsx(s.PiChartPolar,{className:n});case"funnel":return e.jsx(s.TbChartFunnel,{className:n});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:n});case"range":return e.jsx(s.ChartNoAxesGantt,{className:n});case"kpi":return e.jsx(s.TiSortNumerically,{className:n});case"text":return e.jsx(ye,{className:n});case"map":return e.jsx(s.Map,{className:n});case"custom":return a&&l?e.jsx(l,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(ss,{className:n});default:return e.jsx(s.Table2,{className:n})}}function Zt({variant:t="ghost"}){var o,c;const[n,a]=A.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(Ur,{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(Xt,{onChartTypeChange:()=>a(!1)}),e.jsx(Vr,{onChartTypeChange:()=>a(!1)})]})]})}function $r(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(nt,{className:"size-4"}):e.jsx(tt,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(nt,{className:"size-4"}):e.jsx(tt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function en(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.isShowingVisual),a=s.useEditorStore(c=>{var i,u;return(u=(i=c.card)==null?void 0:i.preferences)==null?void 0:u.chartOptions}),r=s.getChartGridStyle(a),{setChartGrid:l}=s.useEditorActions();function o(){const c=["xy","none","x","y"],u=(c.indexOf(r)+1)%c.length;l(c[u])}return n?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($r,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:o,children:[(r==="xy"||!r)&&e.jsx(Gn,{className:"size-4"}),r==="x"&&e.jsx(On,{className:"size-4"}),r==="y"&&e.jsx(ca,{className:"size-4"}),r==="none"&&e.jsx(xa,{className:"size-4"})]})]}):null}function qr(){const t=s.useEditorStore(j=>j.frame),n=s.useEditorStore(j=>j.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(j,x)=>{j.dataTransfer.setData("tabIndex",x.toString())},i=j=>{j.preventDefault()},u=(j,x)=>{const y=j.dataTransfer.getData("tabIndex");if(y===x.toString())return;const p=Array.from(t.cards),[N]=p.splice(parseInt(y),1);p.splice(x,0,N),a({...t,cards:p})};function d(j){const x=t.cards.filter(N=>N.id!==j),y=x[0],p={...t,cards:x,activeCardId:y.id};a(p),r(y.id),l(y)}function m(j,x){const y={...t,cards:[...t.cards,x],activeCardId:j.id};a(y),r(x.id)}function h(){const j={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};m(n,j)}function f(j){const x={dataSource:j.dataSource,connectionId:j.connectionId,lastSelectedDatabase:j.lastSelectedDatabase,lastSelectedSchema:j.lastSelectedSchema,lastSelectedTable:j.lastSelectedTable,lastSelectedDatamodelId:j.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(j,x)}function g(j,x){return j.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||j.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const y=x.displayTab===void 0?!1:!x.displayTab;l({...x,displayTab:y}),o({...x,displayTab:y})},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(zn,{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((j,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:y=>c(y,x),onDragOver:i,onDrop:y=>u(y,x),className:"",value:j.id,children:[g(t,j),e.jsx(s.Editable,{enabled:t.activeCardId===j.id,text:j.tabTitle||j.title,onSave:y=>{l({...n,tabTitle:y}),o({...n,tabTitle:y})},children:j.tabTitle||j.title},j.id),t.activeCardId===j.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>d(j.id)})]},j.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>f(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(Bn,{className:"h-4 w-4"})})]})})}function sn(){const t=s.useEditorStore(x=>x.frame),n=s.useEditorStore(x=>x.card),a=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:u}=s.useEditorActions(),{data:d,isLoading:m,isFetching:h}=s.useDashboardCardQuery(n);function f(x){const y=t.cards.find(p=>p.id===x);if(y!=null&&y.sql){r||i(!0),o(x);return}if(y!=null&&y.queryConfig){r&&i(!1),g(x),o(x);return}r||g(x),o(x)}function g(x){const y={...t,cards:t.cards.map(N=>N.id===n.id?n:N),activeCardId:x};l(y);const p=y.cards.find(N=>N.id===x);p.sql&&u(!0),c(p)}function j(){return n.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:d==null?void 0:d.records,isPending:m||h})})}):n.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:d==null?void 0:d.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Qt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:f,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:j()},x.id)),e.jsx(qr,{})]})}function cs({children:t}){var R,b;s.useEditorStore(w=>w.frame);const n=s.useEditorStore(w=>w.card),a=s.useEditorStore(w=>w.isDevMode),r=s.useEditorStore(w=>w.isShowingVisual),l=s.useDashboardStore(w=>w.isVisualEditing),o=s.useEditorStore(w=>w.pythonStdOut);s.useEditorStore(w=>w.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:u,runAssistant:d,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:f,isLoading:g,isFetching:j,errorMessage:x,refetch:y}=s.useDashboardCardQuery(n);function p(){const w=JSON.stringify(f==null?void 0:f.records,null,2),v=new Blob([w],{type:"application/json"}),D=URL.createObjectURL(v),C=document.createElement("a");C.href=D,C.download=`${n.title}.json`,C.click()}function N(){const v=[Object.keys(f==null?void 0:f.records.reduce((S,O)=>({...S,...O}),{})).join(","),...((f==null?void 0:f.records)||[]).map(S=>Object.values(S).join(","))].join(`
|
|
354
|
+
`),D=new Blob([v],{type:"text/csv"}),C=URL.createObjectURL(D),I=document.createElement("a");I.href=C,I.download=`${n.title}.csv`,I.click()}function T(){const w=`Can you get the documentation for ${n.type} chart?`;d(w)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Zt,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:T,children:e.jsx(An,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(zr,{})]}),!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:N,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:p,children:e.jsx(_n,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(f==null?void 0:f.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(en,{})]}),n.type==="table"&&n.sql&&!s.hasValidCardConfig(n.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((b=(R=n.preferences)==null?void 0:R.tablePrefs)==null?void 0:b.enableDevModePagination)??!1,onCheckedChange:w=>{var v;h({...n.preferences,tablePrefs:{...(v=n.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:w}}),y()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(Gr,{})]}),r?e.jsx(sn,{}):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(Yr,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":o}),children:[(f==null?void 0:f.records)&&(f==null?void 0:f.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(f==null?void 0:f.records)||[]}),x&&e.jsx(Yt,{error:x})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Yr(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Gr(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Kr(){var x,y;const t=s.useEditorStore(p=>p.card.customCardPreferences),{data:n}=Wt(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(p=>p.card),l=s.useEditorStore(p=>p.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:u}=s.useCustomVisual((t==null?void 0:t.url)||""),d=(x=u==null?void 0:u.visuals)==null?void 0:x.find(p=>p.name===(t==null?void 0:t.componentName));function m(p,N){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[p]:{cardId:N,hookRef:null}};c({...t,dataInputCardIds:R})}function h(p){var T,R;const N=(T=l==null?void 0:l.cards)==null?void 0:T.filter(b=>{var w;return((w=b==null?void 0:b.customCardPreferences)==null?void 0:w.visualType)!=="multiple"}).map(b=>({value:b.id,label:b.tabTitle||b.title}));return e.jsx("div",{className:"space-y-2",children:(R=p==null?void 0:p.dataInputs)==null?void 0:R.map((b,w)=>{var v,D;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:b}),e.jsx(je,{className:"col-span-6 h-8 w-full justify-between",label:"",options:N||[],value:((D=(v=t==null?void 0:t.dataInputCardIds)==null?void 0:v[w])==null?void 0:D.cardId)||"",onValueChange:C=>m(w,C)})]},w+Math.random())})})}function f(p,N,T=[],R=""){var b,w;return t?p==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((b=t==null?void 0:t.settings)==null?void 0:b[N])||R,onChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[N]:v.target.value}})}},N):p==="select"?e.jsx(je,{className:"h-8 w-full",label:"",options:T,value:((w=t==null?void 0:t.settings)==null?void 0:w[N])||R,onValueChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[N]:v}})}}):null:null}function g(p){const N=Object.entries((p==null?void 0:p.settings)||{});return e.jsx("div",{className:"space-y-3",children:N.map(([T,R])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:R.title}),f(R.ui,T,R.options,R.defaultValue)]},T))})}function j(p){t&&c({...t,visualType:p,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(je,{icon:e.jsx(In,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:p=>c({...t||{url:"",componentName:""},url:p})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:j,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(je,{icon:e.jsx(Fn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(p=>p.type===o).map(p=>({value:p.name,label:p.name})))||[],value:t.componentName,onValueChange:p=>{console.log("changing value",p),c({...t,componentName:p})}})})]})})]}),((y=r==null?void 0:r.customCardPreferences)==null?void 0:y.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[d&&d.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(d)})]}),d&&d.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(d)})})]})]})]})}function qe(){const[t,n]=A.useState([]),a=s.useEditorStore(d=>d.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(d=>d.actions),o=s.useEditorStore(d=>d.queryResultColumns);s.useEditorStore(d=>{var m;return(m=d.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),A.useEffect(()=>{o&&n(new Array(o.length).fill(!1))},[o]);function c(d,m){var h,f;m?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:d,expression:""}]}):l({...a,onClickFilter:[{columnIndex:d,expression:""}]}):(l({...a,onClickFilter:(f=a==null?void 0:a.onClickFilter)==null?void 0:f.filter(g=>g.columnIndex!==d)}),n(g=>{const j=[...g];return j[d]=!1,j}))}function i(d,m){var f;const h=(f=a==null?void 0:a.onClickFilter)==null?void 0:f.map(g=>g.columnIndex===d?{...g,expression:m.target.value}:g);l({...a,onClickFilter:h})}function u(d){var m,h,f,g;if(t!=null&&t[d]||(h=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(j=>j.columnIndex===d))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(f=a==null?void 0:a.onClickFilter)==null?void 0:f.find(j=>j.columnIndex===d))==null?void 0:g.expression,onChange:j=>i(d,j),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:o==null?void 0:o.map((d,m)=>{var h,f;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(g=>g.columnIndex===m)),onCheckedChange:g=>c(m,g)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:d}),e.jsx("div",{className:"flex items-center gap-2",children:((f=a==null?void 0:a.onClickFilter)==null?void 0:f.find(g=>g.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{n(g=>{const j=[...g];return j[m]=!g[m],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),u(m)]})},d)})})}function Hr({idx:t}){var i;const n=s.useEditorStore(u=>{var d;return(d=u.card)==null?void 0:d.preferences}),a=s.useEditorStore(u=>{var d;return(d=u.card.preferences)==null?void 0:d.datasetOptions}),r=s.useEditorStore(u=>u.actions.setCardPreferences),l=(i=n==null?void 0:n.chartOptions)==null?void 0:i.indexAxis,o=a==null?void 0:a.find(u=>u.idx===t);function c(u,d){(u==="end"||u==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:u!=="none",align:u,anchor:u,clamp:!0};if(!o)r({...n,datasetOptions:[...a||[],{idx:d,datalabels:m}]});else{const h={...o};h.datalabels=m;const f=a==null?void 0:a.map(g=>g.idx===d?h:g);r({...n,datasetOptions:f})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Ct,{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(Wn,{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(Xn,{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(Jn,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function Qr(){const t=s.useEditorStore(o=>o.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function vs({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function tn(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var d,m,h;return(h=(m=(d=u==null?void 0:u.card)==null?void 0:d.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=Qr();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(u=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:u,children:nn(u)},u))})]}),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((u,d)=>e.jsx(an,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:u,idx:d},u))})]})]})}function nn(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function an({col:t,idx:n,className:a,iconClassName:r,children:l}){const o=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,f;return(f=(h=m.card)==null?void 0:h.preferences)==null?void 0:f.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===n),{setCardPreferences:u}=s.useEditorStore(m=>m.actions);function d(m){if(!i)u({...o,datasetOptions:[...c||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const f=c==null?void 0:c.map(g=>g.idx===n?h:g);u({...o,datasetOptions:f})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(vs,{className:"max-w-[100px]",title:t,children:nn(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>d("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>d("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>d("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Hr,{idx:n})]})]})}function qs(){const t=s.useEditorStore(g=>g.selectedConnectionId),n=s.useEditorStore(g=>g.selectedDatamodelId),a=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),l=s.useEditorStore(g=>g.selectedTableName),o=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:u}=s.useDashboardActions(),{modelItems:d,tableName:m,connectionType:h}=s.useEditorAside();function f(g,j="dashboard",x){var D;const y=s.fmt(g.column_name),p=s.fmt(a||""),N=s.fmt(r||""),T=s.fmt(m);let R=s.getQualifiedTableName({schemaName:N,tableName:T,connectionType:h,databaseName:p}),b=`${R}.${y}`;const w=(D=d==null?void 0:d.find(C=>C.id===n))==null?void 0:D.name;n&&n!=="none"&&(b=`${s.DATAMODEL_NAMESPCACE}.${w}.${y}`,R=`${s.DATAMODEL_NAMESPCACE}.${w}`),x!=null&&x.qualifiedFieldName&&(b=x.qualifiedFieldName),x!=null&&x.entityName&&(R=x.entityName);const v=o==null?void 0:o.find(C=>C.column===b&&C.table===T&&(C.database===p||C.database===a));if(v)u(v.id),i(v.id);else{const C=s.v4();return m==="api"&&t?(c({location:j,id:C,column:b,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,R,y)}),C):(c({id:C,location:j,column:b,title:g.column_name,dataType:g.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,R,y)}),C)}}return{assignFilter:f}}function Je(){const t=s.useDashboardStore(i=>i.dashboard.filters),n=s.useEditorStore(i=>i.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=qs();function o(i){const u=l(i,"frame");a({...n,filterId:u})}const c=t==null?void 0:t.find(i=>i.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(Wr,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function Wr({columns:t,onSelect:n}){var c;const[a,r]=pe.useState(!1),[l,o]=pe.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:u=>{const d=u===l?"":u;o(d),r(!1),d&&n(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function 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:n=>n.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(tn,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(qe,{}),e.jsx(Je,{})]})]})]})})}function Xr({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(qe,{}),e.jsx(Je,{})]})]})]})})}function rn(){const t=s.useEditorStore(i=>i.card.type),n=s.useEditorStore(i=>i.isDevMode),a=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var m;const u={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},d={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(m=a==null?void 0:a.chartOptions)==null?void 0:m.plugins,...u}}};r(d)}function o(){var i,u,d;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((d=(u=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:u.datalabels)==null?void 0:d.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,u,d;return e.jsx("div",{children:e.jsxs(s.Select,{value:((d=(u=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:u.datalabels)==null?void 0:d.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?o():c()})}const Zr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},el={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function sl(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:tl(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(rn,{}),e.jsx(qe,{}),e.jsx(Je,{})]})]})}function tl(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(Zr,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(el,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 nl({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(c,i,u){const d=[...t];d[c]={...d[c],[i]:u},n(d)}function l(c){const i=[...t];i.splice(c,1),n(i)}function o(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:o,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:u=>r(i,"start",u.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:u=>r(i,"end",u.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:u=>r(i,"color",u.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function al(){var m,h,f,g,j;const t=s.useEditorStore(x=>x.card.preferences),n=s.useEditorStore(x=>x.actions.setCardPreferences),a=s.useEditorStore(x=>x.card),r=s.isExplorerCard(a),l=s.useEditorStore(x=>x.actions.setNumberFormat);s.useEditorStore(x=>{var y,p;return(p=(y=x.card.preferences)==null?void 0:y.formatNumber)==null?void 0:p.decimalPlaces});const o=s.useEditorStore(x=>{var y,p;return(p=(y=x.card.preferences)==null?void 0:y.formatNumber)==null?void 0:p.locale}),c=s.useEditorStore(x=>{var y,p;return(p=(y=x.card.preferences)==null?void 0:y.formatNumber)==null?void 0:p.currency});s.useEditorStore(x=>x.actions.setFilterOnClickField);const i=s.useEditorStore(x=>{var y,p;return(p=(y=x.card.preferences)==null?void 0:y.formatNumber)==null?void 0:p.colorRanges})||[],u=s.useEditorStore(x=>x.actions.setColorRanges),d=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(x=>x.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:x=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:x}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:x=>{var y,p,N;return l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,((p=t==null?void 0:t.formatNumber)==null?void 0:p.currency)||"",x,((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(x=>e.jsx(s.SelectItem,{value:x.locale,children:x.locale},x.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:x=>{var y,p,N;console.log("currency",x),l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,x==="none"?"":x,((p=t==null?void 0:t.formatNumber)==null?void 0:p.locale)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),d.map(x=>e.jsx(s.SelectItem,{value:x,children:x},x))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((g=(f=t==null?void 0:t.formatNumber)==null?void 0:f.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:x=>{var y,p,N;return l(Number(x),((y=t==null?void 0:t.formatNumber)==null?void 0:y.currency)||"",((p=t==null?void 0:t.formatNumber)==null?void 0:p.locale)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(x=>e.jsx(s.SelectItem,{value:x,children:x},x))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((j=t==null?void 0:t.formatNumber)==null?void 0:j.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:x=>{var y,p,N;return l(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,((p=t==null?void 0:t.formatNumber)==null?void 0:p.currency)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.locale)||"",x.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(nl,{colorRanges:i,setColorRanges:u})]})]})}function rl(){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(al,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function Ts({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const ll=[{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"}],ol=["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"],il=ol.map(t=>({label:t,value:t}));function cl(){var u,d,m,h,f,g,j,x,y,p,N,T,R,b,w,v,D,C;const t=s.useEditorStore(I=>I.card),n=(d=(u=t==null?void 0:t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:d.topoJsonUrl,[a,r]=A.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(I=>({label:I,value:I}))||[],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(Ts,{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(Ts,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(je,{className:"h-9",options:i,onValueChange:I=>{console.log("value",I),l({...t.preferences,mapVisualOptions:{topoJsonUrl:I}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:I=>{r(I.target.value)},onBlur:()=>{var I;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(je,{className:"h-9",options:c,value:((g=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:I=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,objectKey:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(je,{className:"h-9",options:ll,value:((x=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:I=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projection:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(je,{className:"h-9",options:il,value:((p=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:p.colorScale)||"",label:"Select Color Scale",onValueChange:I=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,colorScale:I}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ts,{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:((T=(N=t.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:T.projectionScale)||1,onChange:I=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionScale:Number(I.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(b=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:b.projectionOffset)==null?void 0:w[0])||0,onChange:I=>{var S,O,k,E;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[Number(I.target.value),((E=(k=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:E[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((C=(D=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:C[1])||0,onChange:I=>{var S,O,k,E;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[((E=(k=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:E[0])||0,Number(I.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(qe,{})]})}function dl(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:n}=s.useEditorStore(l=>l.actions);function a(l){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function ds({cardType:t,docContent:n,suffix:a="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${a}`}),e.jsx(s.AccordionContent,{children:n||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(dl,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(qe,{}),e.jsx(Je,{})]})]})]})})}function ul(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(je,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{n(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[a(),e.jsx(tn,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(qe,{}),e.jsx(Je,{})]})]})]})})}function ml({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(qe,{}),e.jsx(Je,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function ln({color:t,onColorChange:n,onClose:a}){const[r,l]=A.useState(0),[o,c]=A.useState(100),[i,u]=A.useState(50),[d,m]=A.useState(t);A.useEffect(()=>{const y=ct(t);if(y){const p=dt(y.r,y.g,y.b);l(p.h),c(p.s),u(p.l),m(t)}},[t]);const h=y=>{l(y),g(y,o,i)},f=y=>{const p=y.currentTarget.getBoundingClientRect(),N=Math.max(0,Math.min(1,(y.clientX-p.left)/p.width)),T=Math.max(0,Math.min(1,(y.clientY-p.top)/p.height)),R=N*100,b=(1-T)*100;c(R),u(b),g(r,R,b)},g=(y,p,N)=>{const T=xl(y,p,N),R=hl(T.r,T.g,T.b);m(R)},j=y=>{if(m(y),/^#[0-9A-Fa-f]{6}$/.test(y)){const p=ct(y);if(p){const N=dt(p.r,p.g,p.b);l(N.h),c(N.s),u(N.l)}}},x=()=>{/^#[0-9A-Fa-f]{6}$/.test(d)&&(n(d),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:f,onMouseMove:y=>{y.buttons===1&&f(y)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:d}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:y=>h(Number(y.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:d,onChange:y=>j(y.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:d}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:x,children:"OK"})]})]})}function ct(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function hl(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function dt(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let o=0,c=0;const i=(r+l)/2;if(r!==l){const u=r-l;switch(c=i>.5?u/(2-r-l):u/(r+l),r){case t:o=((n-a)/u+(n<a?6:0))/6;break;case n:o=((a-t)/u+2)/6;break;case a:o=((t-n)/u+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function xl(t,n,a){t/=360,n/=100,a/=100;let r,l,o;if(n===0)r=l=o=a;else{const c=(d,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?d+(m-d)*6*h:h<.5?m:h<.6666666666666666?d+(m-d)*(.6666666666666666-h)*6:d),i=a<.5?a*(1+n):a+n-a*n,u=2*a-i;r=c(u,i,t+1/3),l=c(u,i,t),o=c(u,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const pl=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function on(){var T,R,b,w,v,D,C,I,S,O;const t=s.useEditorStore(k=>k.card),n=s.useEditorStore(k=>{var E;return(E=k.card)==null?void 0:E.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=A.useState({}),[i,u]=A.useState(null),[d,m]=A.useState(null),h=A.useMemo(()=>{var B,L,F,V,z,J,X;if(!(l!=null&&l.records)||l.records.length===0)return[];const k=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",E=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",M=((B=t==null?void 0:t.config)==null?void 0:B.pivotByColumns)&&t.config.pivotByColumns.length>0;if((k||E)&&M){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const K=new Set;return l.pivotSchema.forEach($=>{$.alias&&K.add($.alias)}),Array.from(K)}if(l.records.length>0){const K=l.records[0],$=Object.keys(K),Y=new Set;(L=t==null?void 0:t.config)!=null&&L.groupByColumns&&t.config.groupByColumns.forEach(q=>{Y.add(q.label||q.name),Y.add(q.alias||q.name)});const U=new Set;return(F=t==null?void 0:t.config)!=null&&F.metricColumns&&t.config.metricColumns.forEach(q=>{const P=q.alias||q.name;U.add(P),U.add(`${P}_count`),U.add(`${P}_sum`),U.add(`${P}_avg`),U.add(`${P}_min`),U.add(`${P}_max`);const W=q.entityName||q.qualifiedEntityName;W&&(U.add(`${W}_${P}`),U.add(`${W}_${P}_count`))}),$.filter(q=>!Y.has(q)&&!U.has(q))}}if((E||k)&&!M&&((z=(V=t==null?void 0:t.config)==null?void 0:V.metricColumns)!=null&&z.length))return t.config.metricColumns.map(K=>K.alias||K.label||K.name);if((X=(J=t==null?void 0:t.config)==null?void 0:J.groupByColumns)!=null&&X.length){const K=t.config.groupByColumns[0],$=K.label||K.name,Y=new Set;return l.records.forEach(U=>{const Z=U[$];Z!=null&&Y.add(String(Z))}),Array.from(Y)}return[]},[l,(T=t==null?void 0:t.config)==null?void 0:T.groupByColumns,(R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns,(b=t==null?void 0:t.config)==null?void 0:b.metricColumns,t==null?void 0:t.type]),f=A.useMemo(()=>s.getDefaultChartColors(),[]);A.useEffect(()=>{const k={};h.forEach((E,M)=>{k[E]=s.getColorForValue(E,M,n==null?void 0:n.colorConfig)}),c(k)},[h,n==null?void 0:n.colorConfig,f]);const g=(k,E)=>{const M={...o,[k]:E};c(M);const B={...n||{},colorConfig:{segments:M}};a(B);const L={...t,preferences:B};r(L)},j=(k,E)=>{var z;const M=f[E%f.length],{[k]:B,...L}=((z=n==null?void 0:n.colorConfig)==null?void 0:z.segments)||{},F={...n||{},colorConfig:{segments:L}};a(F);const V={...t,preferences:F};r(V),c(J=>({...J,[k]:M}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((v=(w=t==null?void 0:t.config)==null?void 0:w.groupByColumns)==null?void 0:v.length)||((C=(D=t==null?void 0:t.config)==null?void 0:D.pivotByColumns)==null?void 0:C.length):(S=(I=t==null?void 0:t.config)==null?void 0:I.groupByColumns)==null?void 0:S.length)||["table","kpi","text","custom"].includes(t.type))return null;const p=()=>{const k={...n||{},colorConfig:{segments:{}}};a(k);const E={...t,preferences:k};r(E);const M={};h.forEach((B,L)=>{M[B]=s.getColorForValue(B,L,void 0)}),c(M)},N=Object.keys(((O=n==null?void 0:n.colorConfig)==null?void 0:O.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(la,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:N&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:p,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((k,E)=>{const M=s.isDefaultColor(o[k],E),B=!M;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===k,onOpenChange:L=>u(L?k:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[k]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:f.slice(0,10).map((L,F)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[k]===L?"border-gray-900":"border-transparent"),style:{backgroundColor:L},onClick:()=>{g(k,L),u(null)},children:[F===E%f.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:L})]},`default-${F}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:pl.map((L,F)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[k]===L?"border-2 border-gray-900":L==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:L},onClick:()=>{g(k,L),u(null)},children:e.jsx("span",{className:"sr-only",children:L})},`preset-${F}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{m({value:k,color:o[k]}),u(null)},children:"Custom color"}),!M&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(k,E),u(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:k}),B&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},k)})}),d&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(ln,{color:d.color,onColorChange:k=>{g(d.value,k),m(null)},onClose:()=>m(null)})})]})]})})]})}function De({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[o,c]=A.useState(t??""),[i,u]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const d=()=>{n(o),u(!1)},m=()=>{c(t??""),u(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),u(!0)},onFocus:()=>u(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?d():h.key==="Escape"&&m()},"aria-label":a||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:d,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const fl=["auto","number","currency","percent","scientific","date"],gl=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"KRW",label:"KRW - South Korean Won"}],jl=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],yl=t=>t.charAt(0).toUpperCase()+t.slice(1);function Ys({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,u)=>{n({...t,[i]:u})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:fl.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":yl(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:gl.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:jl.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function ut({axis:t,label:n,type:a,config:r,onChange:l}){var h,f,g,j,x,y,p,N,T,R,b,w;const o=(v,D)=>{l({...r,[v]:D})},c=(v,D)=>{var C,I;l({...r,name:{enabled:v==="enabled"?D:((C=r==null?void 0:r.name)==null?void 0:C.enabled)??!1,text:v==="text"?D:(I=r==null?void 0:r.name)==null?void 0:I.text}})},i=(v,D)=>{var C,I;l({...r,labels:{enabled:v==="enabled"?D:((C=r==null?void 0:r.labels)==null?void 0:C.enabled)??!0,rotation:v==="rotation"?D:(I=r==null?void 0:r.labels)==null?void 0:I.rotation}})},u=(v,D)=>{l({...r,scale:{...r==null?void 0:r.scale,[v]:D===""?"auto":Number(D)}})},d=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:v=>o("enabled",v),onClick:v=>v.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:v=>c("enabled",v)})]}),((f=r==null?void 0:r.name)==null?void 0:f.enabled)&&e.jsx(De,{placeholder:`${n} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:v=>c("text",v),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:v=>o("position",v),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":s.titleCase(v)},v))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((j=r==null?void 0:r.labels)==null?void 0:j.enabled)!==!1,onCheckedChange:v=>i("enabled",v)})]}),((x=r==null?void 0:r.labels)==null?void 0:x.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((y=r==null?void 0:r.labels)==null?void 0:y.rotation)||"auto"),onValueChange:v=>i("rotation",v==="auto"?"auto":Number(v)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":`${v}°`},v))})]})]})]}),a==="value"&&e.jsx(Ys,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:v=>l({...r,formatOptions:v}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(De,{type:"number",placeholder:"auto",value:((p=r==null?void 0:r.scale)==null?void 0:p.min)==="auto"||((N=r==null?void 0:r.scale)==null?void 0:N.min)===void 0?"":String(r.scale.min),onSave:v=>u("min",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(De,{type:"number",placeholder:"auto",value:((T=r==null?void 0:r.scale)==null?void 0:T.max)==="auto"||((R=r==null?void 0:r.scale)==null?void 0:R.max)===void 0?"":String(r.scale.max),onSave:v=>u("max",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(De,{type:"number",placeholder:"auto",value:((b=r==null?void 0:r.scale)==null?void 0:b.stepSize)==="auto"||((w=r==null?void 0:r.scale)==null?void 0:w.stepSize)===void 0?"":String(r.scale.stepSize),onSave:v=>u("stepSize",v),className:""})})]})]})]})]})]})}function cn(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const d={...n||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};a(d);const m={...t,preferences:d};r(m)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(ut,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(ut,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function dn(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var m,h,f,g;return(g=(f=(h=(m=d.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:f.plugins)==null?void 0:g.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(d,m)=>{const h={...n,[d]:m};a(h)},i=["top","bottom","left","right"],u=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??o,onCheckedChange:d=>c("display",d)})]}),((n==null?void 0:n.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||r,onValueChange:d=>c("position",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(d=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:s.titleCase(d)},d))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||l,onValueChange:d=>c("align",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(d=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:s.titleCase(d)},d))})]})]})]})]})})]})}function un(){var D,C,I,S,O,k,E,M,B;const t=s.useEditorStore(L=>L.card),n=s.useEditorStore(L=>{var F,V;return(V=(F=L.card)==null?void 0:F.preferences)==null?void 0:V.dataLabelsConfig}),a=s.useEditorStore(L=>{var F;return(F=L.card)==null?void 0:F.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((D=a==null?void 0:a.chartOptions)==null?void 0:D.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",u=!i,d=(I=(C=a==null?void 0:a.chartOptions)==null?void 0:C.plugins)==null?void 0:I.datalabels,m=(d==null?void 0:d.display)!==!1&&((d==null?void 0:d.anchor)||(d==null?void 0:d.align)),h=(n==null?void 0:n.enabled)!==void 0?n.enabled:m,f=(L,F)=>{const V={...n,[L]:F},z={...t.preferences||{},dataLabelsConfig:V};r(z);const J={...t,preferences:z};l(J)},g=(L,F)=>{const V={...n,font:{...n==null?void 0:n.font,[L]:F}},z={...t.preferences||{},dataLabelsConfig:V};r(z);const J={...t,preferences:z};l(J)},j=(L,F)=>{const V={...n,formatOptions:{...n==null?void 0:n.formatOptions,[L]:F}},z={...t.preferences||{},dataLabelsConfig:V};r(z);const J={...t,preferences:z};l(J)},y=(()=>{const L=t.type;return L==="stackedBar"||L==="stackedLine"||L==="pie"||L==="doughnut"?"center":o?"right":"top"})();let p=[];c||i?p=["center"]:p=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(F=>F!==y),"custom"];const N=()=>s.titleCase(y),T=["center","start","end"],R=["center","start","end","top","bottom"],b=u?["auto","number","currency","percent","none"]:["number","currency","percent","none"],w=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],v=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:L=>f("enabled",L)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:L=>f("position",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:p.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:L==="auto"?N():L==="custom"?"Custom (Advanced)":s.titleCase(L)},L))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:L=>f("showTotal",L)})]}),(n==null?void 0:n.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(n==null?void 0:n.anchor)||"center",onValueChange:L=>f("anchor",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:T.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:s.titleCase(L)},L))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((n==null?void 0:n.align)||"center"),onValueChange:L=>f("align",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:R.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:s.titleCase(L)},L))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(u?"auto":"none"),onValueChange:L=>f("format",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:b.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:L==="auto"&&u?"Auto (Use Axis)":L==="none"?"None (Raw Value)":s.titleCase(L)},L))})]})]}),(n==null?void 0:n.format)&&!["auto","none"].includes(n.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(n.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(De,{type:"number",placeholder:"0",value:String(((S=n==null?void 0:n.formatOptions)==null?void 0:S.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:L=>j("decimalPlaces",Number(L)),className:""})})]}),n.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((O=n==null?void 0:n.formatOptions)==null?void 0:O.currency)||"USD",onValueChange:L=>j("currency",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:w.map(L=>e.jsx(s.SelectItem,{value:L.value,className:"text-xs",children:L.label},L.value))})]})]}),["number","currency"].includes(n.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((k=n==null?void 0:n.formatOptions)==null?void 0:k.useSuffix)??!1,onCheckedChange:L=>j("useSuffix",L)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((E=n==null?void 0:n.formatOptions)==null?void 0:E.locale)||"en-US",onValueChange:L=>j("locale",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(L=>e.jsx(s.SelectItem,{value:L.value,className:"text-xs",children:L.label},L.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(De,{type:"number",placeholder:"12",value:String(((M=n==null?void 0:n.font)==null?void 0:M.size)||12),onSave:L=>g("size",Number(L)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((B=n==null?void 0:n.font)==null?void 0:B.weight)||"normal",onValueChange:L=>g("weight",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(n==null?void 0:n.color)==="auto"||!(n!=null&&n.color)?"auto":"custom",onValueChange:L=>{L==="auto"&&f("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(De,{type:"number",placeholder:"0",value:String((n==null?void 0:n.rotation)||0),onSave:L=>f("rotation",Number(L)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function vl(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[e.jsx(on,{}),e.jsx(cn,{}),e.jsx(dn,{}),e.jsx(un,{})]})]})}const bl=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."]})]}),Nl=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."]})]}),Cl=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 Sl(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=o=>r.includes(a)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(vl,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(ul,{}));case"tornado":case"pyramid":return l(e.jsx(ds,{docContent:bl,cardType:a}));case"kpi":return e.jsx(rl,{});case"line":case"bar":return l(e.jsx(Jr,{cardType:a}));case"range":return l(e.jsx(ds,{docContent:Nl,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(ds,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(Xr,{cardType:a}));case"table":return e.jsx(ml,{cardType:a});case"text":return e.jsx(ds,{docContent:Cl,cardType:a,suffix:"Visual"});case"map":return e.jsx(cl,{});case"custom":return e.jsx(Kr,{});default:return l(e.jsx(sl,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function mn({label:t,column:n,functions:a,onFunctionChange:r}){let l=a[0];"aggregate"in n?l=a.find(c=>c.value===n.aggregate)||a[0]:"granularity"in n&&(l=a.find(c=>c.value===n.granularity)||a[0]);function o(c){r(c)}return e.jsx(je,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:a,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const wl=[{label:"Sum",value:"SUM",logo:e.jsx(Nt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Te,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(Un,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(kn,{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 Dl({column:t}){const{updateMetricColumnOld:n}=s.useEditorActions();let a=wl;s.isTextDataType(t.type)&&(a=a.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(a=a.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:ns(t.name,l)};n(t.id,o)}return e.jsx(mn,{column:t,functions:a,onFunctionChange:l=>r(l),label:"Aggregation"})}const kl=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function Tl({column:t}){const{updateGroupByColumnOld:n}=s.useEditorActions();function a(r){const l={...t,granularity:r,label:We(t.name,r)};n(t.id,l)}return e.jsx(mn,{column:t,functions:kl,onFunctionChange:r=>a(r),label:"Granularity"})}function El({col:t,onChange:n,droppableId:a}){const{columns:r}=s.useDataColumns(),l=A.useMemo(()=>{let i=[];(a===ze||a===Ve||a===_e)&&(i=r);const u=i==null?void 0:i.filter(d=>d.column_name!==t.name);return u==null?void 0:u.map(d=>({id:d.column_name,value:d.column_name}))},[r,a,t.name]),o=[{id:t.name,value:t.name}];function c(i){const u=r==null?void 0:r.find(d=>{var m;return d.column_name===((m=i[0])==null?void 0:m.id)});u&&n(u)}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 hn({column:t}){const n=s.useEditorStore(u=>u.card.type),a=s.useEditorStore(u=>{var d,m;return(m=(d=u.card)==null?void 0:d.config)==null?void 0:m.metricColumns}),r=(a==null?void 0:a.map(u=>u.label))||[],l=r==null?void 0:r.find(u=>u===t.label||u===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(an,{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(rn,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&i()]})}function Il({column:t,type:n,onRemoveColumn:a,droppableId:r}){const[l,o]=A.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:u}=s.useEditorActions(),{attributes:d,listeners:m,setNodeRef:h,transform:f,transition:g,isDragging:j}=s.useSortable({id:t.id,data:{type:n}}),x=f?{opacity:j?.5:void 0,transform:s.CSS.Translate.toString(f),transition:g}:void 0,y=s.isTextDataType(t.type);function p(w){const v=s.isNumberDataType(w.data_type),D=s.isTextDataType(w.data_type),C=s.isDateDataType(w.data_type),I=v?"number":D?"string":C?"date":"string";if(r===ze){if(D){const S={id:t.id,name:w.column_name,type:I,role:"groupby"};c(t.id,S)}if(C){const S={id:t.id,name:w.column_name,type:I,role:"groupby",label:We(w.column_name,"month"),granularity:"month"};c(t.id,S)}}if(r===_e){if(D){const S={id:t.id,name:w.column_name,type:I,role:"groupby"};u(t.id,S)}if(C){const S={id:t.id,name:w.column_name,type:I,label:We(w.column_name,"month"),granularity:"month",role:"groupby"};u(t.id,S)}}if(r===Ve){const S={id:t.id,name:w.column_name,type:I,role:"metric",label:ns(w.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};i(t.id,S)}}function N(){if(r===Ve)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(hn,{column:t})})}function T(){const w=s.isDateDataType(t.type);if(r===Ve)return e.jsx(Dl,{column:t});if((r===ze||r===_e)&&w)return e.jsx(Tl,{column:t})}function R(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===ze||r===_e)&&y}),children:e.jsx(El,{col:t,onChange:p,droppableId:r})})}function b(){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(ma,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(vt,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...d,ref:h,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:[b(),T(),R()]}),l&&N()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>a(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function Es({id:t,label:n,columns:a,previewColumns:r,sortableType:l,onRemoveColumn:o}){var x,y;const{setNodeRef:c,isOver:i,over:u}=s.useDroppable({id:t}),d=s.useDndStore(p=>p.activeId),m=s.useEditorStore(p=>{var N;return(N=p.card)==null?void 0:N.type}),h=i||((y=(x=u==null?void 0:u.data)==null?void 0:x.current)==null?void 0:y.type)===l,f=d?r:a,g=l===fs?"Rows":l===gs?"Pivot Columns":"Columns";function j(){if(!f||f.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(p=>p.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:n}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),j(),e.jsx("div",{className:"space-y-2",children:f==null?void 0:f.map(p=>p.id===$t.id?e.jsx(Al,{},p.id):e.jsx(Il,{droppableId:t,type:l,column:p,onRemoveColumn:o},p.id))})]})})}function Al(){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 xn({children:t,id:n,type:a}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:u}=s.useSortable({id:n,data:{type:a}}),d=c?{opacity:u?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...l,...r,ref:o,style:d,children:t})}function Ml(){const t=s.useEditorStore(p=>{var N;return(N=p.card.queryConfig)==null?void 0:N.orderBy})||[],n=s.useEditorStore(p=>{var N;return(N=p.card.queryConfig)==null?void 0:N.groupByColumns})||[],a=s.useEditorStore(p=>{var N;return(N=p.card.queryConfig)==null?void 0:N.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...n,...a];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(En,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(Dn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(Tn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(wn,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(p=>!t.some(N=>N.columnId===p.id)).map(p=>({id:p.id,value:p.label||p.name}));function f(p,N){const T=g(p);return T?T.role==="metric"?N==="asc"?d:m:N==="asc"?i:u:null}function g(p){return c.find(N=>N.id===p)}function j(p){const N=t.find(T=>T.columnId===p);if(N){const T={...N,direction:N.direction==="asc"?"desc":"asc"};o(T)}}const x=p=>{r({columnId:p.id,direction:"asc"})};function y(p){const N=t.find(T=>T.columnId===p);N&&l(N)}return e.jsx(s.SortableContext,{items:t.map(p=>Ze(p.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:p=>x(p[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(p=>{var N,T;return e.jsx(xn,{id:Ze(p.columnId),type:_s,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(vt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(vs,{className:"w-[175px] text-sm",children:((N=g(p.columnId))==null?void 0:N.label)||((T=g(p.columnId))==null?void 0:T.name)})]}),e.jsx("button",{title:p.direction==="asc"?"Ascending":"Descending",onClick:()=>j(p.columnId),className:"rounded-sm p-0",children:f(p.columnId,p.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>y(p.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"})})})]})},p.columnId)},Ze(p.columnId))})]})})}function Ll(){const t=s.useEditorStore(y=>{var p;return((p=y.card.queryConfig)==null?void 0:p.groupByColumns)||[]}),n=s.useEditorStore(y=>y.card.type),a=s.useDndStore(y=>y.previewGroupByColumns),r=s.useEditorStore(y=>{var p;return((p=y.card.queryConfig)==null?void 0:p.metricColumns)||[]}),l=s.useDndStore(y=>y.previewMetricColumns),o=s.useEditorStore(y=>{var p;return((p=y.card.queryConfig)==null?void 0:p.pivotColumns)||[]}),c=s.useDndStore(y=>y.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:u,removeColumnFromPivotBy:d}=s.useEditorActions();function m(y){i(y)}function h(y){u(y)}function f(y){d(y)}let g="Group By",j="Metrics",x="Stack By";return n==="table"&&(g="Rows",j="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(Xt,{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(Es,{onRemoveColumn:m,sortableType:fs,id:ze,label:g,columns:t,previewColumns:a}),e.jsx(Es,{onRemoveColumn:f,sortableType:gs,id:_e,label:x,columns:o,previewColumns:c}),e.jsx(Es,{onRemoveColumn:h,sortableType:Rs,id:Ve,label:j,columns:r,previewColumns:l}),e.jsx(Ml,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Gs({children:t,column:n,id:a,sortableType:r,className:l}){const[o,c]=A.useState(!1),{removeEditorFilter:i,clearEditorFilter:u}=s.useEditorActions(),d=s.useEditorStore(h=>{var f,g;return(g=(f=h.card.queryConfig)==null?void 0:f.filters)==null?void 0:g.some(j=>j.filterColumnName===n.name)});function m(h){i(h)}return e.jsx(xn,{id:a,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":o}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:n.name}),d&&e.jsx("button",{onClick:()=>u(n),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>m(n),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!o&&"rounded-b-md",o&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",l),children:t})]})]})})}function Rl({column:t,sortableType:n}){const a=s.useDashboardStore(T=>T.themeStyle),r=s.useEditorStore(T=>{var R,b;return(b=(R=T.card)==null?void 0:R.queryConfig)==null?void 0:b.filters}),l=s.useEditorStore(T=>{var R,b;return(b=(R=T.card.queryConfig)==null?void 0:R.filterColumns)==null?void 0:b.find(w=>w.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),u=A.useMemo(()=>{var T;return(T=r==null?void 0:r.find(R=>R.filterColumnName===t.name))==null?void 0:T.filterValue},[r,t.name]),d=A.useMemo(()=>Array.isArray(u)?u.map(T=>({id:T,value:T})):[],[u]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:f,isLoading:g,isFetching:j,isError:x}=s.useFilterQuery(h),y=A.useMemo(()=>{var R;return h.column?(R=f==null?void 0:f.records)==null?void 0:R.map(b=>{let w=h.column.split(".").slice(-1)[0].replace(/"/g,"");return b[w]===void 0&&(w=w.toLowerCase()),{id:b[w],value:b[w]}}):[]},[f,h.column]);function p(T){const R=T.map(b=>b.id);m(t.name,R)}function N(){return g||j?e.jsx(s.Skeleton,{style:{borderRadius:a==null?void 0:a.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(Ol,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:y,onChange:p,selectedOptions:d,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Gs,{className:"w-60",id:t.id,sortableType:n,column:t,children:N()})}function Ol({columnName:t}){const{setEditorFilterMode:n}=s.useEditorActions(),a=s.useEditorStore(l=>{var o,c;return(c=(o=l.card.queryConfig)==null?void 0:o.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(a==null?void 0:a.mode)==="exclude"?n(t,"include"):n(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((a==null?void 0:a.mode)==="exclude"?"exclude":"include")})}function Fl({open:t,setOpen:n,dateRange:a,setDateRange:r,containerClassName:l,inputClassName:o,title:c,onApply:i,onClear:u}){const d=s.useDashboardStore(m=>m.themeStyle);return e.jsx("div",{className:s.cn("grid gap-2",l),children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{style:{borderRadius:d==null?void 0:d.controlInputRadius},asChild:!0,children:e.jsxs(s.Button,{size:"sm",id:"date",variant:"outline",className:s.cn("h-9 w-full justify-start rounded-sm text-left font-normal",!a&&"text-muted-foreground",o),children:[e.jsx(s.Calendar,{className:"mr-2 h-4 w-4"}),a!=null&&a.from?a.to?e.jsxs(e.Fragment,{children:[s.format(a.from,"LLL dd, y")," -"," ",s.format(a.to,"LLL dd, y")]}):s.format(a.from,"LLL dd, y"):e.jsx("span",{children:"Pick a date"})]})}),e.jsxs(s.PopoverContent,{style:{borderRadius:d==null?void 0:d.controlInputRadius},className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsx(s.Label,{children:c})}),e.jsx(s.Calendar$1,{initialFocus:!0,mode:"range",defaultMonth:a==null?void 0:a.from,selected:a,onSelect:r,numberOfMonths:2}),e.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3",children:[e.jsx(s.Button,{style:{borderRadius:d==null?void 0:d.controlInputRadius},size:"sm",variant:"outline",onClick:m=>{m.stopPropagation(),i(a),n(!1)},children:"Apply"}),e.jsx(s.Button,{style:{borderRadius:d==null?void 0:d.controlInputRadius},size:"sm",variant:"outline",onClick:u,children:"Clear"})]})]})]})})}function Bl({column:t,sortableType:n}){const[a,r]=A.useState(!1),{selectedConnectionId:l,selectedDatabaseName:o,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:l,title:"",dataType:t.type},{isLoading:u,isFetching:d,isError:m,data:h}=s.useFilterQuery(i),f=h==null?void 0:h.records,{dateRange:g,setDateRange:j,initialDateRange:x}=s.useDateRangeFromRecords(f),{updateEditorFilterValue:y}=s.useEditorActions();function p(R){var w,v;const b={gte:(w=R==null?void 0:R.from)==null?void 0:w.toISOString(),lte:(v=R==null?void 0:R.to)==null?void 0:v.toISOString()};y(t.name,b)}function N(){y(t.name,null,!0),j(x)}function T(){return u||d?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):m?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):f?e.jsx(Fl,{title:i.title,open:a,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:j,onApply:p,onClear:N}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Gs,{className:"w-72",id:t.id,sortableType:n,column:t,children:T()})}function Pl({id:t,label:n,columns:a,previewColumns:r,sortableType:l}){var j,x;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),u=s.useDndStore(y=>y.activeId),d={},m=c||((x=(j=i==null?void 0:i.data)==null?void 0:j.current)==null?void 0:x.type)===l;function h(){if(!g||g.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function f(y){const p=s.isDateDataType(y.type);return y.id===$t.id?e.jsx(Gs,{id:y.id,sortableType:l,column:y,children:e.jsx(zl,{})},y.id):p?e.jsx(Bl,{droppableId:t,sortableType:l,column:y},y.id):e.jsx(Rl,{droppableId:t,sortableType:l,column:y},y.id)}const g=u?r:a;return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(y=>y.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",m&&"border border-muted-foreground/20"),ref:o,style:d,children:[e.jsx(s.Label,{className:"text-sm",children:n}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(y=>f(y))})]})})}function zl(){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 Vl(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),n=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:a}=s.useEditorActions();function r(l){a(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(Pl,{onRemoveColumn:r,sortableType:Fs,id:Os,label:"Filters",columns:t,previewColumns:n})})}function _l(){const t=s.useEditorStore(o=>o.card),n=s.useEditorStore(o=>o.showAIDialog),{setShowAIDialog:a}=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(js,{}),!n&&e.jsxs(s.Button,{onClick:()=>a(!0),variant:"secondary",size:"sm",children:[e.jsx(na,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(Kt,{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,{}),e.jsx(Us,{variant:"default"})]})]})}function Ul(){const t=A.useRef(null),n=A.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);A.useEffect(()=>{var i,u,d,m;r?((i=t.current)==null||i.resize(0),(u=n.current)==null||u.resize(0)):((d=t.current)==null||d.resize(25),(m=n.current)==null||m.resize(25))},[r]);function o(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Rr,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Sl,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(cs,{})})]}):e.jsx(cs,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:a?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:n,defaultSize:25,maxSize:30,children:e.jsx(Ll,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(_l,{}),e.jsx(Vl,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(cs,{})})]})})]}):e.jsx(cs,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function $l(t){s.useAIInteractionStore(_=>_.currentAIContext);const[n,a]=A.useState(""),[r,l]=A.useState(null),{authToken:o}=s.useSemaphorContext(),c=s.useEditorStore(_=>{var ee;return(ee=_==null?void 0:_.card)==null?void 0:ee.sql}),i=s.useEditorStore(_=>_.isDevMode),u=s.useEditorStore(_=>{var ee;return(ee=_==null?void 0:_.card)==null?void 0:ee.python}),{setCardPython:d,setCardSql:m,setRunSql:h,switchCardType:f,setQueryConfig:g}=s.useEditorActions(),j=s.useEditorStore(_=>_.currentAssitantScope)||[],x=s.useEditorStore(_=>_.userInputForAI),y=s.useEditorStore(_=>_.triggerAIRun),p=s.useEditorStore(_=>_.card),N=s.useEditorStore(_=>_.selectedDatabaseName),T=s.useEditorStore(_=>_.selectedTableName),R=s.useEditorStore(_=>_.selectedConnectionId),b=s.useEditorStore(_=>_.selectedSchemaName),w=s.useDashboardStore(_=>_.dashboard.aiScopeTables),{errorMessage:v,refetch:D,data:C}=s.useDashboardCardQuery(p),{setTriggerAIRun:I,setCurrentAssitantScope:S,setCardConfig:O}=s.useEditorActions(),{selectedDatamodelName:k,connectionType:E,selectedDatamodelId:M}=s.useEditorAside(),{messages:B,setMessages:L,regenerate:F,error:V,sendMessage:z,status:J,addToolResult:X,stop:K,clearError:$}=s.useChat({transport:new s.DefaultChatTransport({api:"https://semaphor.cloud/api/v1/assistant",headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const _=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:i,aiContext:_.currentAIContext,reasoningEffort:_.reasoningEffort,showReasoning:_.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:_,body:ee})=>({body:{...ee,messages:s.cleanupIncompleteMessages(_)}})}),onError:_=>{console.log("on error",_)},onToolCall:Y,onFinish(){a("")}});A.useEffect(()=>{y&&x&&(z({role:"user",parts:[{type:"text",text:x}]}),I(!1))},[y,x,z,I]);async function Y({toolCall:_}){var ee,le,H,Q,re,de,Se,ve,fe,se,ne,ue,be,rs,ls,os;if(["createChartFromSql","createForecast"].includes(_.toolName)){const Xe=((ee=_.input)==null?void 0:ee.sql)??((le=_.args)==null?void 0:le.sql),Ae=((H=_.input)==null?void 0:H.python)??((Q=_.args)==null?void 0:Q.python),me=((re=_.input)==null?void 0:re.chartType)??((de=_.args)==null?void 0:de.chartType);f(me),m(Xe),d(Ae),h(!0),X({tool:_.toolName,toolCallId:_.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(_.toolName==="getUserSql"){if(!c){X({tool:_.toolName,toolCallId:_.toolCallId,output:{status:"error",message:"No SQL found"}});return}X({tool:_.toolName,toolCallId:_.toolCallId,output:{status:"success",sql:c,python:u||""}})}else if(_.toolName==="generateQueryConfig"){a("Generating query config...");const Xe=((Se=_.input)==null?void 0:Se.chartType)??((ve=_.args)==null?void 0:ve.chartType),Ae=((fe=_.input)==null?void 0:fe.queryConfig)??((se=_.args)==null?void 0:se.queryConfig);((ne=_.input)==null?void 0:ne.cardConfig)??((ue=_.args)==null||ue.cardConfig),f(Xe),O(Ae),m(void 0),d(void 0);const me=await D();if((be=me==null?void 0:me.data)!=null&&be.error){X({tool:_.toolName,toolCallId:_.toolCallId,output:{status:"error",queryConfig:Ae,message:(rs=me==null?void 0:me.data)==null?void 0:rs.error.message}});return}if((ls=me==null?void 0:me.data)!=null&&ls.records){X({tool:_.toolName,toolCallId:_.toolCallId,output:{status:"success",queryConfig:Ae,message:"The data has been visualized"}});return}X({tool:_.toolName,toolCallId:_.toolCallId,output:{status:"success",queryConfig:Ae,message:"The data has been visualized",records:(os=me==null?void 0:me.data)==null?void 0:os.records}})}else a("Analyzing...")}function U(_){const ee=s.removeFromScopeArray(j,_);Z(ee)}function Z(_){const ee=s.sanitizeAIScope(_);S(ee),L(le=>[...le,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(ee)}`}]}])}function q(){const _={databaseName:N||"",schemaName:b||"",tableName:T||"",datamodelId:M||"",datamodelName:s.resolveDatamodelName(k),connectionId:R||"",connectionType:E||""},ee=s.dedup([...j,_]);Z(ee)}function P(){const _={databaseName:N||"",schemaName:b||"",tableName:T||"",datamodelName:s.resolveDatamodelName(k),connectionId:R||"",connectionType:E||"",datamodelId:M||""};if(!s.isInAiScopeArray([...w||[],...j],_)||j.length===0){const le=s.dedup([...w||[],...j,_]).filter(H=>H.connectionId===_.connectionId);Z(le)}}const W=!["ready","error"].includes(J),te=s.getErrorMessage(V);return{messages:B,setMessages:L,sendMessage:z,regenerate:F,isLoading:W,handleSetAIScope:P,handleAddCurrentTableToScope:q,removeFromCurrentSelections:U,currentAssitantScope:j,setCurrentAssitantScope:S,stop:K,status:J,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:te,clearError:$}}const ql=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function mt(){const t=A.useRef(null),[n,a]=A.useState(!1),[r,l]=A.useState(s.isDevEnv),[o,c]=A.useState(!1),[i,u]=A.useState(!1),d=s.useCurrentAIContext(),{setCurrentAIContext:m}=s.useAIActions(),{clearQueue:h}=s.useQueueActions(),{clearFileAttachments:f}=s.useFileActions(),g=s.useFileAttachments("editor"),j=s.useDashboardStore(se=>se.dashboard.aiContext),x=s.useEditorStore(se=>se.card.dataSource),y=s.useEditorStore(se=>se.actions.setCardSql),p=s.useEditorStore(se=>se.actions.setRunSql),N=s.useEditorStore(se=>se.showAIDialog),T=s.useDashboardStore(se=>se.handleOpenAssistantProfile),{setShowAIDialog:R,setCardPython:b}=s.useEditorActions(),{setDataSource:w}=s.useEditorActions(),{assistantProfile:v}=s.useAssistantProfile(),{messages:D,setMessages:C,sendMessage:I,isLoading:S,stop:O,status:k,llmUsage:E,errorMessage:M,clearError:B}=$l(),[L,F]=A.useState(""),V=se=>{F(se.target.value)},z=se=>{se.preventDefault();const ne=L.trim();if(!ne&&g.length===0)return;const ue=[];ne&&ue.push({type:"text",text:ne}),g.forEach(be=>{be.data&&ue.push({type:"file",mediaType:be.type,filename:be.name,url:`data:${be.type};base64,${be.data}`})}),I({role:"user",parts:ue}),F(""),f("editor"),W({force:!0})},{visibleMessages:J,hasMoreMessages:X,totalMessageCount:K,loadMoreMessages:$,resetMessageWindow:Y}=s.useMessageWindow(D,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:U,isAtBottom:Z,hasNewMessages:q,newMessageCount:P,scrollToBottom:W,handleScroll:te,resetNewMessageCount:_}=s.useAutoScroll(J,{threshold:50,delay:0,dependencies:[k,D.length]});A.useEffect(()=>{var se;N&&((se=t.current)==null||se.focus(),m({selectedEntities:(x==null?void 0:x.selectedEntities)||[]}))},[N,x,m]),s.useAutoSubmitQueue({assistantType:"editor",status:k,isLoading:S,sendMessage:I});const{hasActiveTools:ee}=s.useActiveToolStatus(D);function le(se,ne){ne==="sql"?(y(se),p(!0)):ne==="python"&&(b(se),p(!0))}function H(){var se;(se=j==null?void 0:j.selectedEntities)==null||se[0],u(!0)}function Q(){d.selectedEntities.length===0&&m({selectedEntities:(j==null?void 0:j.selectedEntities)||[]})}function re(se){Q();const ne={role:"user",parts:[{type:"text",text:se.title+" "+se.subtitle}]};I(ne)}function de(se){Q(),I({role:"user",parts:[{type:"text",text:se}]})}function Se(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:a,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:r,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:c,children:"System Message"})]})]})}function ve(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const fe=(L==null?void 0:L.length)===0&&(D==null?void 0:D.filter(se=>se.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:[ve(),T&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:T,children:(v==null?void 0:v.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Se(),s.isDevEnv,e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:H,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:"New Chat",onClick:()=>{C([]),h("editor"),B(),Y()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",onClick:()=>{R(!1)},children:e.jsx(s.ArrowRightToLine,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:U,className:"mt-2 flex w-full grow basis-0",onScroll:te,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[X&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:$,className:"text-xs",children:["Load ",Math.min(5,K-J.length)," more messages (",K-J.length," hidden)"]})}),e.jsx(s.PrintMessages,{messages:J,showTools:r,handleRun:le,showSystemMessage:o}),!ee&&e.jsx(s.AssistantStatus,{status:k,errorMessage:M})]})}),!Z&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{W({force:!0}),_()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),q&&P>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:P>9?"9+":P})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[fe&&!v&&e.jsx(s.Placeholders,{onClick:re,placeholders:ql}),e.jsx("div",{children:fe&&v&&e.jsx(s.SeedQuestions,{seedQuestions:v.seedQuestions||[],handleSeedQuestionClick:de})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:t,setInput:F,stop:O,input:L,handleInputChange:V,handleSubmit:se=>{Q(),z(se),W({force:!0})},isLoading:S,status:k,assistantType:"editor",onFocus:()=>{}})]}),E&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",E.inputTokens," prompt tokens, ",E.outputTokens," ","completion tokens, ",E.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(x==null?void 0:x.selectedEntities)||[],open:i,onOpenChange:u,dataSource:x||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}const Ks=t=>{var S;const{updateCardConfig:n,updateGroupByColumn:a,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:u,removeSortByColumn:d}=s.useEditorActions(),m=s.useEditorStore(O=>O.card.type),h=t==null?void 0:t.id,f=A.useCallback(O=>{if(!(t!=null&&t.config))return[];switch(O){case"groupBy":return(t.config.groupByColumns||[]).map(k=>({id:k.id,name:k.name,dataType:k.dataType,label:k.label!==void 0?k.label:k.name,qualifiedEntityName:k.qualifiedEntityName,entityId:k.entityId,entityName:k.entityName,entityType:k.entityType,dateFormat:k.dateFormat,customFormat:k.customFormat,granularity:k.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(k=>({id:k.id,name:k.name,dataType:k.dataType,label:k.label!==void 0?k.label:k.name,qualifiedEntityName:k.qualifiedEntityName,entityId:k.entityId,entityName:k.entityName,entityType:k.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(k=>({id:k.id,name:k.name,dataType:k.dataType,label:k.label!==void 0?k.label:k.name,qualifiedEntityName:k.qualifiedEntityName,entityId:k.entityId,entityName:k.entityName,entityType:k.entityType,direction:k.direction}));case"source":return[];default:return[]}},[t]),g=A.useCallback((O,k)=>{if(h)switch(O){case"groupBy":{n(h,{groupByColumns:k});break}case"metrics":{n(h,{metricColumns:k});break}case"pivotBy":{n(h,{pivotByColumns:k});break}case"sortBy":{n(h,{sortByColumns:k});break}}},[h,n]),j=A.useCallback((O,k,E)=>{if(!h)return;const B=f(O)[k];if(B)switch(O){case"groupBy":a(h,B.id,{label:E});break;case"metrics":r(h,B.id,{label:E});break;case"pivotBy":l(h,B.id,{label:E});break;case"sortBy":o(h,B.id,{label:E});break}},[h,f,a,r,l,o]),x=A.useCallback((O,k)=>{if(!h)return;const M=f("metrics")[O];M&&r(h,M.id,{aggregate:k,label:s.getAggregationLabel(M.name,k)})},[h,f,r]),y=A.useCallback((O,k,E)=>{if(!h)return;const B=f("groupBy")[O];if(!B)return;const L={dateFormat:k};k==="custom"&&E?L.customFormat=E:L.customFormat=void 0,a(h,B.id,L)},[h,f,a]),p=A.useCallback((O,k)=>{if(!h)return;const M=f("groupBy")[O];M&&a(h,M.id,{granularity:k})},[h,f,a]),N=A.useCallback((O,k)=>{if(!h)return;const M=f("metrics")[O];M&&r(h,M.id,{aliasTemplate:k})},[h,f,r]),T=A.useCallback((O,k)=>{if(console.log("handleValueAliasesChange",O,k),!h)return;console.log("handleValueAliasesChange",O,k);const M=f("metrics")[O];M&&(console.log("handleValueAliasesChange",k),r(h,M.id,{valueAliases:k}))},[h,f,r]),R=A.useCallback(O=>{h&&n(h,{comparisonType:O})},[h,n]),b=A.useCallback(O=>{h&&n(h,{showTrendline:O})},[h,n]),w=A.useCallback(O=>{h&&n(h,{trendlineWindow:O})},[h,n]),v=A.useCallback(O=>{h&&n(h,{trendlineGranularity:O})},[h,n]),D=A.useCallback(O=>{h&&n(h,{targetValue:O})},[h,n]),C=A.useCallback(O=>{var V;if(!h)return;const k=[...f("groupBy"),...f("pivotBy"),...f("metrics"),...f("sortBy")],E=(V=t==null?void 0:t.config)==null?void 0:V.joinPlan,M=s.validateEntityConsistency(O,k,E);if(!M.isValid){M.showError&&s.showJoinRequiredNotification();return}const B=s.getSmartContainerForField(O,k),L=f(B);if(s.fieldAlreadyExists(O,L))return;const F=s.getNewField(O,B,L);F&&g(B,[...L,F])},[h,(S=t==null?void 0:t.config)==null?void 0:S.joinPlan,f,g]),I=A.useCallback((O,k)=>{if(!h)return;const M=f(O)[k];if(M){if(O!=="sortBy"){const B=f("sortBy"),L=B.filter(F=>!(F.name===M.name&&F.qualifiedEntityName===M.qualifiedEntityName));L.length!==B.length&&n(h,{sortByColumns:L})}switch(O){case"groupBy":c(h,M.id);break;case"metrics":i(h,M.id);break;case"pivotBy":u(h,M.id);break;case"sortBy":d(h,M.id);break}}},[h,f,c,i,u,d,n]);return{getFieldsForContainer:f,setFieldsForContainer:g,updateLabel:j,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:p,handleAliasTemplateChange:N,handleValueAliasesChange:T,removeField:I,handleFieldClick:C,handleKpiComparisonTypeChange:R,handleKpiShowTrendlineChange:b,handleKpiTrendlineWindowChange:w,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:D,cardType:m}};function Yl({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function Gl({field:t}){const{attributes:n,listeners:a,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,u]=A.useState(!1),d=s.useEditorStore(j=>j.card),{handleFieldClick:m}=Ks(d),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const f=j=>{const x=(j||"").toLowerCase();switch(s.getDataType(x)){case"number":return Te;case"date":return s.Calendar;case"boolean":return Ue;case"json":return Qe;case"geo":return es;default:return ye}},g=j=>{const x=(j||"").toLowerCase(),y=s.getDataType(x);return y==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):y==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Te,{className:"h-3 w-3"})}):y==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):y==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):y==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):y==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(es,{className:"h-3 w-3"})}):y==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(as,{className:"h-3 w-3"})}):null};return f(t.dataType),e.jsxs("div",{ref:r,style:h,...n,...a,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>m(t),children:[g(t.dataType),e.jsx(s.TooltipProvider$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/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(Yl,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{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(ga,{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 Kl(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useEditorStore(T=>T.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:u}=s.useColumns(),d=o.filter(T=>T.name.toLowerCase().includes(t.toLowerCase())||T.dataType.toLowerCase().includes(t.toLowerCase())||T.qualifiedEntityName&&T.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=T=>{if(T.dataType==="number"||T.dataType==="integer"||T.dataType==="float"||T.dataType==="decimal"||T.dataType==="currency")return"metrics";const R=s.getDataType(T.dataType);return["date","string","boolean"].includes(R)?"dimensions":R==="number"?"metrics":"dimensions"},f=(a==="all"?d:d.filter(T=>m(T)===a)).reduce((T,R)=>{const b=R.qualifiedEntityName||"Other Fields";return T[b]||(T[b]={label:s.toLabel(R.entityName),fields:[]}),T[b].fields.push(R),T},{}),j=Object.keys(f),x=d.filter(T=>m(T)==="dimensions").length,y=d.filter(T=>m(T)==="metrics").length,p=d.filter(T=>m(T)==="calculated").length,N=d.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):u?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:u.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[o.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:T=>n(T.target.value)})]}),N&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:T=>r(T),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:d.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:y})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(as,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:j,className:"space-y-2",children:Object.entries(f).map(([T,R])=>{const b=c.find(w=>w.entityName===T)||{entityName:T,label:R.label};return e.jsxs(s.AccordionItem,{value:T,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{title:b.label||b.entityName,className:"flex items-center gap-2",children:[e.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:b.label||b.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:R.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:R.fields.map(w=>e.jsx(Gl,{field:w},w.id))})})]},T)})}),Object.keys(f).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(f).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 Hl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(Kl,{})," "]})}function Ql({initialJoinPlan:t,availableDataSources:n}){const[a,r]=A.useState(t),[l,o]=A.useState(new Set),c=()=>{const w=a.joins.length>0?Math.max(...a.joins.map(D=>D.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:w,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,v]}),o(new Set([...l,v.id]))},i=w=>{r({...a,joins:a.joins.filter(v=>v.id!==w)}),o(new Set([...l].filter(v=>v!==w)))},u=(w,v)=>{var S,O;const D=a.joins.find(k=>k.id===w);if(!D)return;const C={...D,...v},I=a.joins.map(k=>k.id===w?C:k);if((S=C.source)!=null&&S.name&&((O=C.target)!=null&&O.name)&&C.joinKeyGroups[0].keys.length===0){const k=n.find(L=>{var F;return L.name===((F=C.source)==null?void 0:F.name)}),E=n.find(L=>{var F;return L.name===((F=C.target)==null?void 0:F.name)}),M={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(k==null?void 0:k.name)||"",entityName:(k==null?void 0:k.name)||"",entityType:(k==null?void 0:k.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(E==null?void 0:E.name)||"",entityName:(E==null?void 0:E.name)||"",entityType:(E==null?void 0:E.type)||"table"},operator:"="},B=[...C.joinKeyGroups];B[0]={...B[0],keys:[M]},C.joinKeyGroups=B,I[I.findIndex(L=>L.id===w)]=C}r({...a,joins:I})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:u,moveJoinUp:w=>{const v=a.joins.findIndex(D=>D.id===w);if(v>0){const D=[...a.joins],C={...D[v]},I={...D[v-1]};D[v]=I,D[v-1]=C,D.forEach((O,k)=>{O.sequence=k+1});const S={...a,joins:D};r(S)}},moveJoinDown:w=>{const v=a.joins.findIndex(D=>D.id===w);if(v<a.joins.length-1){const D=[...a.joins],C={...D[v]},I={...D[v+1]};D[v]=I,D[v+1]=C,D.forEach((O,k)=>{O.sequence=k+1});const S={...a,joins:D};r(S)}},toggleJoinExpansion:w=>{const v=new Set(l);v.has(w)?v.delete(w):v.add(w),o(v)},getAvailableSourceEntities:w=>{if(a.joins.length===0)return n;const v=a.joins.findIndex(C=>C.id===w);if(v===0)return n;const D=new Set;return a.baseEntity.name&&D.add(a.baseEntity.name),a.joins.slice(0,v).forEach(C=>{D.add(C.source.name),D.add(C.target.name)}),n.filter(C=>D.has(C.name))},getAvailableTargetEntities:w=>n.filter(v=>v.name!==w),addJoinKeyGroup:w=>{const v=a.joins.find(C=>C.id===w);if(!v)return;const D=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];u(w,{joinKeyGroups:D})},updateGroupOperator:(w,v,D)=>{const C=a.joins.find(S=>S.id===w);if(!C)return;const I=[...C.joinKeyGroups];I[v]={...I[v],operator:D},u(w,{joinKeyGroups:I})},removeJoinKeyGroup:(w,v)=>{const D=a.joins.find(I=>I.id===w);if(!D)return;const C=[...D.joinKeyGroups];C.splice(v,1),u(w,{joinKeyGroups:C})},addJoinKey:(w,v)=>{const D=a.joins.find(k=>k.id===w);if(!D)return;const C=n.find(k=>k.name===D.source.name),I=n.find(k=>k.name===D.target.name),S=[...D.joinKeyGroups],O={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(C==null?void 0:C.name)||"",entityName:(C==null?void 0:C.name)||"",entityType:(C==null?void 0:C.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="};S[v]={...S[v],keys:[...S[v].keys,O]},u(w,{joinKeyGroups:S})},updateJoinKey:(w,v,D,C,I)=>{const S=a.joins.find(B=>B.id===w);if(!S)return;const O=n.find(B=>B.name===S.source.name),k=n.find(B=>B.name===S.target.name),E=[...S.joinKeyGroups],M=E[v].keys[D];C==="sourceColumnName"&&O?E[v].keys[D]={...M,source:{...M.source,name:I}}:C==="targetColumnName"&&k?E[v].keys[D]={...M,target:{...M.target,name:I}}:C==="operator"&&(E[v].keys[D]={...M,operator:I}),u(w,{joinKeyGroups:E})},removeJoinKey:(w,v,D)=>{const C=a.joins.find(S=>S.id===w);if(!C)return;const I=[...C.joinKeyGroups];I[v].keys.splice(D,1),u(w,{joinKeyGroups:I})},generateSQLPreview:()=>{const w=[...a.joins].sort((C,I)=>C.sequence-I.sequence),v=a.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let D=`SELECT *
|
|
355
355
|
FROM ${v.name}`;return w.forEach(C=>{const I=n.find(k=>k.name===C.target.name);if(!I)return;const S=C.joinKeyGroups.filter(k=>k.keys&&k.keys.length>0).map(k=>{const E=k.keys.filter(M=>{var B,L,F,V;return((B=M.source)==null?void 0:B.name)&&((L=M.target)==null?void 0:L.name)&&((F=M.source)==null?void 0:F.entityName)&&((V=M.target)==null?void 0:V.entityName)}).map(M=>`${M.source.entityName}.${M.source.name} ${M.operator} ${M.target.entityName}.${M.target.name}`);return E.length>1?`(${E.join(` ${k.operator} `)})`:E[0]}).filter(Boolean),O=S.length>1?S.join(" OR "):S[0]||"condition_here";D+=`
|
|
356
356
|
${C.joinType} JOIN ${I.name}
|
|
357
|
-
ON ${O}`}),D},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(C=>!C.source.name||!C.target.name)||a.joins.some(C=>C.joinKeyGroups.some(I=>I.keys.length===0))||a.joins.some(C=>C.joinKeyGroups.some(I=>I.keys.some(S=>!S.source.name||!S.target.name||!S.operator))))}}function Wl({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(S=>S.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:u,setJoinPlan:d,addJoin:m,removeJoin:h,updateJoin:f,moveJoinUp:g,moveJoinDown:j,toggleJoinExpansion:x,getAvailableSourceEntities:y,getAvailableTargetEntities:p,addJoinKeyGroup:b,updateGroupOperator:T,removeJoinKeyGroup:R,addJoinKey:N,updateJoinKey:w,removeJoinKey:v,generateSQLPreview:D,isValidConfiguration:C}=Ql({initialJoinPlan:t,availableDataSources:n}),I=S=>{const O=c.find(k=>k.entityName===S);return(O==null?void 0:O.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:S=>{const O=n.find(k=>k.name===S);d({...i,baseEntity:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:S,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(S=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:S.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:S.type}),S.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},S.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:D()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(S=>{const O=n.find(M=>M.name===S.source.name),k=n.find(M=>M.name===S.target.name),E=u.has(S.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:S.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",S.sequence,O&&k&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",O.name," → ",k.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(S.id),disabled:S.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(S.id),disabled:S.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(S.id),children:E?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(S.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),E&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:S.source.name,onValueChange:M=>{const B=n.find(L=>L.name===M);f(S.id,{source:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:M,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:y(S.id).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name]})},M.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:S.joinType,onValueChange:M=>f(S.id,{joinType:M}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:S.target.name,onValueChange:M=>{const B=n.find(L=>L.name===M);f(S.id,{target:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:M,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},disabled:!S.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:S.source.name?p(S.source.name).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name,M.name===S.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},M.name)):[]})]})]})]}),S.source.name&&S.target.name&&O&&k&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>b(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),S.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:S.joinKeyGroups.map((M,B)=>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 ",B+1]}),B>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:M.operator,onValueChange:L=>T(S.id,B,L),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:()=>R(S.id,B),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[M.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:M.keys.map((L,F)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[F>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:M.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:L.source.name,onValueChange:V=>w(S.id,B,F,"sourceColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:I(S.source.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:L.operator,onValueChange:V=>w(S.id,B,F,"operator",V),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:L.target.name,onValueChange:V=>w(S.id,B,F,"targetColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:I(S.target.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>v(S.id,B,F),children:e.jsx(s.X,{className:"size-3.5"})})]},L.id||F))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>N(S.id,B),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},M.id))})]})]})]},S.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(i),disabled:!C(),children:"Save"})]})]})}function ht({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Wl,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function Jl({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=a.find(c=>c.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=a.find(u=>u.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=a.find(u=>u.name===l.source.name),i=a.find(u=>u.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((u,d)=>u+d.keys.length,0)," ","condition",l.joinKeyGroups.reduce((u,d)=>u+d.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 Xl(){var m,h;const t=s.useEditorStore(f=>f.card),n=s.useEditorStore(f=>f.actions.updateCardConfig),a=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=A.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=f=>{n(t.id,{...t==null?void 0:t.config,joinPlan:f}),l(!1)},i=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},u=()=>{l(!1)},d=()=>{const f=[...a.joins].sort((x,y)=>x.sequence-y.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
|
|
358
|
-
FROM ${g.name}`;return f.forEach(x=>{const y=o.find(T=>T.name===x.target.name);if(!y)return;const p=x.joinKeyGroups.filter(T=>T.keys&&T.keys.length>0).map(T=>{const R=T.keys.filter(
|
|
357
|
+
ON ${O}`}),D},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(C=>!C.source.name||!C.target.name)||a.joins.some(C=>C.joinKeyGroups.some(I=>I.keys.length===0))||a.joins.some(C=>C.joinKeyGroups.some(I=>I.keys.some(S=>!S.source.name||!S.target.name||!S.operator))))}}function Wl({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(S=>S.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:u,setJoinPlan:d,addJoin:m,removeJoin:h,updateJoin:f,moveJoinUp:g,moveJoinDown:j,toggleJoinExpansion:x,getAvailableSourceEntities:y,getAvailableTargetEntities:p,addJoinKeyGroup:N,updateGroupOperator:T,removeJoinKeyGroup:R,addJoinKey:b,updateJoinKey:w,removeJoinKey:v,generateSQLPreview:D,isValidConfiguration:C}=Ql({initialJoinPlan:t,availableDataSources:n}),I=S=>{const O=c.find(k=>k.entityName===S);return(O==null?void 0:O.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:S=>{const O=n.find(k=>k.name===S);d({...i,baseEntity:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:S,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(S=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:S.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:S.type}),S.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},S.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:D()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(S=>{const O=n.find(M=>M.name===S.source.name),k=n.find(M=>M.name===S.target.name),E=u.has(S.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:S.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",S.sequence,O&&k&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",O.name," → ",k.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(S.id),disabled:S.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(S.id),disabled:S.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(S.id),children:E?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(S.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),E&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:S.source.name,onValueChange:M=>{const B=n.find(L=>L.name===M);f(S.id,{source:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:M,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:y(S.id).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name]})},M.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:S.joinType,onValueChange:M=>f(S.id,{joinType:M}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:S.target.name,onValueChange:M=>{const B=n.find(L=>L.name===M);f(S.id,{target:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:M,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},disabled:!S.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:S.source.name?p(S.source.name).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name,M.name===S.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},M.name)):[]})]})]})]}),S.source.name&&S.target.name&&O&&k&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>N(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),S.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:S.joinKeyGroups.map((M,B)=>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 ",B+1]}),B>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:M.operator,onValueChange:L=>T(S.id,B,L),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:()=>R(S.id,B),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[M.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:M.keys.map((L,F)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[F>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:M.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:L.source.name,onValueChange:V=>w(S.id,B,F,"sourceColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:I(S.source.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:L.operator,onValueChange:V=>w(S.id,B,F,"operator",V),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:L.target.name,onValueChange:V=>w(S.id,B,F,"targetColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:I(S.target.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>v(S.id,B,F),children:e.jsx(s.X,{className:"size-3.5"})})]},L.id||F))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>b(S.id,B),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},M.id))})]})]})]},S.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(i),disabled:!C(),children:"Save"})]})]})}function ht({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Wl,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function Jl({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=a.find(c=>c.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=a.find(u=>u.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=a.find(u=>u.name===l.source.name),i=a.find(u=>u.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((u,d)=>u+d.keys.length,0)," ","condition",l.joinKeyGroups.reduce((u,d)=>u+d.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 Xl(){var m,h;const t=s.useEditorStore(f=>f.card),n=s.useEditorStore(f=>f.actions.updateCardConfig),a=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=A.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=f=>{n(t.id,{...t==null?void 0:t.config,joinPlan:f}),l(!1)},i=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},u=()=>{l(!1)},d=()=>{const f=[...a.joins].sort((x,y)=>x.sequence-y.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
|
|
358
|
+
FROM ${g.name}`;return f.forEach(x=>{const y=o.find(T=>T.name===x.target.name);if(!y)return;const p=x.joinKeyGroups.filter(T=>T.keys&&T.keys.length>0).map(T=>{const R=T.keys.filter(b=>{var w,v,D,C;return((w=b.source)==null?void 0:w.name)&&((v=b.target)==null?void 0:v.name)&&((D=b.source)==null?void 0:D.entityName)&&((C=b.target)==null?void 0:C.entityName)}).map(b=>`${b.source.entityName}.${b.source.name} ${b.operator} ${b.target.entityName}.${b.target.name}`);return R.length>1?`(${R.join(` ${T.operator} `)})`:R[0]}).filter(Boolean),N=p.length>1?p.join(" OR "):p[0]||"condition_here";j+=`
|
|
359
359
|
${x.joinType} JOIN ${y.name}
|
|
360
|
-
ON ${b}`}),j};return o.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[a.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$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":a.joins.length>0,"text-gray-500":a.joins.length===0})}),"Join",a.joins.length>1?"s":""," (",a.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(Jl,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:o,generateSQLPreview:d})})]})}),e.jsx(ht,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:u,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(ht,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:u,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function Zl({open:t,onOpenChange:n}){const[a,r]=A.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(x=>x.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];A.useEffect(()=>{t&&r([])},[t]);const i=x=>{r(y=>y.some(b=>b.name===x.name&&b.type===x.type)?y.filter(b=>!(b.name===x.name&&b.type===x.type)):[...y,x])},u=()=>{r([...c])},d=()=>{r([])},m=()=>{if(a.length===0)return;const x=a[0],y=x.connectionId||"",p=x.connectionType||"",T=a.some(N=>N.type==="dataset")?"semanticDomain":"database";l({connectionId:y,connectionType:p,mode:T,selectedEntities:a}),n(!1)},h=x=>{switch(x.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(ja,{className:"h-4 w-4"});case"model":return e.jsx(Pn,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},f=x=>"label"in x&&x.label?x.label:x.name,g=x=>{if("description"in x&&x.description)return x.description;const y=[];return x.database&&y.push(x.database),x.schema&&y.push(x.schema),x.name&&y.push(x.name),y.join(".")},j=x=>a.some(y=>y.name===x.name&&y.type===x.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((x,y)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",j(x)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:j(x),onCheckedChange:()=>i(x)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(x)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:f(x)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(x)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:x.type})]},`${x.type}-${x.name}-${y}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function eo({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,u)=>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})]},u))})]})})}function so({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((n,a)=>{const r=s.getEntityDetails(n),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function to({isVisible:t,onToggleVisibility:n}){const[a,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),u=s.useEditorStore(f=>f.card.dataSource);Ie();const{updateDataSource:d}=s.useEditorActions(),m={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...m,...u,selectedEntities:(u==null?void 0:u.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!c}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i(!c),className:"h-6 w-6 p-0",children:c?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),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:n,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 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((f,g)=>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(f),e.jsx("button",{onClick:j=>{j.stopPropagation();const x=h.selectedEntities.filter(y=>!(y.name===f.name&&y.type===f.type));d({...m,...u,selectedEntities:x})},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(eo,{entity:f})]},`${f.type}-${f.name}-${g}`)),h.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:["+",h.selectedEntities.length-3," more"]})}),e.jsx(so,{entities:h.selectedEntities.slice(3)})]})]})}),e.jsx(Xl,{})]})]}),e.jsx(Hl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(u==null?void 0:u.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:h,fallbackDataSource:m}),e.jsx(Zl,{open:l,onOpenChange:o})]})}const no="chart-selector-standard-first";function ao(){const[t,n]=s.useLocalStorageState(no,!0);return{standardFirst:t,updatePreference:n}}const xt=({pluginVisual:t,index:n,onSelect:a})=>{const r=ys(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},pt=["default","standardPlugin","customPlugin"];function ro({selectedChart:t,onChartChange:n}){var R;const[a,r]=A.useState(!1),{data:l}=Jt();ao();const c=((R=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:R.url)||"";zs(c);const{setCardType:i,setCardPreferences:u,setIsDevMode:d}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:f}=s.useEditorActions(),[g,j]=s.useLocalStorageState("chart-section-active",null),x=A.useMemo(()=>g?[g,...pt.filter(N=>N!==g)]:pt,[g]);function y(N){m(null),u({}),i(N),["custom","text","map"].includes(N)&&(d(!0),f(void 0)),n(N),r(!1)}function p(N){m(null),u({}),i("custom"),h({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),f(void 0),n("custom"),r(!1)}const b=()=>{var w;if(t==="custom"){const v=s.useEditorStore.getState().card;return((w=v==null?void 0:v.customCardPreferences)==null?void 0:w.componentName)||"Custom Visual"}const N=s.chartTypes.find(v=>v.id===t);return(N==null?void 0:N.label)||"Select chart type"},T=()=>{var w,v;if(t==="custom"){const D=s.useEditorStore.getState().card,C=(w=D==null?void 0:D.customCardPreferences)==null?void 0:w.icon,I=(v=D==null?void 0:D.customCardPreferences)==null?void 0:v.componentName;if(C&&I)return e.jsx(lo,{icon:C,componentName:I});if(I){const S=s.getAutoDetectedChartIcon(I);if(S)return S}return e.jsx(ss,{className:"h-4 w-4"})}const N=s.chartTypes.find(D=>D.id===t);if(N){const D=N.icon;return e.jsx(D,{className:"h-4 w-4"})}return e.jsx(ss,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[T(),e.jsx("span",{children:b()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),x.map(N=>{if(N==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="default",onCheckedChange:w=>j(w?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:s.chartTypes.map(w=>{const v=w.icon;return e.jsx(s.CommandItem,{value:`${w.label} ${w.id} chart graph visualization`,onSelect:()=>y(w.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{className:"h-4 w-4"}),e.jsx("span",{children:w.label})]})},w.id)})},"default");if(N==="standardPlugin"){const w=l.filter(v=>v.pluginType==="standard");return w.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="standardPlugin",onCheckedChange:v=>j(v?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:w.filter(v=>v.componentType==="chart").map((v,D)=>e.jsx(xt,{pluginVisual:v,index:D,onSelect:()=>p(v)},`${v.url}-${v.name}-${D}`))},"standardPlugin"):null}if(N==="customPlugin"){const w=l.filter(v=>v.pluginType==="custom");return w.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="customPlugin",onCheckedChange:v=>j(v?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:w.map((v,D)=>e.jsx(xt,{pluginVisual:v,index:D,onSelect:()=>p(v)},`${v.url}-${v.name}-${D}`))},"customPlugin"):null}return null})]})]})})]})})}const lo=({icon:t,componentName:n})=>{const a=ys(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(ss,{className:"h-4 w-4"})},oo=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!0},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"}];function io({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(o=>o.card),r=((l=a==null?void 0:a.config)==null?void 0:l.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center gap-1",children:oo.map(o=>{if(o.requiresPivot&&!r)return null;const c=o.icon,i=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(o.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o.label})})]},o.id)})})}const Hs=({dataType:t})=>{const n=s.getDataType(t);return n==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):n==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Te,{className:"h-3 w-3"})}):n==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})};function co({aliasTemplate:t,onAliasTemplateChange:n}){var u;const[a,r]=A.useState(t),[l,o]=A.useState(!1),c=(u=s.useEditorStore(d=>{var m;return(m=d.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:u[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?a:t,onChange:d=>{r(d.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:d=>d.stopPropagation(),className:"h-8 text-xs",onKeyDown:d=>{d.key==="Enter"&&l&&a!==t?(n(a),o(!1)):d.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function uo({valueAliases:t,onValueAliasesChange:n}){const[a,r]=A.useState(null),[l,o]=A.useState(""),[c,i]=A.useState(""),u=()=>{n({...t,"":""})},d=h=>{const f={...t};delete f[h],n(f)},m=h=>{const f={...t};delete f[h],f[l]=c,n(f),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,f],g)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:j=>o(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:j=>i(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(f)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(f)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>d(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+g)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:u,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function mo({field:t,searchQuery:n="",limit:a=500}){const{authToken:r}=s.useSemaphorContext(),l=s.useEditorStore(u=>u.card),o=l==null?void 0:l.dataSource,c=["attribute-values",t.entityName,t.name,n,a],i=s.useQuery({queryKey:c,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},d={connection_id:o.connectionId,cardConfig:u,cardDataSource:o,cache_config:s.getCacheConfig({card:l})};console.log("requestBody",d);const m=await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(r==null?void 0:r.accessToken)||"",d);if(m!=null&&m.error)return console.error("Error fetching attribute values:",m.error),[];const h=t.name;return((m==null?void 0:m.records)||[]).map(g=>{const j=g[h]||g[t.alias||h]||g[t.label];return{id:j||"",value:j||"",label:String(j||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:i.data||[],isLoading:i.isLoading,isFetching:i.isFetching,isError:i.isError,error:i.error,refetch:i.refetch}}function ho({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:o}){var T,R;const c=!!l,[i,u]=A.useState(c?"values":"fields"),[d,m]=A.useState(""),[h,f]=A.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),g=a.filter(N=>{var v;return c?!1:!((v=r==null?void 0:r.conditions)==null?void 0:v.some(D=>D.field.id===N.id))&&N.label.toLowerCase().includes(d.toLowerCase())}),j=N=>{f({...h,field:N}),u("values")},x=()=>{if(h.field&&h.selectedValues.length>0){const N={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let w;if(c){const v=((r==null?void 0:r.conditions)||[]).map(D=>D.id===l.id?N:D);w={...r,conditions:v}}else{const v=(r==null?void 0:r.conditions)||[];w={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...v,N],groups:[]}}o(w),n(!1)}},y=()=>{if(!c||!l)return;const N=((r==null?void 0:r.conditions)||[]).filter(w=>w.id!==l.id);if(N.length>0){const w={...r,conditions:N};o(w)}else o(void 0);n(!1)},p=N=>{f({...h,selectedValues:N})},b=()=>{c&&l?(f({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),u("values")):(f({id:s.v4(),field:null,selectedValues:[]}),u("fields")),m("")};return A.useEffect(()=>{t&&b()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(T=h.field)==null?void 0:T.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(R=h.field)==null?void 0:R.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(N=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[N.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(N.value)?`${N.value.length} values`:String(N.value)})]},N.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:d,onChange:N=>m(N.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(N=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>j(N),children:[e.jsx(Hs,{dataType:s.getDataType(N.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:N.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[N.entityName,".",N.name]})]})]},N.id))}),g.length===0&&d&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',d,'"']}),g.length===0&&!d&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(xo,{field:h.field,selectedValues:h.selectedValues,onValuesChange:p,onBack:c?void 0:()=>u("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:y,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:b,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:x,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function xo({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,o]=A.useState(""),{values:c,isLoading:i,isFetching:u}=mo({field:t,searchQuery:l,limit:500}),d=l?c.filter(f=>String(f.value).toLowerCase().includes(l.toLowerCase())):c,m=f=>{const g=n.includes(f);a(g?n.filter(j=>j!==f):[...n,f])},h=()=>{n.length===d.length&&d.length>0?a([]):a(d.map(f=>f.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:f=>o(f.target.value),className:"pl-10"})]}),i||u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===d.length&&d.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",d.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:d.map(f=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(f.value),children:[e.jsx(s.Checkbox,{checked:n.includes(f.value),onCheckedChange:()=>m(f.value)}),e.jsx(vs,{className:"text-sm",children:f.label})]},f.id))})]})]})}function po({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Js,Xs,Zs;const{attributes:i,listeners:u,setNodeRef:d,transform:m,transition:h,isDragging:f}=s.useSortable({id:t.id}),g=s.useEditorStore(G=>G.card),{updateLabel:j,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:p,handleAliasTemplateChange:b,handleValueAliasesChange:T,removeField:R,handleKpiComparisonTypeChange:N,handleKpiShowTrendlineChange:w,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:D,handleKpiTargetValueChange:C}=Ks(g),[I,S]=A.useState(!1),[O,k]=A.useState(!1),[E,M]=A.useState(null),[B,L]=A.useState(t.dateFormat||"YYYY-MM-DD"),[F,V]=A.useState(t.customFormat||""),[z,J]=A.useState(!!t.customFormat),[X,K]=A.useState(t.granularity||"day"),[$,Y]=A.useState(t.aliasTemplate||""),[U,Z]=A.useState(t.valueAliases||{}),[q,P]=A.useState((Js=t.parameters)==null?void 0:Js.filters),W=G=>{G==="custom"?J(!0):(J(!1),L(G),n==="groupBy"&&y(a,G,""))},te=G=>{V(G),n==="groupBy"&&y(a,"custom",G)},_=G=>{var he;K(G);const ce=(he=se(G)[0])==null?void 0:he.value;ce&&!z&&(L(ce),n==="groupBy"&&y(a,ce,"")),n==="groupBy"&&p(a,G)},ee=G=>{Y(G),n==="metrics"&&b(a,G)},le=G=>{Z(G),n==="metrics"&&T(a,G)},H=G=>{j(n,a,G)},Q=G=>{var ie;if(P(G),n==="metrics"){const ce={...t,parameters:{...t.parameters,filters:G}},he=[...((ie=g.config)==null?void 0:ie.metricColumns)||[]];he[a]=ce,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:he})}k(!1)},re=()=>{R(n,a)},de={transform:s.CSS.Transform.toString(m),transition:h},Se=s.getDataType(t.dataType),ve=Se==="date",fe=c==="kpi",se=G=>{switch(G){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},ne=se(X),ue=n!=="pivotBy",be=ve&&n==="groupBy",rs=!fe&&ve&&n==="groupBy",ls=fe&&ve&&n==="groupBy",os=fe&&n==="metrics"&&((Xs=g.config)==null?void 0:Xs.comparisonType)==="target",Xe=n==="metrics",Ae=()=>e.jsx("div",{onPointerDown:G=>{G.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),me=()=>ue?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(De,{value:t.label??"",onSave:H,placeholder:"Display label...",type:"text"})]}):null,Ws=()=>be?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:X,onValueChange:_,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G,children:s.toTitleCase(G)},G))})]})]}):null,fn=()=>rs?e.jsxs(e.Fragment,{children:[Ws(),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:z?"custom":B,onValueChange:W,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:ne.map(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),z&&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:F,onChange:G=>{G.stopPropagation(),te(G.target.value)},onClick:G=>G.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,gn=()=>{var G,ie,ce,he,Me;return ls?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((G=g.config)==null?void 0:G.comparisonType)||"none",onValueChange:N,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ie=g.config)==null?void 0:ie.showTrendline)||!1,onCheckedChange:w})]})}),((ce=g.config)==null?void 0:ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((he=g.config)==null?void 0:he.trendlineWindow)||30,onChange:is=>{const Nn=parseInt(is.target.value)||30;v(Nn)},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:((Me=g.config)==null?void 0:Me.trendlineGranularity)||"day",onValueChange:D,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},jn=()=>{var G,ie;return os?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(De,{value:((G=g.config)==null?void 0:G.targetValue)!==void 0&&((ie=g.config)==null?void 0:ie.targetValue)!==null?String(g.config.targetValue):"",onSave:ce=>{!isNaN(Number(ce))&&ce!==null?C(Number(ce)):C(0)},placeholder:"Enter target value...",type:"text"})]}):null},yn=()=>Xe?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:G=>{x(a,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(q==null?void 0:q.conditions)&&q.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:q.conditions.map(G=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{M(G),k(!0)},children:[e.jsxs("span",{className:"font-medium",children:[G.field.label,":"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(G.value)?G.value.length===1?String(G.value[0]):G.value.length<=2?G.value.join(", "):`${G.value.slice(0,2).join(", ")} +${G.value.length-2}`:String(G.value)})}),Array.isArray(G.value)&&G.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",G.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:G.value.map((ie,ce)=>e.jsx("div",{children:String(ie)},ce))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ie=>{var he;ie.stopPropagation();const ce=q.conditions.filter(Me=>Me.id!==G.id);if(ce.length>0){const Me={...q,conditions:ce};Q(Me)}else if(P(void 0),n==="metrics"){const Me={...t,parameters:{...t.parameters,filters:void 0}},is=[...((he=g.config)==null?void 0:he.metricColumns)||[]];is[a]=Me,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:is})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},G.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{M(null),k(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(hn,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(co,{aliasTemplate:$,onAliasTemplateChange:ee}),e.jsx(uo,{valueAliases:U,onValueAliasesChange:le})]})]}):null,{columns:vn=[]}=s.useColumns(),bn=(q==null?void 0:q.conditions)&&q.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:d,style:de,...i,...u,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Hs,{dataType:Se}),e.jsx(vs,{className:s.cn("w-[140px] flex-1 text-sm",bn&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Zs=q==null?void 0:q.conditions)==null?void 0:Zs.length)&&!I&&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-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:q.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:q.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),S(!I)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${I?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ie=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ie),l(ie)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),re()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),I&&e.jsxs("div",{className:"space-y-3",children:[Ae(),me(),c==="kpi"&&Ws(),fn(),gn(),jn(),yn()]})]}),O&&e.jsx(ho,{open:O,onOpenChange:G=>{k(G),G||M(null)},availableFields:vn,existingFilters:q,editingCondition:E,onSave:G=>{var ie;if(G)Q(G);else if(P(void 0),n==="metrics"){const ce={...t,parameters:{...t.parameters,filters:void 0}},he=[...((ie=g.config)==null?void 0:ie.metricColumns)||[]];he[a]=ce,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:he})}M(null)}})]})}function fo({concept:t}){const n=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$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:n()})]})})}function us({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),d=s.useEditorStore(j=>j.card),m=s.useEditorStore(j=>j.card.type),h=n.length>0,f=(j,x)=>{var p;!((p=d.config)!=null&&p.sortByColumns)||d.config.sortByColumns.findIndex(b=>b.id===j)===-1||u(d.id,j,{direction:x})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),g&&e.jsx(fo,{concept:t})]}),e.jsx("div",{ref:i,className:`rounded-lg border-2 border-dashed p-1 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"min-h-[60px] border-muted-foreground/20 bg-background"}`,children:n.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:n.map(j=>j.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((j,x)=>{const p=j.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(po,{field:j,zone:t,index:x,sortDirection:p,onSortDirectionChange:b=>f(j.id,b),hasPivotColumns:o,cardType:m})})},j.id)})})})})]})}const ft=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],go=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Is({value:t,onChange:n,label:a}){const[r,l]=A.useState(!1),[o,c]=A.useState(!1),i=()=>{const u=ft.find(d=>d.value===t);return u?u.color:t.startsWith("#")?t:ft[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:go.map(u=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===u?"border-gray-900":"border-transparent"),style:{backgroundColor:u},onClick:()=>{n(u),l(!1)},children:e.jsx("span",{className:"sr-only",children:u})},u))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(ln,{color:i(),onColorChange:u=>{n(u),c(!1)},onClose:()=>c(!1)})})]})]})}const ms={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
|
|
361
|
-
Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function jo(){var i,u,d,m,h,f,g,j,x,y;const t=s.useEditorStore(p=>p.card),{setCardPreferences:n}=s.useEditorActions(),a=((i=t.config)==null?void 0:i.metricColumns)||[],r=((u=t.config)==null?void 0:u.groupByColumns)||[];if(!(t.type==="kpi"&&(a.length>=2&&r.length===0||a.length>=1&&r.length>0)))return null;const o=((m=(d=t.preferences)==null?void 0:d.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=p=>{var T;const b={...t.preferences,kpiVisualOptions:{...(T=t.preferences)==null?void 0:T.kpiVisualOptions,metricComparison:{...o,...p}}};n(b)};return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:p=>c({enabled:p,...p&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:p=>c({calculationType:p}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(ms).map(([p,b])=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:b.label},p))})]}),(()=>{var b,T,R;const p=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(b=ms[p])==null?void 0:b.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(T=ms[p])==null?void 0:T.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(R=ms[p])==null?void 0:R.example]})]})})()]}),e.jsx(Ys,{formatOptions:o.formatOptions||{},onFormatOptionsChange:p=>c({formatOptions:p}),showTitle:!0,title:"COMPARISON FORMAT"}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"left",onValueChange:p=>c({position:p}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:p=>c({showArrow:p})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:p=>c({showColor:p})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Is,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:p=>c({colorConfig:{...o.colorConfig,increase:p}}),label:"Primary > Secondary"}),e.jsx(Is,{value:((f=o.colorConfig)==null?void 0:f.decrease)||"red",onChange:p=>c({colorConfig:{...o.colorConfig,decrease:p}}),label:"Primary < Secondary"}),e.jsx(Is,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:p=>c({colorConfig:{...o.colorConfig,noChange:p}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:p=>c({conditionalLabel:p})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((j=o.conditionalLabels)==null?void 0:j.increase)??"Increase",onChange:p=>c({conditionalLabels:{...o.conditionalLabels,increase:p.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((x=o.conditionalLabels)==null?void 0:x.decrease)??"Decrease",onChange:p=>c({conditionalLabels:{...o.conditionalLabels,decrease:p.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((y=o.conditionalLabels)==null?void 0:y.noChange)??"No change",onChange:p=>c({conditionalLabels:{...o.conditionalLabels,noChange:p.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:p=>c({labelName:p.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function yo(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var u;const i={...t.preferences,kpiVisualOptions:{...(u=t.preferences)==null?void 0:u.kpiVisualOptions,formatOptions:c}};n(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Te,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(Ys,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function vo({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const l=s.useEditorStore(j=>{var x;return((x=j.card.customCardPreferences)==null?void 0:x.url)&&j.card.type==="custom"}),o=s.useEditorStore(j=>j.card),c=o==null?void 0:o.type,i=t.length>0||a.length>0,u=c!=="kpi",d=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel"].includes(c),h=u&&!m,f=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(us,{zone:"groupBy",fields:t,label:f().label,placeholder:f().placeholder}),h&&e.jsx(us,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(us,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),d&&e.jsx(us,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(yo,{}),e.jsx(jo,{}),e.jsx(on,{}),e.jsx(cn,{}),e.jsx(dn,{}),e.jsx(un,{})]})})]})]})}function bo({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(h=>h.showAIDialog),i=a.length>0||r.length>0||l.length>0,{setShowAIDialog:u}=s.useEditorActions(),d=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(d);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(ro,{selectedChart:t,onChartChange:n}),e.jsx(io,{selectedChart:t,onChartChange:n})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||m}),children:e.jsx(js,{})}),!c&&e.jsxs(s.Button,{onClick:()=>u(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(s.Sparkles,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(vo,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function No({initialFilters:t,availableFields:n}={}){const[a,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(N=>N.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=n||l||[],u={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},d=N=>{const w=v=>{if(v.id===N){const D=i[0]||u,C=s.getDataType(D.dataType)==="date";return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:D,operator:C?"between":"=",value:C?[]:""}]}}return{...v,groups:v.groups.map(w)}};r(w(a))},m=N=>{const w=v=>{if(v.id===N){const D=i[0]||u,C=s.getDataType(D.dataType)==="date";return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:C?"between":"=",value:C?[]:""}],groups:[]}]}}return{...v,groups:v.groups.map(w)}};r(w(a))},h=(N,w)=>{const v=D=>D.id===N?{...D,conditions:D.conditions.filter(C=>C.id!==w)}:{...D,groups:D.groups.map(v)};r(v(a))},f=(N,w)=>{const v=D=>D.id===N?{...D,groups:D.groups.filter(C=>C.id!==w)}:{...D,groups:D.groups.map(v)};r(v(a))},g=(N,w,v,D)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const C=I=>I.id===N?{...I,conditions:I.conditions.map(S=>S.id===w?{...S,[v]:D}:S)}:{...I,groups:I.groups.map(C)};r(C(a))},j=(N,w,v)=>{const D=C=>C.id===N?{...C,conditions:C.conditions.map(I=>I.id===w?{...I,...v}:I)}:{...C,groups:C.groups.map(D)};r(D(a))},x=(N,w)=>{const v=D=>D.id===N?{...D,logicalOperator:w}:{...D,groups:D.groups.map(v)};r(v(a))},y=(N,w)=>{const v=D=>D.id===N?{...D,negate:w}:{...D,groups:D.groups.map(v)};r(v(a))},p=(N,w,v)=>{const D=C=>C.id===N?{...C,conditions:s.arrayMove(C.conditions,w,v)}:{...C,groups:C.groups.map(D)};r(D(a))},b=(N,w,v)=>{const D=C=>C.id===N?{...C,groups:s.arrayMove(C.groups,w,v)}:{...C,groups:C.groups.map(D)};r(D(a))},T=N=>{if(!N||N.conditions.length===0&&N.groups.length===0)return"-- No filters defined";const w=D=>{let C="";typeof D.field=="object"?C=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:C=String(D.field);const I=D.operator;let S=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof S=="string"?S=`'${S}'`:Array.isArray(S)&&(S=`'${S.join(", ")}'`);else if(D.field.dataType==="date"||D.field.dataType==="datetime"||D.field.dataType==="timestamp")if(D.operator==="between"&&Array.isArray(S)&&S.length===2){const O=S[0]?`'${S[0]}'`:"NULL",k=S[1]?`'${S[1]}'`:"NULL";return`${C} BETWEEN ${O} AND ${k}`}else if((D.operator==="in"||D.operator==="not in")&&Array.isArray(S)){const O=S.map(k=>k?`'${k}'`:"NULL").join(", ");return`${C} ${I} (${O})`}else typeof S=="string"||S instanceof Date?S=`'${S}'`:Array.isArray(S)&&S.length>0&&(S=`'${S[0]}'`);else if(["in","not in"].includes(D.operator)){let O=[];Array.isArray(S)?O=S.map(k=>typeof k=="string"?`'${k}'`:String(k)):typeof S=="string"?O=S.split(",").map(k=>{const E=k.trim();return D.field.dataType==="string"?`'${E}'`:E}):typeof S=="number"&&(O=[String(S)]),S=`(${O.join(", ")})`}switch(I){case"contains":return typeof S=="string"?`${C} LIKE '%${S.replace(/'/g,"")}'`:`${C} LIKE '%${String(S)}'`;case"startsWith":return typeof S=="string"?`${C} LIKE '${S.replace(/'/g,"")}%'`:`${C} LIKE '${String(S)}%'`;case"endsWith":return typeof S=="string"?`${C} LIKE '%${S.replace(/'/g,"")}'`:`${C} LIKE '%${String(S)}'`;case"isNull":return`${C} IS NULL`;case"isNotNull":return`${C} IS NOT NULL`;default:return`${C} ${I} ${S}`}},v=D=>{const C=D.conditions.map(w),I=D.groups.map(E=>v(E)),S=[...C,...I].filter(Boolean);if(S.length===0)return"";const O=S.join(` ${D.logicalOperator} `),k=S.length>1?`(${O})`:O;return D.negate?`NOT ${k}`:k};return v(N)},R=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:d,addGroup:m,removeCondition:h,removeGroup:f,updateCondition:g,updateConditionFields:j,updateGroupOperator:x,updateGroupNegate:y,reorderConditions:p,reorderGroups:b,generateSQLPreview:T,hasAnyFilters:R}}function Co({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const So=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(s.File,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},wo=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function Do({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[o,c]=A.useState(!1),i=A.useMemo(()=>{const u={};return a.forEach(d=>{const m=wo(d);u[m]||(u[m]={}),u[m][d.entityId]||(u[m][d.entityId]=[]),u[m][d.entityId].push(d)}),u},[a]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Co,{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(([u,d])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),u]}),children:Object.entries(d).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[So(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((f,g)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{n(f),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)===f.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:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+g))]},`${u}-${m}`))},u))})]})})]})}function Qs(t){var j;const n=s.useEditorStore(x=>x.card),{authToken:a}=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"},u={joinPlan:l,groupByColumns:[o],metricColumns:[c],sortByColumns:[i]},d=((j=n.dataSource)==null?void 0:j.connectionId)||n.connectionId,{data:m,isPending:h,error:f}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(a==null?void 0:a.accessToken)||"",{connection_id:d,cardConfig:u,cardDataSource:n.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!d,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(x=>({label:x.value||"BLANK",value:x.value||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:h,error:f}}function ko({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[o,c]=pe.useState(!1),{filterValues:i}=Qs(t),u=m=>{a(n.filter(h=>h!==m))},d=m=>{n.includes(m)?a(n.filter(h=>h!==m)):a([...n,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(m=>{const h=i.find(f=>f.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:f=>{f.key==="Enter"&&u(m)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),u(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>d(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function To({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=Qs(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:o.map((u,d)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:u.value,children:u.label},u.value+d))})]})}function Eo({value:t,operator:n,onChange:a,className:r}){var u;const{tokenProps:l}=s.useSemaphorContext(),o=(u=l==null?void 0:l.params)==null?void 0:u.timeZone,c=A.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const d=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(d&&m)return{from:d,to:m}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const d=new Date(t);if(!isNaN(d.getTime()))return{from:d,to:d}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const d=new Date(t);if(!isNaN(d.getTime()))return{from:d,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const d=new Date(t);if(!isNaN(d.getTime()))return{from:void 0,to:d}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const d=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):d;if(!isNaN(d.getTime()))return{from:d,to:m}}}},[t,n]),i=d=>{if(!d){a(void 0);return}if(d.from&&d.to)a([d.from.toISOString(),d.to.toISOString()]);else if(d.from){const m=new Date(d.from);m.setHours(23,59,59,999),a([d.from.toISOString(),m.toISOString()])}else if(d.to){const m=new Date(d.to);m.setHours(0,0,0,0),a([m.toISOString(),d.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Io=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Ao=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Mo=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Lo=["=","!=","isNull","isNotNull"],Ro=["between","isNull","isNotNull"],Oo={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null"};function gt(t){return Oo[t]||s.titleCase(t)}function Fo(t){switch(t){case"string":return Ao;case"number":return Mo;case"boolean":return Lo;case"date":return Ro;default:return Io}}function pn({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:u}){const{attributes:d,listeners:m,setNodeRef:h,transform:f,transition:g,isDragging:j}=s.useSortable({id:t.id}),{isPending:x,error:y}=Qs(t.field),p={transform:s.CSS.Transform.toString(f),transition:g};return e.jsxs("div",{ref:h,style:p,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${j?"z-50 opacity-50":""}`,children:[e.jsx("div",{...d,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:b=>c(a,b),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(Do,{value:t.field,onValueChange:b=>{const T=b,R=s.getDataType(T.dataType)==="date";u(a,t.id,{field:T,value:"",operator:R?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:b=>{b==="in"||b==="not in"?u(a,t.id,{operator:b,value:[]}):b==="isNull"||b==="isNotNull"?u(a,t.id,{operator:b,value:null}):u(a,t.id,{operator:b,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-44",children:e.jsx(s.SelectValue,{children:t.operator?gt(t.operator):""})}),e.jsx(s.SelectContent,{children:Fo(s.getDataType(t.field.dataType)).map(b=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:b,children:gt(b)},b))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?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..."]}):y?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ko,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(b=>typeof b=="string")?t.value:[],onChange:b=>u(a,t.id,{value:b}),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:b=>u(a,t.id,{value:b.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(To,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:b=>u(a,t.id,{value:b}),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:b=>u(a,t.id,{value:b==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(Eo,{value:t.value,operator:t.operator,onChange:b=>u(a,t.id,{value:b}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:b=>l(a,t.id,"value",b.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Bo({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:u,onReorderConditions:d,onReorderGroups:m,onAddCondition:h,onAddGroup:f,availableFields:g,renderFilterGroup:j,updateConditionFields:x}){const{attributes:y,listeners:p,setNodeRef:b,transform:T,transition:R,isDragging:N}=s.useSortable({id:t.id}),w={transform:s.CSS.Transform.toString(T),transition:R},v=C=>{const{active:I,over:S}=C;if(S&&I.id!==S.id){const O=t.conditions.findIndex(E=>E.id===I.id),k=t.conditions.findIndex(E=>E.id===S.id);O!==-1&&k!==-1&&d(t.id,O,k)}},D=C=>{const{active:I,over:S}=C;if(S&&I.id!==S.id&&a){const O=t.groups.findIndex(E=>E.id===I.id),k=t.groups.findIndex(E=>E.id===S.id);O!==-1&&k!==-1&&m(a,O,k)}};return e.jsxs("div",{ref:b,style:w,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${N?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...y,...p,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:C=>r(t.id,C),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&o(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:v,children:e.jsx(s.SortableContext,{items:t.conditions.map(C=>C.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((C,I)=>e.jsx(pn,{condition:C,index:I,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:u,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:x},C.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:D,children:e.jsx(s.SortableContext,{items:t.groups.map(C=>C.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(C=>j(C,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Po({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:u,addGroup:d,removeCondition:m,removeGroup:h,updateCondition:f,updateConditionFields:g,updateGroupOperator:j,updateGroupNegate:x,reorderConditions:y,reorderGroups:p,generateSQLPreview:b,hasAnyFilters:T,setCurrentFilters:R}=No({initialFilters:t,availableFields:n}),N=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[w,v]=A.useState(!1),D=(S,O,k)=>{const E=M=>M.id===S?{...M,conditions:M.conditions.map(B=>B.id===O?{...B,field:k,dataType:k.dataType}:B)}:{...M,groups:M.groups.map(E)};R(E(o))},C=(S,O=0,k)=>O===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:N,collisionDetection:s.closestCenter,onDragEnd:E=>{const{active:M,over:B}=E;if(B&&M.id!==B.id){const L=S.conditions.findIndex(V=>V.id===M.id),F=S.conditions.findIndex(V=>V.id===B.id);L!==-1&&F!==-1&&y(S.id,L,F)}},children:e.jsx(s.SortableContext,{items:S.conditions.map(E=>E.id),strategy:s.verticalListSortingStrategy,children:S.conditions.map((E,M)=>e.jsx(pn,{condition:E,index:M,groupId:S.id,groupLogicalOperator:S.logicalOperator,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:g},E.id))})}),e.jsx(s.DndContext,{sensors:N,collisionDetection:s.closestCenter,onDragEnd:E=>{const{active:M,over:B}=E;if(B&&M.id!==B.id){const L=S.groups.findIndex(V=>V.id===M.id),F=S.groups.findIndex(V=>V.id===B.id);L!==-1&&F!==-1&&p(S.id,L,F)}},children:e.jsx(s.SortableContext,{items:S.groups.map(E=>E.id),strategy:s.verticalListSortingStrategy,children:S.groups.map(E=>C(E,O+1,S.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>u(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>d(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},S.id):e.jsx(Bo,{group:S,depth:O,parentGroupId:k,onUpdateGroupOperator:j,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onReorderConditions:y,onReorderGroups:p,onAddCondition:u,onAddGroup:d,availableFields:c,renderFilterGroup:C,updateConditionFields:g},S.id),I=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):C(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:w,onCheckedChange:S=>v(!!S)}),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)"})]})}),T&&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:b(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),I>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(T?o:null),children:"Apply Filters"})]})]})}function zo({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=d=>{a(t,d),c(!1)},u=()=>{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:d=>{d.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(Po,{filters:n,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:u})]})]})}function Vo({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[l,o]=A.useState(null),c=s.useEditorStore(j=>j.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,u=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],d=A.useCallback(j=>j.startsWith("card-")?null:j.startsWith("source-")||n.find(x=>x.id===j)?"source":a("groupBy").find(x=>x.id===j)?"groupBy":a("metrics").find(x=>x.id===j)?"metrics":a("pivotBy").find(x=>x.id===j)?"pivotBy":a("sortBy").find(x=>x.id===j)?"sortBy":null,[n,a]),m=A.useCallback(j=>{o(j.active.id)},[]),h=A.useCallback(j=>{const{active:x,over:y}=j;if(!y||!t){o(null);return}const p=x.id,b=y.id,T=d(p),R=d(b)||b;if(R==="sortBy"){if(T==="source"){const N=n.find(v=>v.id===p);if(!N){o(null);return}if(!(a("groupBy").some(v=>v.name===N.name&&v.qualifiedEntityName===N.qualifiedEntityName)||a("metrics").some(v=>v.name===N.name&&v.qualifiedEntityName===N.qualifiedEntityName))){o(null);return}}else if(T==="pivotBy"){o(null);return}else if(T!=="groupBy"&&T!=="metrics"&&T!=="sortBy"){o(null);return}}if(T==="source"&&R==="sortBy"){const N=[...n].find(D=>D.id===p);if(!N){o(null);return}const w=a("sortBy");if(s.fieldAlreadyExists(N,w)){o(null);return}const v=s.getNewField(N,"sortBy",w);o(null),r("sortBy",[...w,v]);return}if(T==="source"&&R!=="source"&&R!=="sortBy"){const N=[...n].find(C=>C.id===p);if(!N){o(null);return}const w=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(w.length>0){const C=w[0].qualifiedEntityName;if(!C){o(null);return}if(C!==N.qualifiedEntityName&&N.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(C,N.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const v=a(R);if(s.fieldAlreadyExists(N,v)){o(null);return}const D=s.getNewField(N,R,v);o(null),r(R,[...v,D]);return}if(T&&R&&T!=="source"&&R!=="source"&&T!==R){const N=a(T),w=a(R),v=N.find(I=>I.id===p);if(!v){o(null);return}const D=s.getNewField(v,R,w);if(o(null),R==="sortBy"){s.fieldAlreadyExists(v,w)||r(R,[...w,D]);return}const C=N.filter(I=>I.id!==p);r(T,C),r(R,[...w,D]);return}if(T&&R&&T===R&&T!=="source"){const N=a(T),w=N.findIndex(D=>D.id===p),v=N.findIndex(D=>D.id===b);if(w!==v){const D=s.arrayMove(N,w,v);r(T,D)}}o(null)},[t,n,a,r,d,i]),f=l?u.find(j=>j.id===l):null;return{activeId:l,activeField:f,handleDragStart:m,handleDragEnd:h}}function _o({dashboardFilterCount:t=0,cardFilterCount:n=0,clickFilterCount:a=0,onClick:r,className:l,showIcon:o=!0}){const c=t+n+a,i=c>0,u=t>0,d=n>0,m=a>0,h=e.jsxs(e.Fragment,{children:[o&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),f=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",l),children:h});return i?e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:f}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"p-2 text-xs",children:e.jsxs("div",{className:"space-y-1.5",children:[u&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-purple-500"}),e.jsxs("span",{children:[t," Dashboard filter",t!==1?"s":""]})]}),d&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),e.jsxs("span",{children:[n," Card filter",n!==1?"s":""]})]}),m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-gray-500"}),e.jsxs("span",{children:[a," Click filter",a!==1?"s":""]})]})]})})]})}):f}function Uo({onAdvancedToggle:t,onDebugToggle:n,onAccept:a}){const{currentUser:r}=Ie();r==null||r.role;const[l,o]=A.useState(!1),c=s.useEditorStore(p=>p.isDevMode),i=s.useEditorStore(p=>p.card),u=s.useEditorStore(p=>p.card.dataSource);s.isExplorerCard(i);const{config:d}=A.useContext(s.SemaphorContext).tokenProps,m=(d==null?void 0:d.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),f=s.useEditorStore(p=>p.showAIDialog),g=s.useEditorStore(p=>p.frame),j=s.useManagementStore(p=>p.selectedVisual),x=(j==null?void 0:j.id)===(g==null?void 0:g.id),{setShowAIDialog:y}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",f&&"justify-end",!m&&"justify-end"),children:[m&&t&&!f&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:c,onCheckedChange:()=>h(!c),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[(r==null?void 0:r.type)!=="tenant"&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 p-0",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>{o(!0)},children:[e.jsx(s.Database,{className:"mr-2 h-4 w-4"}),"Set Data Context"]})})]}),e.jsx($s,{}),a&&!x&&e.jsx(Us,{variant:"default"}),x&&e.jsx(Lr,{}),n&&s.isDevEnv]}),l&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(u==null?void 0:u.selectedEntities)||[],open:l,onOpenChange:o,dataSource:u||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function $o({activeView:t,onViewChange:n}){const a=s.useEditorStore(l=>l.card),{errorMessage:r}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:l=>n(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),a.type!=="kpi"&&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":"Info"})]})})}const qo=[{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 Yo(){var u,d;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=A.useState(!1),[l,o]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((d=(u=t.config)==null?void 0:u.rowLimit)==null?void 0:d.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:qo.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function Go({isOpen:t,onClose:n}){const a=Lt(n,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:u}=s.useCustomVisual(r),d=A.useMemo(()=>!r||r.trim()===""?null:u("Chart Settings"),[u,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:d&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(d,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function Ko({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:u,activeCard:d,columns:m,columnsLoading:h,columnsError:f}){var J;const g=s.useEditorStore(X=>X.card),j=s.useDashboardStore(X=>X.filterValues),x=(j==null?void 0:j.length)||0,{updateCardConfig:y,setCard:p,updateCardInFrame:b,setCardId:T}=s.useEditorActions(),{updateCardId:R}=s.useDashboardActions(),[N,w]=A.useState(null),v=s.useEditorStore(X=>X.showAIDialog),[D,C]=A.useState(!1),{isConsoleMode:I}=s.useDashboardPreferences(),S=s.useEditorStore(X=>{var K;return((K=X.card.customCardPreferences)==null?void 0:K.url)&&X.card.type==="custom"}),{data:O,errorMessage:k,isLoading:E,isFetching:M,pagination:B}=s.useDashboardCardQuery(d),L=(X,K)=>{const $={...d,paginationConfig:{page:X+1,pageSize:K}};p($),b($)};function F(){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(j||{},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(d.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",m.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":f?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const V=X=>{if(!g.config)return;if(!X.length){y(g.id,{...g.config,sortByColumns:[]});return}const K=g.config,$=X.map(({id:Y,desc:U})=>{var W,te;const Z=(W=K.metricColumns)==null?void 0:W.find(_=>_.label===Y),q=(te=K.groupByColumns)==null?void 0:te.find(_=>_.label===Y),P=Z||q;return P?{id:s.getFieldId("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:U?"desc":"asc"}:null}).filter(Y=>Y!==null);y(g.id,{...K,sortByColumns:$})},z=A.useMemo(()=>{var X,K;return(K=(X=g.config)==null?void 0:X.sortByColumns)==null?void 0:K.map($=>({id:$.label,desc:$.direction==="desc"}))},[(J=g.config)==null?void 0:J.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(Uo,{showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:u}),a&&F(),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"&&v&&e.jsx(Zt,{variant:"outline"}),e.jsx($o,{activeView:t,onViewChange:n}),i&&e.jsx(_o,{dashboardFilterCount:x,cardFilterCount:u,onClick:i,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(Yo,{})}),v&&e.jsx(js,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(en,{})})]}),!D&&S&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>C(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(sn,{})}),t==="table"&&(O==null?void 0:O.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:d,data:(O==null?void 0:O.records)||[],paginationMetadata:B,onPaginationChange:L,isLoading:E||M,onSortChange:V,sortState:z})}),t==="sql"&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[I&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:g.id,onSave:X=>{const K=s.sanitizeCardId(X);if(!K){w("Card ID cannot be empty");return}const $=R(g.id,K);if($.success){T(K);const Y={...g,id:K};p(Y),b(Y),w(null),s.ue.success("Card ID updated successfully")}else w($.error||"Failed to update Card ID"),s.ue.error($.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:g.id,className:"h-5 w-5"})]}),N&&e.jsx("p",{className:"text-xs text-destructive",children:N})]}),(O==null?void 0:O.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(Gt,{sql:O==null?void 0:O.sql,error:k})]})})]}),e.jsx(Go,{isOpen:D,onClose:()=>C(!1)})]})]})}function Ho({activeField:t}){const[n,a]=A.useState(!0);return A.useEffect(()=>{t&&a(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Hs,{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 Qo=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const n=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},a=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function Wo(){var K,$;const[t,n]=A.useState("chart"),[a,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),u=s.useEditorStore(Y=>Y.showAIDialog),d=s.useDashboardStore(Y=>Y.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(Y=>Y.card.type);A.useEffect(()=>Qo(),[]);const f=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},j=()=>{console.log("Advanced mode toggled")},x=()=>{o(!0)},y=Y=>{m(Y)},p=s.useEditorStore(Y=>Y.frame),b=s.useEditorStore(Y=>Y.card);s.useEditorStore(Y=>Y.activeTabCardId),s.useEditorStore(Y=>Y.actions.getAvailableFields);const{addCard:T,removeCard:R,updateCard:N,setActiveCard:w,updateFilters:v}=s.useEditorActions(),{columns:D=[],isLoading:C,error:I}=s.useColumns(),S=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=b,{getFieldsForContainer:k,setFieldsForContainer:E}=Ks(O),{activeField:M,handleDragStart:B,handleDragEnd:L}=Vo({activeCardId:p.activeCardId,sourceFields:D,getFieldsForContainer:k,setFieldsForContainer:E}),F=(Y,U)=>{U&&v(Y,U)},V=Y=>{var U;N(Y,{config:{...(U=p.cards.find(Z=>Z.id===Y))==null?void 0:U.config,filters:void 0}})},z=D,J=Y=>{if(!Y)return 0;let U=Y.conditions.length;return Y.groups.forEach(Z=>{U+=J(Z)}),U},X=J(((K=O==null?void 0:O.config)==null?void 0:K.filters)||null);return e.jsxs(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragStart:B,onDragEnd:L,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(to,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!u&&e.jsx(bo,{selectedChart:h,onChartChange:y,groupByFields:k("groupBy"),pivotByFields:k("pivotBy"),metricsFields:k("metrics"),sortByFields:k("sortBy")}),e.jsx(Ko,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onAccept:f,onClear:g,onAdvancedToggle:j,onFiltersClick:x,filterCount:X,activeCard:O,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:D,columnsLoading:C,columnsError:I,getFieldsForContainer:k,cards:p.cards,activeCardId:p.activeCardId,addCard:T,setActiveCard:w})]}),!c&&d&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),O&&e.jsx(zo,{cardId:O.id,filters:(($=O.config)==null?void 0:$.filters)||null,onFiltersChange:F,onClearFilters:V,availableFields:z,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Ho,{activeField:M||null})})]})}function Jo({authToken:t,onSave:n,onClose:a}){const r=A.useRef(null),l=s.useEditorStore(b=>b.showAIDialog),o=s.useEditorStore(b=>b.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:u,setOnClose:d}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:f,handleDragCancel:g,sensors:j}=Dr();A.useEffect(()=>{n&&u(n),a&&d(a)},[n,u,a,d]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var b,T;l?((b=r.current)==null||b.resize(40),i(!0)):(i(!1),(T=r.current)==null||T.resize(0))},[l,i]);function x(b){b<1?i(!1):l||i(!0)}function y(){return e.jsxs(e.Fragment,{children:[e.jsx(qt,{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(Ul,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(mt,{})})]})]})}function p(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Wo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(mt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:j,onDragStart:f,onDragEnd:h,onDragOver:m,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:y()})}):p()})}function Xo(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(c=>c.actions),a=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),n(!1))}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(Jo,{onSave:l,onClose:o})})}function Zo({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(Te,{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(Ue,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Ln,{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 ei(){const t=s.useEditorStore(o=>o.selectedDatabaseName),n=s.useEditorStore(o=>o.selectedTableName),a=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=qs();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(o.column_name)&&i.table===n&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zo,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function si({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Te,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(es,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(as,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})}function ti(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useDashboardStore(p=>p.dashboard.filters)||[],{assignFilter:o}=qs(),c=s.useEditorStore(p=>p.card.dataSource),{columns:i=[],isLoading:u,error:d}=s.useColumns(),m=i.filter(p=>p.name.toLowerCase().includes(t.toLowerCase())||p.dataType.toLowerCase().includes(t.toLowerCase())||p.label&&p.label.toLowerCase().includes(t.toLowerCase())),h=p=>{const b=s.getDataType(p.dataType);return b==="number"?"metrics":(["date","string","boolean"].includes(b),"dimensions")},f=a==="all"?m:m.filter(p=>h(p)===a),g=m.filter(p=>h(p)==="dimensions").length,j=m.filter(p=>h(p)==="metrics").length,x=p=>{const b={column_name:p.name,data_type:p.dataType,label:p.label,description:p.description};o(b,"dashboard",p)};if(u)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(d)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const y=m.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:p=>n(p.target.value)})]}),y&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:p=>r(p),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[f.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),f.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),f.map(p=>{const b=l==null?void 0:l.some(T=>{var R;return T.title===p.name||((R=T.column)==null?void 0:R.includes(p.name))});return e.jsx("div",{onClick:()=>x(p),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":b}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(si,{dataType:p.dataType}),e.jsx("span",{children:p.label||p.name})]})},p.id)})]})]})}function ni(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),n=s.useCurrentActiveCard(),a=n&&((r=n.dataSource)==null?void 0:r.selectedEntities)&&n.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:a?e.jsx(ti,{}):e.jsx(qt,{type:"filter",ColumnsComponent:()=>e.jsx(ei,{})})})]})}function ai(){const t=s.useDashboardStore(r=>r.dashboard.filters),n=s.useDashboardStore(r=>r.theme),a=t==null?void 0:t.filter(r=>r.hide);return a!=null&&a.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":n==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":n==="dark"}),children:a==null?void 0:a.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function ri(){const t=s.useDashboardStore(r=>r.showFilters),n=s.useDashboardStore(r=>r.isVisualEditing),a=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":n,"flex grow overflow-auto":!n}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[a&&e.jsx(ai,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(ni,{})})]})}function li(){const t=s.useDashboardStore(l=>l.dashboard),n=s.useDashboardStore(l=>l.actions.setDashboard),a=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!a}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),n(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function oi({showControls:t=!1,showFooter:n=!0,...a}){if(typeof window>"u")return null;const{preferences:r}=a;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:r,children:[e.jsx(li,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(vr,{}),e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(Xo,{}),e.jsx(ri,{})]})]})]})})]})})}exports.DashboardPlus=oi;exports.ResourceManagementPanel=Ut;exports.ScheduleDashboard=wt;exports.SelectComponent=He;exports.cleanCard=St;exports.getDashbaordStateWithoutData=xs;
|
|
360
|
+
ON ${N}`}),j};return o.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[a.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$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":a.joins.length>0,"text-gray-500":a.joins.length===0})}),"Join",a.joins.length>1?"s":""," (",a.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(Jl,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:o,generateSQLPreview:d})})]})}),e.jsx(ht,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:u,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(ht,{open:r,onOpenChange:l,joinPlan:a,availableDataSources:o,onSave:c,onCancel:u,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function Zl({open:t,onOpenChange:n}){const[a,r]=A.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(x=>x.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];A.useEffect(()=>{t&&r([])},[t]);const i=x=>{r(y=>y.some(N=>N.name===x.name&&N.type===x.type)?y.filter(N=>!(N.name===x.name&&N.type===x.type)):[...y,x])},u=()=>{r([...c])},d=()=>{r([])},m=()=>{if(a.length===0)return;const x=a[0],y=x.connectionId||"",p=x.connectionType||"",T=a.some(b=>b.type==="dataset")?"semanticDomain":"database";l({connectionId:y,connectionType:p,mode:T,selectedEntities:a}),n(!1)},h=x=>{switch(x.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(ja,{className:"h-4 w-4"});case"model":return e.jsx(Pn,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},f=x=>"label"in x&&x.label?x.label:x.name,g=x=>{if("description"in x&&x.description)return x.description;const y=[];return x.database&&y.push(x.database),x.schema&&y.push(x.schema),x.name&&y.push(x.name),y.join(".")},j=x=>a.some(y=>y.name===x.name&&y.type===x.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((x,y)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",j(x)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:j(x),onCheckedChange:()=>i(x)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(x)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:f(x)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(x)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:x.type})]},`${x.type}-${x.name}-${y}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function eo({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,u)=>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})]},u))})]})})}function so({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((n,a)=>{const r=s.getEntityDetails(n),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function to({isVisible:t,onToggleVisibility:n}){const[a,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),u=s.useEditorStore(f=>f.card.dataSource);Ie();const{updateDataSource:d}=s.useEditorActions(),m={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...m,...u,selectedEntities:(u==null?void 0:u.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!c}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i(!c),className:"h-6 w-6 p-0",children:c?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),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:n,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 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((f,g)=>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(f),e.jsx("button",{onClick:j=>{j.stopPropagation();const x=h.selectedEntities.filter(y=>!(y.name===f.name&&y.type===f.type));d({...m,...u,selectedEntities:x})},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(eo,{entity:f})]},`${f.type}-${f.name}-${g}`)),h.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:["+",h.selectedEntities.length-3," more"]})}),e.jsx(so,{entities:h.selectedEntities.slice(3)})]})]})}),e.jsx(Xl,{})]})]}),e.jsx(Hl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(u==null?void 0:u.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:h,fallbackDataSource:m}),e.jsx(Zl,{open:l,onOpenChange:o})]})}const no="chart-selector-standard-first";function ao(){const[t,n]=s.useLocalStorageState(no,!0);return{standardFirst:t,updatePreference:n}}const xt=({pluginVisual:t,index:n,onSelect:a})=>{const r=ys(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},pt=["default","standardPlugin","customPlugin"];function ro({selectedChart:t,onChartChange:n}){var R;const[a,r]=A.useState(!1),{data:l}=Jt();ao();const c=((R=s.useEditorStore(b=>b.card).customCardPreferences)==null?void 0:R.url)||"";zs(c);const{setCardType:i,setCardPreferences:u,setIsDevMode:d}=s.useEditorStore(b=>b.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:f}=s.useEditorActions(),[g,j]=s.useLocalStorageState("chart-section-active",null),x=A.useMemo(()=>g?[g,...pt.filter(b=>b!==g)]:pt,[g]);function y(b){m(null),u({}),i(b),["custom","text","map"].includes(b)&&(d(!0),f(void 0)),n(b),r(!1)}function p(b){m(null),u({}),i("custom"),h({type:"component",visualType:"single",url:b.url,componentName:b.name,icon:b.icon,pluginChartType:b.chartType}),f(void 0),n("custom"),r(!1)}const N=()=>{var w;if(t==="custom"){const v=s.useEditorStore.getState().card;return((w=v==null?void 0:v.customCardPreferences)==null?void 0:w.componentName)||"Custom Visual"}const b=s.chartTypes.find(v=>v.id===t);return(b==null?void 0:b.label)||"Select chart type"},T=()=>{var w,v;if(t==="custom"){const D=s.useEditorStore.getState().card,C=(w=D==null?void 0:D.customCardPreferences)==null?void 0:w.icon,I=(v=D==null?void 0:D.customCardPreferences)==null?void 0:v.componentName;if(C&&I)return e.jsx(lo,{icon:C,componentName:I});if(I){const S=s.getAutoDetectedChartIcon(I);if(S)return S}return e.jsx(ss,{className:"h-4 w-4"})}const b=s.chartTypes.find(D=>D.id===t);if(b){const D=b.icon;return e.jsx(D,{className:"h-4 w-4"})}return e.jsx(ss,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[T(),e.jsx("span",{children:N()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),x.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:g==="default",onCheckedChange:w=>j(w?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:s.chartTypes.map(w=>{const v=w.icon;return e.jsx(s.CommandItem,{value:`${w.label} ${w.id} chart graph visualization`,onSelect:()=>y(w.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{className:"h-4 w-4"}),e.jsx("span",{children:w.label})]})},w.id)})},"default");if(b==="standardPlugin"){const w=l.filter(v=>v.pluginType==="standard");return w.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="standardPlugin",onCheckedChange:v=>j(v?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:w.filter(v=>v.componentType==="chart").map((v,D)=>e.jsx(xt,{pluginVisual:v,index:D,onSelect:()=>p(v)},`${v.url}-${v.name}-${D}`))},"standardPlugin"):null}if(b==="customPlugin"){const w=l.filter(v=>v.pluginType==="custom");return w.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="customPlugin",onCheckedChange:v=>j(v?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:w.map((v,D)=>e.jsx(xt,{pluginVisual:v,index:D,onSelect:()=>p(v)},`${v.url}-${v.name}-${D}`))},"customPlugin"):null}return null})]})]})})]})})}const lo=({icon:t,componentName:n})=>{const a=ys(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(ss,{className:"h-4 w-4"})},oo=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!0},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"}];function io({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(o=>o.card),r=((l=a==null?void 0:a.config)==null?void 0:l.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center gap-1",children:oo.map(o=>{if(o.requiresPivot&&!r)return null;const c=o.icon,i=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(o.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o.label})})]},o.id)})})}const Hs=({dataType:t})=>{const n=s.getDataType(t);return n==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):n==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Te,{className:"h-3 w-3"})}):n==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})};function co({aliasTemplate:t,onAliasTemplateChange:n}){var u;const[a,r]=A.useState(t),[l,o]=A.useState(!1),c=(u=s.useEditorStore(d=>{var m;return(m=d.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:u[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?a:t,onChange:d=>{r(d.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:d=>d.stopPropagation(),className:"h-8 text-xs",onKeyDown:d=>{d.key==="Enter"&&l&&a!==t?(n(a),o(!1)):d.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function uo({valueAliases:t,onValueAliasesChange:n}){const[a,r]=A.useState(null),[l,o]=A.useState(""),[c,i]=A.useState(""),u=()=>{n({...t,"":""})},d=h=>{const f={...t};delete f[h],n(f)},m=h=>{const f={...t};delete f[h],f[l]=c,n(f),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,f],g)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:j=>o(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:j=>i(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(f)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(f)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>d(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+g)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:u,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function mo({field:t,searchQuery:n="",limit:a=500}){const{authToken:r}=s.useSemaphorContext(),l=s.useEditorStore(u=>u.card),o=l==null?void 0:l.dataSource,c=["attribute-values",t.entityName,t.name,n,a],i=s.useQuery({queryKey:c,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},d={connection_id:o.connectionId,cardConfig:u,cardDataSource:o,cache_config:s.getCacheConfig({card:l})};console.log("requestBody",d);const m=await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(r==null?void 0:r.accessToken)||"",d);if(m!=null&&m.error)return console.error("Error fetching attribute values:",m.error),[];const h=t.name;return((m==null?void 0:m.records)||[]).map(g=>{const j=g[h]||g[t.alias||h]||g[t.label];return{id:j||"",value:j||"",label:String(j||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:i.data||[],isLoading:i.isLoading,isFetching:i.isFetching,isError:i.isError,error:i.error,refetch:i.refetch}}function ho({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:o}){var T,R;const c=!!l,[i,u]=A.useState(c?"values":"fields"),[d,m]=A.useState(""),[h,f]=A.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),g=a.filter(b=>{var v;return c?!1:!((v=r==null?void 0:r.conditions)==null?void 0:v.some(D=>D.field.id===b.id))&&b.label.toLowerCase().includes(d.toLowerCase())}),j=b=>{f({...h,field:b}),u("values")},x=()=>{if(h.field&&h.selectedValues.length>0){const b={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let w;if(c){const v=((r==null?void 0:r.conditions)||[]).map(D=>D.id===l.id?b:D);w={...r,conditions:v}}else{const v=(r==null?void 0:r.conditions)||[];w={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...v,b],groups:[]}}o(w),n(!1)}},y=()=>{if(!c||!l)return;const b=((r==null?void 0:r.conditions)||[]).filter(w=>w.id!==l.id);if(b.length>0){const w={...r,conditions:b};o(w)}else o(void 0);n(!1)},p=b=>{f({...h,selectedValues:b})},N=()=>{c&&l?(f({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),u("values")):(f({id:s.v4(),field:null,selectedValues:[]}),u("fields")),m("")};return A.useEffect(()=>{t&&N()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(T=h.field)==null?void 0:T.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(R=h.field)==null?void 0:R.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(b=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[b.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(b.value)?`${b.value.length} values`:String(b.value)})]},b.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:d,onChange:b=>m(b.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(b=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>j(b),children:[e.jsx(Hs,{dataType:s.getDataType(b.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:b.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[b.entityName,".",b.name]})]})]},b.id))}),g.length===0&&d&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',d,'"']}),g.length===0&&!d&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(xo,{field:h.field,selectedValues:h.selectedValues,onValuesChange:p,onBack:c?void 0:()=>u("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:y,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:N,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:x,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function xo({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,o]=A.useState(""),{values:c,isLoading:i,isFetching:u}=mo({field:t,searchQuery:l,limit:500}),d=l?c.filter(f=>String(f.value).toLowerCase().includes(l.toLowerCase())):c,m=f=>{const g=n.includes(f);a(g?n.filter(j=>j!==f):[...n,f])},h=()=>{n.length===d.length&&d.length>0?a([]):a(d.map(f=>f.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:f=>o(f.target.value),className:"pl-10"})]}),i||u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===d.length&&d.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",d.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:d.map(f=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(f.value),children:[e.jsx(s.Checkbox,{checked:n.includes(f.value),onCheckedChange:()=>m(f.value)}),e.jsx(vs,{className:"text-sm",children:f.label})]},f.id))})]})]})}function po({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Js,Xs,Zs;const{attributes:i,listeners:u,setNodeRef:d,transform:m,transition:h,isDragging:f}=s.useSortable({id:t.id}),g=s.useEditorStore(G=>G.card),{updateLabel:j,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:p,handleAliasTemplateChange:N,handleValueAliasesChange:T,removeField:R,handleKpiComparisonTypeChange:b,handleKpiShowTrendlineChange:w,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:D,handleKpiTargetValueChange:C}=Ks(g),[I,S]=A.useState(!1),[O,k]=A.useState(!1),[E,M]=A.useState(null),[B,L]=A.useState(t.dateFormat||"YYYY-MM-DD"),[F,V]=A.useState(t.customFormat||""),[z,J]=A.useState(!!t.customFormat),[X,K]=A.useState(t.granularity||"day"),[$,Y]=A.useState(t.aliasTemplate||""),[U,Z]=A.useState(t.valueAliases||{}),[q,P]=A.useState((Js=t.parameters)==null?void 0:Js.filters),W=G=>{G==="custom"?J(!0):(J(!1),L(G),n==="groupBy"&&y(a,G,""))},te=G=>{V(G),n==="groupBy"&&y(a,"custom",G)},_=G=>{var he;K(G);const ce=(he=se(G)[0])==null?void 0:he.value;ce&&!z&&(L(ce),n==="groupBy"&&y(a,ce,"")),n==="groupBy"&&p(a,G)},ee=G=>{Y(G),n==="metrics"&&N(a,G)},le=G=>{Z(G),n==="metrics"&&T(a,G)},H=G=>{j(n,a,G)},Q=G=>{var ie;if(P(G),n==="metrics"){const ce={...t,parameters:{...t.parameters,filters:G}},he=[...((ie=g.config)==null?void 0:ie.metricColumns)||[]];he[a]=ce,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:he})}k(!1)},re=()=>{R(n,a)},de={transform:s.CSS.Transform.toString(m),transition:h},Se=s.getDataType(t.dataType),ve=Se==="date",fe=c==="kpi",se=G=>{switch(G){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},ne=se(X),ue=n!=="pivotBy",be=ve&&n==="groupBy",rs=!fe&&ve&&n==="groupBy",ls=fe&&ve&&n==="groupBy",os=fe&&n==="metrics"&&((Xs=g.config)==null?void 0:Xs.comparisonType)==="target",Xe=n==="metrics",Ae=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:G=>{G.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),me=()=>ue?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(De,{value:t.label??"",onSave:H,placeholder:"Display label...",type:"text"})]}):null,Ws=()=>be?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:X,onValueChange:_,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G,children:s.toTitleCase(G)},G))})]})]}):null,fn=()=>rs?e.jsxs(e.Fragment,{children:[Ws(),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:z?"custom":B,onValueChange:W,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:ne.map(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),z&&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:F,onChange:G=>{G.stopPropagation(),te(G.target.value)},onClick:G=>G.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,gn=()=>{var G,ie,ce,he,Me;return ls?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((G=g.config)==null?void 0:G.comparisonType)||"none",onValueChange:b,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ie=g.config)==null?void 0:ie.showTrendline)||!1,onCheckedChange:w})]})}),((ce=g.config)==null?void 0:ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((he=g.config)==null?void 0:he.trendlineWindow)||30,onChange:is=>{const Nn=parseInt(is.target.value)||30;v(Nn)},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:((Me=g.config)==null?void 0:Me.trendlineGranularity)||"day",onValueChange:D,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},jn=()=>{var G,ie;return os?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(De,{value:((G=g.config)==null?void 0:G.targetValue)!==void 0&&((ie=g.config)==null?void 0:ie.targetValue)!==null?String(g.config.targetValue):"",onSave:ce=>{!isNaN(Number(ce))&&ce!==null?C(Number(ce)):C(0)},placeholder:"Enter target value...",type:"text"})]}):null},yn=()=>Xe?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:G=>{x(a,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(q==null?void 0:q.conditions)&&q.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:q.conditions.map(G=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{M(G),k(!0)},children:[e.jsxs("span",{className:"font-medium",children:[G.field.label,":"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(G.value)?G.value.length===1?String(G.value[0]):G.value.length<=2?G.value.join(", "):`${G.value.slice(0,2).join(", ")} +${G.value.length-2}`:String(G.value)})}),Array.isArray(G.value)&&G.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",G.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:G.value.map((ie,ce)=>e.jsx("div",{children:String(ie)},ce))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ie=>{var he;ie.stopPropagation();const ce=q.conditions.filter(Me=>Me.id!==G.id);if(ce.length>0){const Me={...q,conditions:ce};Q(Me)}else if(P(void 0),n==="metrics"){const Me={...t,parameters:{...t.parameters,filters:void 0}},is=[...((he=g.config)==null?void 0:he.metricColumns)||[]];is[a]=Me,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:is})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},G.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{M(null),k(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(hn,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(co,{aliasTemplate:$,onAliasTemplateChange:ee}),e.jsx(uo,{valueAliases:U,onValueAliasesChange:le})]})]}):null,{columns:vn=[]}=s.useColumns(),bn=(q==null?void 0:q.conditions)&&q.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:d,style:de,...i,...u,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Hs,{dataType:Se}),e.jsx(vs,{className:s.cn("w-[140px] flex-1 text-sm",bn&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Zs=q==null?void 0:q.conditions)==null?void 0:Zs.length)&&!I&&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-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:q.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:q.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),S(!I)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${I?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ie=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ie),l(ie)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),re()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),I&&e.jsxs("div",{className:"space-y-3",children:[Ae(),me(),c==="kpi"&&Ws(),fn(),gn(),jn(),yn()]})]}),O&&e.jsx(ho,{open:O,onOpenChange:G=>{k(G),G||M(null)},availableFields:vn,existingFilters:q,editingCondition:E,onSave:G=>{var ie;if(G)Q(G);else if(P(void 0),n==="metrics"){const ce={...t,parameters:{...t.parameters,filters:void 0}},he=[...((ie=g.config)==null?void 0:ie.metricColumns)||[]];he[a]=ce,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:he})}M(null)}})]})}function fo({concept:t}){const n=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$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:n()})]})})}function us({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),d=s.useEditorStore(j=>j.card),m=s.useEditorStore(j=>j.card.type),h=n.length>0,f=(j,x)=>{var p;!((p=d.config)!=null&&p.sortByColumns)||d.config.sortByColumns.findIndex(N=>N.id===j)===-1||u(d.id,j,{direction:x})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),g&&e.jsx(fo,{concept:t})]}),e.jsx("div",{ref:i,className:`rounded-lg border-2 border-dashed p-1 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"min-h-[60px] border-muted-foreground/20 bg-background"}`,children:n.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:n.map(j=>j.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((j,x)=>{const p=j.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(po,{field:j,zone:t,index:x,sortDirection:p,onSortDirectionChange:N=>f(j.id,N),hasPivotColumns:o,cardType:m})})},j.id)})})})})]})}const ft=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],go=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Is({value:t,onChange:n,label:a}){const[r,l]=A.useState(!1),[o,c]=A.useState(!1),i=()=>{const u=ft.find(d=>d.value===t);return u?u.color:t.startsWith("#")?t:ft[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:go.map(u=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===u?"border-gray-900":"border-transparent"),style:{backgroundColor:u},onClick:()=>{n(u),l(!1)},children:e.jsx("span",{className:"sr-only",children:u})},u))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(ln,{color:i(),onColorChange:u=>{n(u),c(!1)},onClose:()=>c(!1)})})]})]})}const ms={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
|
|
361
|
+
Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function jo(){var i,u,d,m,h,f,g,j,x,y;const t=s.useEditorStore(p=>p.card),{setCardPreferences:n}=s.useEditorActions(),a=((i=t.config)==null?void 0:i.metricColumns)||[],r=((u=t.config)==null?void 0:u.groupByColumns)||[];if(!(t.type==="kpi"&&(a.length>=2&&r.length===0||a.length>=1&&r.length>0)))return null;const o=((m=(d=t.preferences)==null?void 0:d.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=p=>{var T;const N={...t.preferences,kpiVisualOptions:{...(T=t.preferences)==null?void 0:T.kpiVisualOptions,metricComparison:{...o,...p}}};n(N)};return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:p=>c({enabled:p,...p&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:p=>c({calculationType:p}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(ms).map(([p,N])=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:N.label},p))})]}),(()=>{var N,T,R;const p=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(N=ms[p])==null?void 0:N.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(T=ms[p])==null?void 0:T.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(R=ms[p])==null?void 0:R.example]})]})})()]}),e.jsx(Ys,{formatOptions:o.formatOptions||{},onFormatOptionsChange:p=>c({formatOptions:p}),showTitle:!0,title:"COMPARISON FORMAT"}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"left",onValueChange:p=>c({position:p}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:p=>c({showArrow:p})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:p=>c({showColor:p})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Is,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:p=>c({colorConfig:{...o.colorConfig,increase:p}}),label:"Primary > Secondary"}),e.jsx(Is,{value:((f=o.colorConfig)==null?void 0:f.decrease)||"red",onChange:p=>c({colorConfig:{...o.colorConfig,decrease:p}}),label:"Primary < Secondary"}),e.jsx(Is,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:p=>c({colorConfig:{...o.colorConfig,noChange:p}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:p=>c({conditionalLabel:p})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((j=o.conditionalLabels)==null?void 0:j.increase)??"Increase",onChange:p=>c({conditionalLabels:{...o.conditionalLabels,increase:p.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((x=o.conditionalLabels)==null?void 0:x.decrease)??"Decrease",onChange:p=>c({conditionalLabels:{...o.conditionalLabels,decrease:p.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((y=o.conditionalLabels)==null?void 0:y.noChange)??"No change",onChange:p=>c({conditionalLabels:{...o.conditionalLabels,noChange:p.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:p=>c({labelName:p.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function yo(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var u;const i={...t.preferences,kpiVisualOptions:{...(u=t.preferences)==null?void 0:u.kpiVisualOptions,formatOptions:c}};n(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Te,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(Ys,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function vo({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const l=s.useEditorStore(j=>{var x;return((x=j.card.customCardPreferences)==null?void 0:x.url)&&j.card.type==="custom"}),o=s.useEditorStore(j=>j.card),c=o==null?void 0:o.type,i=t.length>0||a.length>0,u=c!=="kpi",d=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel"].includes(c),h=u&&!m,f=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(us,{zone:"groupBy",fields:t,label:f().label,placeholder:f().placeholder}),h&&e.jsx(us,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(us,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),d&&e.jsx(us,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(yo,{}),e.jsx(jo,{}),e.jsx(on,{}),e.jsx(cn,{}),e.jsx(dn,{}),e.jsx(un,{})]})})]})]})}function bo({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(h=>h.showAIDialog),i=a.length>0||r.length>0||l.length>0,{setShowAIDialog:u}=s.useEditorActions(),d=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(d);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(ro,{selectedChart:t,onChartChange:n}),e.jsx(io,{selectedChart:t,onChartChange:n})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||m}),children:e.jsx(js,{})}),!c&&e.jsxs(s.Button,{onClick:()=>u(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(s.Sparkles,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(vo,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function No({initialFilters:t,availableFields:n}={}){const[a,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(b=>b.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=n||l||[],u={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},d=b=>{const w=v=>{if(v.id===b){const D=i[0]||u,C=s.getDataType(D.dataType)==="date";return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:D,operator:C?"between":"=",value:C?[]:""}]}}return{...v,groups:v.groups.map(w)}};r(w(a))},m=b=>{const w=v=>{if(v.id===b){const D=i[0]||u,C=s.getDataType(D.dataType)==="date";return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:C?"between":"=",value:C?[]:""}],groups:[]}]}}return{...v,groups:v.groups.map(w)}};r(w(a))},h=(b,w)=>{const v=D=>D.id===b?{...D,conditions:D.conditions.filter(C=>C.id!==w)}:{...D,groups:D.groups.map(v)};r(v(a))},f=(b,w)=>{const v=D=>D.id===b?{...D,groups:D.groups.filter(C=>C.id!==w)}:{...D,groups:D.groups.map(v)};r(v(a))},g=(b,w,v,D)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const C=I=>I.id===b?{...I,conditions:I.conditions.map(S=>S.id===w?{...S,[v]:D}:S)}:{...I,groups:I.groups.map(C)};r(C(a))},j=(b,w,v)=>{const D=C=>C.id===b?{...C,conditions:C.conditions.map(I=>I.id===w?{...I,...v}:I)}:{...C,groups:C.groups.map(D)};r(D(a))},x=(b,w)=>{const v=D=>D.id===b?{...D,logicalOperator:w}:{...D,groups:D.groups.map(v)};r(v(a))},y=(b,w)=>{const v=D=>D.id===b?{...D,negate:w}:{...D,groups:D.groups.map(v)};r(v(a))},p=(b,w,v)=>{const D=C=>C.id===b?{...C,conditions:s.arrayMove(C.conditions,w,v)}:{...C,groups:C.groups.map(D)};r(D(a))},N=(b,w,v)=>{const D=C=>C.id===b?{...C,groups:s.arrayMove(C.groups,w,v)}:{...C,groups:C.groups.map(D)};r(D(a))},T=b=>{if(!b||b.conditions.length===0&&b.groups.length===0)return"-- No filters defined";const w=D=>{let C="";typeof D.field=="object"?C=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:C=String(D.field);const I=D.operator;let S=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof S=="string"?S=`'${S}'`:Array.isArray(S)&&(S=`'${S.join(", ")}'`);else if(D.field.dataType==="date"||D.field.dataType==="datetime"||D.field.dataType==="timestamp")if(D.operator==="between"&&Array.isArray(S)&&S.length===2){const O=S[0]?`'${S[0]}'`:"NULL",k=S[1]?`'${S[1]}'`:"NULL";return`${C} BETWEEN ${O} AND ${k}`}else if((D.operator==="in"||D.operator==="not in")&&Array.isArray(S)){const O=S.map(k=>k?`'${k}'`:"NULL").join(", ");return`${C} ${I} (${O})`}else typeof S=="string"||S instanceof Date?S=`'${S}'`:Array.isArray(S)&&S.length>0&&(S=`'${S[0]}'`);else if(["in","not in"].includes(D.operator)){let O=[];Array.isArray(S)?O=S.map(k=>typeof k=="string"?`'${k}'`:String(k)):typeof S=="string"?O=S.split(",").map(k=>{const E=k.trim();return D.field.dataType==="string"?`'${E}'`:E}):typeof S=="number"&&(O=[String(S)]),S=`(${O.join(", ")})`}switch(I){case"contains":return typeof S=="string"?`${C} LIKE '%${S.replace(/'/g,"")}'`:`${C} LIKE '%${String(S)}'`;case"startsWith":return typeof S=="string"?`${C} LIKE '${S.replace(/'/g,"")}%'`:`${C} LIKE '${String(S)}%'`;case"endsWith":return typeof S=="string"?`${C} LIKE '%${S.replace(/'/g,"")}'`:`${C} LIKE '%${String(S)}'`;case"isNull":return`${C} IS NULL`;case"isNotNull":return`${C} IS NOT NULL`;default:return`${C} ${I} ${S}`}},v=D=>{const C=D.conditions.map(w),I=D.groups.map(E=>v(E)),S=[...C,...I].filter(Boolean);if(S.length===0)return"";const O=S.join(` ${D.logicalOperator} `),k=S.length>1?`(${O})`:O;return D.negate?`NOT ${k}`:k};return v(b)},R=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:d,addGroup:m,removeCondition:h,removeGroup:f,updateCondition:g,updateConditionFields:j,updateGroupOperator:x,updateGroupNegate:y,reorderConditions:p,reorderGroups:N,generateSQLPreview:T,hasAnyFilters:R}}function Co({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const So=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(s.File,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},wo=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function Do({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[o,c]=A.useState(!1),i=A.useMemo(()=>{const u={};return a.forEach(d=>{const m=wo(d);u[m]||(u[m]={}),u[m][d.entityId]||(u[m][d.entityId]=[]),u[m][d.entityId].push(d)}),u},[a]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Co,{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(([u,d])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),u]}),children:Object.entries(d).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[So(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((f,g)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{n(f),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)===f.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:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+g))]},`${u}-${m}`))},u))})]})})]})}function Qs(t){var j;const n=s.useEditorStore(x=>x.card),{authToken:a}=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"},u={joinPlan:l,groupByColumns:[o],metricColumns:[c],sortByColumns:[i]},d=((j=n.dataSource)==null?void 0:j.connectionId)||n.connectionId,{data:m,isPending:h,error:f}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(a==null?void 0:a.accessToken)||"",{connection_id:d,cardConfig:u,cardDataSource:n.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!d,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(x=>({label:x.value||"BLANK",value:x.value||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:h,error:f}}function ko({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[o,c]=pe.useState(!1),{filterValues:i}=Qs(t),u=m=>{a(n.filter(h=>h!==m))},d=m=>{n.includes(m)?a(n.filter(h=>h!==m)):a([...n,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(m=>{const h=i.find(f=>f.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:f=>{f.key==="Enter"&&u(m)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),u(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>d(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function To({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=Qs(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:o.map((u,d)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:u.value,children:u.label},u.value+d))})]})}function Eo({value:t,operator:n,onChange:a,className:r}){var u;const{tokenProps:l}=s.useSemaphorContext(),o=(u=l==null?void 0:l.params)==null?void 0:u.timeZone,c=A.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const d=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(d&&m)return{from:d,to:m}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const d=new Date(t);if(!isNaN(d.getTime()))return{from:d,to:d}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const d=new Date(t);if(!isNaN(d.getTime()))return{from:d,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const d=new Date(t);if(!isNaN(d.getTime()))return{from:void 0,to:d}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const d=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):d;if(!isNaN(d.getTime()))return{from:d,to:m}}}},[t,n]),i=d=>{if(!d){a(void 0);return}if(d.from&&d.to)a([d.from.toISOString(),d.to.toISOString()]);else if(d.from){const m=new Date(d.from);m.setHours(23,59,59,999),a([d.from.toISOString(),m.toISOString()])}else if(d.to){const m=new Date(d.to);m.setHours(0,0,0,0),a([m.toISOString(),d.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Io=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Ao=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Mo=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Lo=["=","!=","isNull","isNotNull"],Ro=["between","isNull","isNotNull"],Oo={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null"};function gt(t){return Oo[t]||s.titleCase(t)}function Fo(t){switch(t){case"string":return Ao;case"number":return Mo;case"boolean":return Lo;case"date":return Ro;default:return Io}}function pn({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:u}){const{attributes:d,listeners:m,setNodeRef:h,transform:f,transition:g,isDragging:j}=s.useSortable({id:t.id}),{isPending:x,error:y}=Qs(t.field),p={transform:s.CSS.Transform.toString(f),transition:g};return e.jsxs("div",{ref:h,style:p,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${j?"z-50 opacity-50":""}`,children:[e.jsx("div",{...d,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:N=>c(a,N),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(Do,{value:t.field,onValueChange:N=>{const T=N,R=s.getDataType(T.dataType)==="date";u(a,t.id,{field:T,value:"",operator:R?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:N=>{N==="in"||N==="not in"?u(a,t.id,{operator:N,value:[]}):N==="isNull"||N==="isNotNull"?u(a,t.id,{operator:N,value:null}):u(a,t.id,{operator:N,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?gt(t.operator):""})}),e.jsx(s.SelectContent,{children:Fo(s.getDataType(t.field.dataType)).map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N,children:gt(N)},N))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?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..."]}):y?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ko,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(N=>typeof N=="string")?t.value:[],onChange:N=>u(a,t.id,{value:N}),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:N=>u(a,t.id,{value:N.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(To,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:N=>u(a,t.id,{value:N}),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:N=>u(a,t.id,{value:N==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(Eo,{value:t.value,operator:t.operator,onChange:N=>u(a,t.id,{value:N}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:N=>l(a,t.id,"value",N.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Bo({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:u,onReorderConditions:d,onReorderGroups:m,onAddCondition:h,onAddGroup:f,availableFields:g,renderFilterGroup:j,updateConditionFields:x}){const{attributes:y,listeners:p,setNodeRef:N,transform:T,transition:R,isDragging:b}=s.useSortable({id:t.id}),w={transform:s.CSS.Transform.toString(T),transition:R},v=C=>{const{active:I,over:S}=C;if(S&&I.id!==S.id){const O=t.conditions.findIndex(E=>E.id===I.id),k=t.conditions.findIndex(E=>E.id===S.id);O!==-1&&k!==-1&&d(t.id,O,k)}},D=C=>{const{active:I,over:S}=C;if(S&&I.id!==S.id&&a){const O=t.groups.findIndex(E=>E.id===I.id),k=t.groups.findIndex(E=>E.id===S.id);O!==-1&&k!==-1&&m(a,O,k)}};return e.jsxs("div",{ref:N,style:w,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${b?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...y,...p,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:C=>r(t.id,C),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&o(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:v,children:e.jsx(s.SortableContext,{items:t.conditions.map(C=>C.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((C,I)=>e.jsx(pn,{condition:C,index:I,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:u,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:x},C.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:D,children:e.jsx(s.SortableContext,{items:t.groups.map(C=>C.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(C=>j(C,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Po({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:u,addGroup:d,removeCondition:m,removeGroup:h,updateCondition:f,updateConditionFields:g,updateGroupOperator:j,updateGroupNegate:x,reorderConditions:y,reorderGroups:p,generateSQLPreview:N,hasAnyFilters:T,setCurrentFilters:R}=No({initialFilters:t,availableFields:n}),b=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[w,v]=A.useState(!1),D=(S,O,k)=>{const E=M=>M.id===S?{...M,conditions:M.conditions.map(B=>B.id===O?{...B,field:k,dataType:k.dataType}:B)}:{...M,groups:M.groups.map(E)};R(E(o))},C=(S,O=0,k)=>O===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:b,collisionDetection:s.closestCenter,onDragEnd:E=>{const{active:M,over:B}=E;if(B&&M.id!==B.id){const L=S.conditions.findIndex(V=>V.id===M.id),F=S.conditions.findIndex(V=>V.id===B.id);L!==-1&&F!==-1&&y(S.id,L,F)}},children:e.jsx(s.SortableContext,{items:S.conditions.map(E=>E.id),strategy:s.verticalListSortingStrategy,children:S.conditions.map((E,M)=>e.jsx(pn,{condition:E,index:M,groupId:S.id,groupLogicalOperator:S.logicalOperator,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:g},E.id))})}),e.jsx(s.DndContext,{sensors:b,collisionDetection:s.closestCenter,onDragEnd:E=>{const{active:M,over:B}=E;if(B&&M.id!==B.id){const L=S.groups.findIndex(V=>V.id===M.id),F=S.groups.findIndex(V=>V.id===B.id);L!==-1&&F!==-1&&p(S.id,L,F)}},children:e.jsx(s.SortableContext,{items:S.groups.map(E=>E.id),strategy:s.verticalListSortingStrategy,children:S.groups.map(E=>C(E,O+1,S.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>u(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>d(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},S.id):e.jsx(Bo,{group:S,depth:O,parentGroupId:k,onUpdateGroupOperator:j,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onReorderConditions:y,onReorderGroups:p,onAddCondition:u,onAddGroup:d,availableFields:c,renderFilterGroup:C,updateConditionFields:g},S.id),I=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):C(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:w,onCheckedChange:S=>v(!!S)}),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)"})]})}),T&&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:N(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),I>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(T?o:null),children:"Apply Filters"})]})]})}function zo({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=d=>{a(t,d),c(!1)},u=()=>{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:d=>{d.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(Po,{filters:n,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:u})]})]})}function Vo({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[l,o]=A.useState(null),c=s.useEditorStore(j=>j.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,u=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],d=A.useCallback(j=>j.startsWith("card-")?null:j.startsWith("source-")||n.find(x=>x.id===j)?"source":a("groupBy").find(x=>x.id===j)?"groupBy":a("metrics").find(x=>x.id===j)?"metrics":a("pivotBy").find(x=>x.id===j)?"pivotBy":a("sortBy").find(x=>x.id===j)?"sortBy":null,[n,a]),m=A.useCallback(j=>{o(j.active.id)},[]),h=A.useCallback(j=>{const{active:x,over:y}=j;if(!y||!t){o(null);return}const p=x.id,N=y.id,T=d(p),R=d(N)||N;if(R==="sortBy"){if(T==="source"){const b=n.find(v=>v.id===p);if(!b){o(null);return}if(!(a("groupBy").some(v=>v.name===b.name&&v.qualifiedEntityName===b.qualifiedEntityName)||a("metrics").some(v=>v.name===b.name&&v.qualifiedEntityName===b.qualifiedEntityName))){o(null);return}}else if(T==="pivotBy"){o(null);return}else if(T!=="groupBy"&&T!=="metrics"&&T!=="sortBy"){o(null);return}}if(T==="source"&&R==="sortBy"){const b=[...n].find(D=>D.id===p);if(!b){o(null);return}const w=a("sortBy");if(s.fieldAlreadyExists(b,w)){o(null);return}const v=s.getNewField(b,"sortBy",w);o(null),r("sortBy",[...w,v]);return}if(T==="source"&&R!=="source"&&R!=="sortBy"){const b=[...n].find(C=>C.id===p);if(!b){o(null);return}const w=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(w.length>0){const C=w[0].qualifiedEntityName;if(!C){o(null);return}if(C!==b.qualifiedEntityName&&b.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(C,b.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const v=a(R);if(s.fieldAlreadyExists(b,v)){o(null);return}const D=s.getNewField(b,R,v);o(null),r(R,[...v,D]);return}if(T&&R&&T!=="source"&&R!=="source"&&T!==R){const b=a(T),w=a(R),v=b.find(I=>I.id===p);if(!v){o(null);return}const D=s.getNewField(v,R,w);if(o(null),R==="sortBy"){s.fieldAlreadyExists(v,w)||r(R,[...w,D]);return}const C=b.filter(I=>I.id!==p);r(T,C),r(R,[...w,D]);return}if(T&&R&&T===R&&T!=="source"){const b=a(T),w=b.findIndex(D=>D.id===p),v=b.findIndex(D=>D.id===N);if(w!==v){const D=s.arrayMove(b,w,v);r(T,D)}}o(null)},[t,n,a,r,d,i]),f=l?u.find(j=>j.id===l):null;return{activeId:l,activeField:f,handleDragStart:m,handleDragEnd:h}}function _o({dashboardFilterCount:t=0,cardFilterCount:n=0,clickFilterCount:a=0,onClick:r,className:l,showIcon:o=!0}){const c=t+n+a,i=c>0,u=t>0,d=n>0,m=a>0,h=e.jsxs(e.Fragment,{children:[o&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),f=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",l),children:h});return i?e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:f}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"p-2 text-xs",children:e.jsxs("div",{className:"space-y-1.5",children:[u&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-purple-500"}),e.jsxs("span",{children:[t," Dashboard filter",t!==1?"s":""]})]}),d&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),e.jsxs("span",{children:[n," Card filter",n!==1?"s":""]})]}),m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-gray-500"}),e.jsxs("span",{children:[a," Click filter",a!==1?"s":""]})]})]})})]})}):f}function Uo({onAdvancedToggle:t,onDebugToggle:n,onAccept:a}){const{currentUser:r}=Ie();r==null||r.role;const[l,o]=A.useState(!1),c=s.useEditorStore(p=>p.isDevMode),i=s.useEditorStore(p=>p.card),u=s.useEditorStore(p=>p.card.dataSource);s.isExplorerCard(i);const{config:d}=A.useContext(s.SemaphorContext).tokenProps,m=(d==null?void 0:d.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),f=s.useEditorStore(p=>p.showAIDialog),g=s.useEditorStore(p=>p.frame),j=s.useManagementStore(p=>p.selectedVisual),x=(j==null?void 0:j.id)===(g==null?void 0:g.id),{setShowAIDialog:y}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",f&&"justify-end",!m&&"justify-end"),children:[m&&t&&!f&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:c,onCheckedChange:()=>h(!c),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[(r==null?void 0:r.type)!=="tenant"&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 p-0",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>{o(!0)},children:[e.jsx(s.Database,{className:"mr-2 h-4 w-4"}),"Set Data Context"]})})]}),e.jsx($s,{}),a&&!x&&e.jsx(Us,{variant:"default"}),x&&e.jsx(Lr,{}),n&&s.isDevEnv]}),l&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(u==null?void 0:u.selectedEntities)||[],open:l,onOpenChange:o,dataSource:u||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function $o({activeView:t,onViewChange:n}){const a=s.useEditorStore(l=>l.card),{errorMessage:r}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:l=>n(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),a.type!=="kpi"&&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":"Info"})]})})}const qo=[{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 Yo(){var u,d;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=A.useState(!1),[l,o]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((d=(u=t.config)==null?void 0:u.rowLimit)==null?void 0:d.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:qo.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function Go({isOpen:t,onClose:n}){const a=Lt(n,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:u}=s.useCustomVisual(r),d=A.useMemo(()=>!r||r.trim()===""?null:u("Chart Settings"),[u,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:d&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(d,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function Ko({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:u,activeCard:d,columns:m,columnsLoading:h,columnsError:f}){var J;const g=s.useEditorStore(X=>X.card),j=s.useDashboardStore(X=>X.filterValues),x=(j==null?void 0:j.length)||0,{updateCardConfig:y,setCard:p,updateCardInFrame:N,setCardId:T}=s.useEditorActions(),{updateCardId:R}=s.useDashboardActions(),[b,w]=A.useState(null),v=s.useEditorStore(X=>X.showAIDialog),[D,C]=A.useState(!1),{isConsoleMode:I}=s.useDashboardPreferences(),S=s.useEditorStore(X=>{var K;return((K=X.card.customCardPreferences)==null?void 0:K.url)&&X.card.type==="custom"}),{data:O,errorMessage:k,isLoading:E,isFetching:M,pagination:B}=s.useDashboardCardQuery(d),L=(X,K)=>{const $={...d,paginationConfig:{page:X+1,pageSize:K}};p($),N($)};function F(){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(j||{},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(d.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",m.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":f?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const V=X=>{if(!g.config)return;if(!X.length){y(g.id,{...g.config,sortByColumns:[]});return}const K=g.config,$=X.map(({id:Y,desc:U})=>{var W,te;const Z=(W=K.metricColumns)==null?void 0:W.find(_=>_.label===Y),q=(te=K.groupByColumns)==null?void 0:te.find(_=>_.label===Y),P=Z||q;return P?{id:s.getFieldId("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:U?"desc":"asc"}:null}).filter(Y=>Y!==null);y(g.id,{...K,sortByColumns:$})},z=A.useMemo(()=>{var X,K;return(K=(X=g.config)==null?void 0:X.sortByColumns)==null?void 0:K.map($=>({id:$.label,desc:$.direction==="desc"}))},[(J=g.config)==null?void 0:J.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(Uo,{showDebug:a,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:u}),a&&F(),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"&&v&&e.jsx(Zt,{variant:"outline"}),e.jsx($o,{activeView:t,onViewChange:n}),i&&e.jsx(_o,{dashboardFilterCount:x,cardFilterCount:u,onClick:i,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(Yo,{})}),v&&e.jsx(js,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(en,{})})]}),!D&&S&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>C(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(sn,{})}),t==="table"&&(O==null?void 0:O.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:d,data:(O==null?void 0:O.records)||[],paginationMetadata:B,onPaginationChange:L,isLoading:E||M,onSortChange:V,sortState:z})}),t==="sql"&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[I&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:g.id,onSave:X=>{const K=s.sanitizeCardId(X);if(!K){w("Card ID cannot be empty");return}const $=R(g.id,K);if($.success){T(K);const Y={...g,id:K};p(Y),N(Y),w(null),s.ue.success("Card ID updated successfully")}else w($.error||"Failed to update Card ID"),s.ue.error($.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:g.id,className:"h-5 w-5"})]}),b&&e.jsx("p",{className:"text-xs text-destructive",children:b})]}),(O==null?void 0:O.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(Gt,{sql:O==null?void 0:O.sql,error:k})]})})]}),e.jsx(Go,{isOpen:D,onClose:()=>C(!1)})]})]})}function Ho({activeField:t}){const[n,a]=A.useState(!0);return A.useEffect(()=>{t&&a(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Hs,{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 Qo=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const n=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},a=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function Wo(){var K,$;const[t,n]=A.useState("chart"),[a,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),u=s.useEditorStore(Y=>Y.showAIDialog),d=s.useDashboardStore(Y=>Y.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(Y=>Y.card.type);A.useEffect(()=>Qo(),[]);const f=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},j=()=>{console.log("Advanced mode toggled")},x=()=>{o(!0)},y=Y=>{m(Y)},p=s.useEditorStore(Y=>Y.frame),N=s.useEditorStore(Y=>Y.card);s.useEditorStore(Y=>Y.activeTabCardId),s.useEditorStore(Y=>Y.actions.getAvailableFields);const{addCard:T,removeCard:R,updateCard:b,setActiveCard:w,updateFilters:v}=s.useEditorActions(),{columns:D=[],isLoading:C,error:I}=s.useColumns(),S=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=N,{getFieldsForContainer:k,setFieldsForContainer:E}=Ks(O),{activeField:M,handleDragStart:B,handleDragEnd:L}=Vo({activeCardId:p.activeCardId,sourceFields:D,getFieldsForContainer:k,setFieldsForContainer:E}),F=(Y,U)=>{U&&v(Y,U)},V=Y=>{var U;b(Y,{config:{...(U=p.cards.find(Z=>Z.id===Y))==null?void 0:U.config,filters:void 0}})},z=D,J=Y=>{if(!Y)return 0;let U=Y.conditions.length;return Y.groups.forEach(Z=>{U+=J(Z)}),U},X=J(((K=O==null?void 0:O.config)==null?void 0:K.filters)||null);return e.jsxs(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragStart:B,onDragEnd:L,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(to,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!u&&e.jsx(bo,{selectedChart:h,onChartChange:y,groupByFields:k("groupBy"),pivotByFields:k("pivotBy"),metricsFields:k("metrics"),sortByFields:k("sortBy")}),e.jsx(Ko,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onAccept:f,onClear:g,onAdvancedToggle:j,onFiltersClick:x,filterCount:X,activeCard:O,dataSourceState:N.dataSource||s.EMPTY_DATA_SOURCE,columns:D,columnsLoading:C,columnsError:I,getFieldsForContainer:k,cards:p.cards,activeCardId:p.activeCardId,addCard:T,setActiveCard:w})]}),!c&&d&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),O&&e.jsx(zo,{cardId:O.id,filters:(($=O.config)==null?void 0:$.filters)||null,onFiltersChange:F,onClearFilters:V,availableFields:z,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Ho,{activeField:M||null})})]})}function Jo({authToken:t,onSave:n,onClose:a}){const r=A.useRef(null),l=s.useEditorStore(N=>N.showAIDialog),o=s.useEditorStore(N=>N.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:u,setOnClose:d}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:f,handleDragCancel:g,sensors:j}=Dr();A.useEffect(()=>{n&&u(n),a&&d(a)},[n,u,a,d]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var N,T;l?((N=r.current)==null||N.resize(40),i(!0)):(i(!1),(T=r.current)==null||T.resize(0))},[l,i]);function x(N){N<1?i(!1):l||i(!0)}function y(){return e.jsxs(e.Fragment,{children:[e.jsx(qt,{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(Ul,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(mt,{})})]})]})}function p(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Wo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(mt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:j,onDragStart:f,onDragEnd:h,onDragOver:m,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:y()})}):p()})}function Xo(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(c=>c.actions),a=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),n(!1))}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(Jo,{onSave:l,onClose:o})})}function Zo({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(Te,{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(Ue,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Ln,{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 ei(){const t=s.useEditorStore(o=>o.selectedDatabaseName),n=s.useEditorStore(o=>o.selectedTableName),a=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=qs();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(o.column_name)&&i.table===n&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zo,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function si({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ye,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Te,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Ue,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Qe,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(es,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(as,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ye,{className:"h-3 w-3"})})}function ti(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),l=s.useDashboardStore(p=>p.dashboard.filters)||[],{assignFilter:o}=qs(),c=s.useEditorStore(p=>p.card.dataSource),{columns:i=[],isLoading:u,error:d}=s.useColumns(),m=i.filter(p=>p.name.toLowerCase().includes(t.toLowerCase())||p.dataType.toLowerCase().includes(t.toLowerCase())||p.label&&p.label.toLowerCase().includes(t.toLowerCase())),h=p=>{const N=s.getDataType(p.dataType);return N==="number"?"metrics":(["date","string","boolean"].includes(N),"dimensions")},f=a==="all"?m:m.filter(p=>h(p)===a),g=m.filter(p=>h(p)==="dimensions").length,j=m.filter(p=>h(p)==="metrics").length,x=p=>{const N={column_name:p.name,data_type:p.dataType,label:p.label,description:p.description};o(N,"dashboard",p)};if(u)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(d)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const y=m.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:p=>n(p.target.value)})]}),y&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:p=>r(p),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[f.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),f.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),f.map(p=>{const N=l==null?void 0:l.some(T=>{var R;return T.title===p.name||((R=T.column)==null?void 0:R.includes(p.name))});return e.jsx("div",{onClick:()=>x(p),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":N}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(si,{dataType:p.dataType}),e.jsx("span",{children:p.label||p.name})]})},p.id)})]})]})}function ni(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),n=s.useCurrentActiveCard(),a=n&&((r=n.dataSource)==null?void 0:r.selectedEntities)&&n.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:a?e.jsx(ti,{}):e.jsx(qt,{type:"filter",ColumnsComponent:()=>e.jsx(ei,{})})})]})}function ai(){const t=s.useDashboardStore(r=>r.dashboard.filters),n=s.useDashboardStore(r=>r.theme),a=t==null?void 0:t.filter(r=>r.hide);return a!=null&&a.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":n==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":n==="dark"}),children:a==null?void 0:a.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function ri(){const t=s.useDashboardStore(r=>r.showFilters),n=s.useDashboardStore(r=>r.isVisualEditing),a=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":n,"flex grow overflow-auto":!n}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[a&&e.jsx(ai,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(ni,{})})]})}function li(){const t=s.useDashboardStore(l=>l.dashboard),n=s.useDashboardStore(l=>l.actions.setDashboard),a=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!a}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),n(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function oi({showControls:t=!1,showFooter:n=!0,...a}){if(typeof window>"u")return null;const{preferences:r}=a;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:r,children:[e.jsx(li,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(vr,{}),e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(Xo,{}),e.jsx(ri,{})]})]})]})})]})})}exports.DashboardPlus=oi;exports.ResourceManagementPanel=Ut;exports.ScheduleDashboard=wt;exports.SelectComponent=He;exports.cleanCard=St;exports.getDashbaordStateWithoutData=xs;
|