react-semaphor 0.0.546 → 0.0.548
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-EwYQa41k.js → dashboard-plus-CBTf0BDO.js} +2 -2
- package/dist/chunks/{dashboard-plus-oHcFO3g5.js → dashboard-plus-WlY0hLPo.js} +4 -4
- package/dist/chunks/{index-DdiZhL-n.js → index-CEWweOR2.js} +20 -14
- package/dist/chunks/{index-CGfbd0m4.js → index-DIFWt1VS.js} +2 -2
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/dist/types/main.d.ts +3 -0
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var nt=t=>{throw TypeError(t)};var hs=(t,a,n)=>a.has(t)||nt("Cannot "+n);var re=(t,a,n)=>(hs(t,a,"read from private field"),n?n.call(t):a.get(t)),Oe=(t,a,n)=>a.has(t)?nt("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,n),Be=(t,a,n,r)=>(hs(t,a,"write to private field"),r?r.call(t,n):a.set(t,n),n),Fe=(t,a,n)=>(hs(t,a,"access private method"),n);const e=require("react/jsx-runtime"),s=require("./index-
|
|
1
|
+
"use strict";var nt=t=>{throw TypeError(t)};var hs=(t,a,n)=>a.has(t)||nt("Cannot "+n);var re=(t,a,n)=>(hs(t,a,"read from private field"),n?n.call(t):a.get(t)),Oe=(t,a,n)=>a.has(t)?nt("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,n),Be=(t,a,n,r)=>(hs(t,a,"write to private field"),r?r.call(t,n):a.set(t,n),n),Fe=(t,a,n)=>(hs(t,a,"access private method"),n);const e=require("react/jsx-runtime"),s=require("./index-DIFWt1VS.js"),M=require("react");require("react-dom");function Mn(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const ue=Mn(M);var be,Ne,de,fe,ge,Ye,Ns,Nt,Ln=(Nt=class extends s.Subscribable{constructor(a,n){super();Oe(this,ge);Oe(this,be);Oe(this,Ne);Oe(this,de);Oe(this,fe);Be(this,be,a),this.setOptions(n),this.bindMethods(),Fe(this,ge,Ye).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(a){var r;const n=this.options;this.options=re(this,be).defaultMutationOptions(a),s.shallowEqualObjects(this.options,n)||re(this,be).getMutationCache().notify({type:"observerOptionsUpdated",mutation:re(this,de),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&s.hashKey(n.mutationKey)!==s.hashKey(this.options.mutationKey)?this.reset():((r=re(this,de))==null?void 0:r.state.status)==="pending"&&re(this,de).setOptions(this.options)}onUnsubscribe(){var a;this.hasListeners()||(a=re(this,de))==null||a.removeObserver(this)}onMutationUpdate(a){Fe(this,ge,Ye).call(this),Fe(this,ge,Ns).call(this,a)}getCurrentResult(){return re(this,Ne)}reset(){var a;(a=re(this,de))==null||a.removeObserver(this),Be(this,de,void 0),Fe(this,ge,Ye).call(this),Fe(this,ge,Ns).call(this)}mutate(a,n){var r;return Be(this,fe,n),(r=re(this,de))==null||r.removeObserver(this),Be(this,de,re(this,be).getMutationCache().build(re(this,be),this.options)),re(this,de).addObserver(this),re(this,de).execute(a)}},be=new WeakMap,Ne=new WeakMap,de=new WeakMap,fe=new WeakMap,ge=new WeakSet,Ye=function(){var n;const a=((n=re(this,de))==null?void 0:n.state)??s.getDefaultState();Be(this,Ne,{...a,isPending:a.status==="pending",isSuccess:a.status==="success",isError:a.status==="error",isIdle:a.status==="idle",mutate:this.mutate,reset:this.reset})},Ns=function(a){s.notifyManager.batch(()=>{var n,r,o,l,c,i,d,u;if(re(this,fe)&&this.hasListeners()){const m=re(this,Ne).variables,h=re(this,Ne).context;(a==null?void 0:a.type)==="success"?((r=(n=re(this,fe)).onSuccess)==null||r.call(n,a.data,m,h),(l=(o=re(this,fe)).onSettled)==null||l.call(o,a.data,null,m,h)):(a==null?void 0:a.type)==="error"&&((i=(c=re(this,fe)).onError)==null||i.call(c,a.error,m,h),(u=(d=re(this,fe)).onSettled)==null||u.call(d,void 0,a.error,m,h))}this.listeners.forEach(m=>{m(re(this,Ne))})})},Nt);function Ae(t,a){const n=s.useQueryClient(),[r]=ue.useState(()=>new Ln(n,t));ue.useEffect(()=>{r.setOptions(t)},[r,t]);const o=ue.useSyncExternalStore(ue.useCallback(c=>r.subscribe(s.notifyManager.batchCalls(c)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=ue.useCallback((c,i)=>{r.mutate(c,i).catch(s.noop)},[r]);if(o.error&&s.shouldThrowError(r.options.throwOnError,[o.error]))throw o.error;return{...o,mutate:l,mutateAsync:o.mutate}}/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -403,7 +403,7 @@
|
|
|
403
403
|
*
|
|
404
404
|
* This source code is licensed under the ISC license.
|
|
405
405
|
* See the LICENSE file in the root directory of this source tree.
|
|
406
|
-
*/const je=s.createLucideIcon("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function Bs(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var l;return{...o,cards:(l=o.cards)==null?void 0:l.map(c=>Lt(c))}})}})}}function Lt(t){return{...t,customCfg:Ea(t.customCfg),data:[]}}function Ea(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Ta(t,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:o,filterValues:n,operation:"create"})}async function Cs(t,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:l,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:l,shared:c,operation:"update"})}async function Ia(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Aa(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),o=s.useDashboardStore(x=>x.lenses),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=M.useState(!1),[u,m]=M.useState(!1),h=s.useDashboardStore(x=>x.dashboard),f=s.useDashboardStore(x=>x.filterValues),{authToken:p}=s.useSemaphorContext();async function g(){d(!0);const x=Bs(h),v=await Ta(t,x,f,p==null?void 0:p.accessToken);v&&(l([...o||[],v]),c(v.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:x=>{a(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:g,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Ma(){const[t,a]=M.useState(!1),n=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:o,setSelectedLensId:l}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(m){l(m)}async function d(m){if(await Ia(m,c==null?void 0:c.accessToken)){const f=n==null?void 0:n.filter(p=>p.id!==m);o(f||[]),l("original")}}async function u(m){const h=n==null?void 0:n.map(g=>g.id===m.id?{...g,isDefault:!m.isDefault}:{...g,isDefault:!1});o(h||[]);const f={...m,isDefault:!m.isDefault};await Cs(f,c==null?void 0:c.accessToken);const p=n==null?void 0:n.find(g=>g.isDefault);if(p&&p.id!==m.id){const g={...p,isDefault:!1};await Cs(g,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(oa,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(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(),u(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(),d(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 Rt(){var l;const t=s.useDashboardStore.getState().authToken,a=s.useDashboardStore.getState().theme,n=s.useDashboardStore.getState().filterValues,r=(l=s.useDashboardStore.getState().dashboard)==null?void 0:l.title,o=s.useDashboardStore.getState().selectedSheetId;return{authToken:t,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function Ot(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:l}=Rt();if(t)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",l||"");const i=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const m=(await(await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,h=document.createElement("a");h.href=m;const f=`${o}-${new Date().toISOString()}.pdf`;h.download=f,h.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function La({iconClassName:t}){const{authToken:a}=s.useSemaphorContext();s.useDashboardStore(o=>{var l;return(l=o.dashboard)==null?void 0:l.title}),s.useDashboardStore(o=>o.theme),s.useDashboardStore(o=>o.filterValues);const n=s.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await Ot()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function he({defaultValue:t,label:a,options:n,value:r,onValueChange:o,className:l,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:o,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",l),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const ct=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function Bt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:l,isDeleting:c}=Ra(),[i,d]=M.useState(""),[u,m]=M.useState(ct[0].value),[h,f]=M.useState("06:00"),[p,g]=M.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"email",children:"Email"}),e.jsx(s.Input,{id:"email",value:i,onChange:x=>d(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(s.Input,{id:"subject",placeholder:"Monthly Sales Report",value:p,onChange:x=>{g(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(he,{className:"col-span-2 h-8",label:"Select Frequency",options:ct,value:u,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 n({email:i,frequency:u,time:h,subject:p}),f("00:00"),d(""),g("")},className:"h-8 p-2",disabled:o==="loading"||!i,children:[o==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(kt,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:l})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),s.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(x=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[s.titleCase(x.frequency)," "]}),e.jsx(s.Label,{children:x.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(dt,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Wn,{className:"size-3.5"})}),e.jsx(dt,{tooltip:`${x.endUserEmail}`,children:e.jsx(pa,{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 dt=({children:t,tooltip:a})=>e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:t}),e.jsx(s.TooltipContent,{children:a})]})});function Ra(){const[t,a]=M.useState("idle"),[n,r]=M.useState(""),[o,l]=M.useState(null),c=s.useDashboardStore(C=>C.authToken),i=s.useDashboardStore(C=>C.dashboard.id),d=s.useDashboardStore(C=>C.dashboard.title),{endUserId:u}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),m="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:i,endUserId:u},{data:f,isLoading:p,isError:g,isFetching:x,refetch:v}=s.useQuery({queryKey:["subscriptions",i,u],queryFn:()=>s.getRequest(m,(c==null?void 0:c.accessToken)||"",h),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!u});async function j({email:C,subject:R,frequency:E,time:S}){const{authToken:N,...D}=Rt(),w=Intl.DateTimeFormat().resolvedOptions().timeZone,L={email:C,frequency:E,time:S,timezone:w,endUserId:u,endUserEmail:C,subject:R||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:D};a("loading");const k="https://semaphor.cloud/api/v1/subscriptions/create";try{const O=await s.postRequestRegular(k,(N==null?void 0:N.accessToken)||"",{...L});a("success"),r(""),v(),setTimeout(()=>{a("idle")},2e3)}catch(O){console.error(O),a("error"),r(O.message)}}async function b(C){const R="https://semaphor.cloud/api/v1/subscriptions/delete";l(C);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:C}),v(),setTimeout(()=>{l(null)},2e3)}catch(E){console.error(E),l(null),a("error"),r(E.message)}}return{data:f,isLoading:p,isFetching:x,isError:g,isDeleting:o,refetch:v,handleScheduleSubscription:j,handleDeleteSubscription:b,status:t,error:n}}function cs(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();let n=null;a&&(a.endUserId&&a.endUserEmail&&a.tenantId?n={id:a.endUserId,name:a.endUserEmail?String(a.displayName):"",email:a.endUserEmail?String(a.endUserEmail):"",type:"tenant",tenantId:a.tenantId}:a.orgUserId&&a.orgUserEmail&&(n={id:a.orgUserId,name:a.orgUserEmail?String(a.displayName):"",email:a.orgUserEmail?String(a.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:o,isError:l}=s.useQuery({queryKey:["userInfo",n==null?void 0:n.id],queryFn:async()=>{if(!(n!=null&&n.id))return;const i=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${n.id}`,{headers:{Authorization:`Bearer ${(t==null?void 0:t.accessToken)||""}`,"Content-Type":"application/json"}});if(!i.ok)throw new Error("Failed to fetch user info");return(await i.json()).user},enabled:!!(t!=null&&t.accessToken)&&!!(n!=null&&n.id)});return{currentUser:n?{...n,...r||{}}:null,isLoading:o,isError:l}}function Ft(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,a)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},a))})]})})}var ee=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(ee||{});const Oa=async(t,a,n,r,o,l)=>{const c={},i={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${i[a]}`,t,c)},Ba=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}`,t,n)},Fa=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!l.ok){const c=await l.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${l.status}`)}return l.json()},za=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!o.ok){const l=await o.json();throw new Error((l==null?void 0:l.error)||`HTTP error! status: ${o.status}`)}return o.json()},Pa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/duplicate`,t,{})},_a=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,t,r)},Va=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!l.ok){const c=await l.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${l.status}`)}return l.json()},Ua=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/shares`,t)},$a=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,t)};function qa(t){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(a==null?void 0:a.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(a!=null&&a.accessToken):!!(a!=null&&a.accessToken)})}function Ga(t,a,n,r,o){const{authToken:l}=s.useSemaphorContext();return s.useQuery({queryKey:[t,a,n,r,o],queryFn:()=>Oa((l==null?void 0:l.accessToken)||"",t),enabled:!!(l!=null&&l.accessToken)})}function Ha(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>Ba((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} created successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to create ${s.toTitleCase(t)}: ${o.message}`)}})}function Ka(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:({resourceId:r,data:o})=>Fa((a==null?void 0:a.accessToken)||"",t,r,o),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} updated successfully`)},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function Qa(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>za((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} deleted successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to delete ${s.toTitleCase(t)}: ${o.message}`)}})}function Wa(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:r=>Pa((a==null?void 0:a.accessToken)||"",t,r),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.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 Ja(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>_a((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to share resource: ${n.message}`)}})}function Ya(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>Va((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to remove resource shares: ${n.message}`)}})}function Xa(t,a){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,a],queryFn:()=>Ua((n==null?void 0:n.accessToken)||"",t,a),enabled:!!(n!=null&&n.accessToken)&&!!a})}function Za(t,a,n){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,a],queryFn:()=>$a((r==null?void 0:r.accessToken)||"",t,a),enabled:(n==null?void 0:n.enabled)!==void 0?n.enabled&&!!(r!=null&&r.accessToken)&&!!a:!!(r!=null&&r.accessToken)&&!!a})}function er(t,a){return Za(ee.VISUAL,t,a)}function zt(){const[t,a]=M.useState(new Map),n=M.useCallback((l,c)=>{a(i=>{const d=new Map(i),u=new Set(d.get(l)||[]);return c?u.add(c):(u.add("title"),u.add("description")),d.set(l,u),d})},[]),r=M.useCallback((l,c)=>{a(i=>{const d=new Map(i),u=new Set(d.get(l)||[]);return c?u.delete(c):u.clear(),u.size===0?d.delete(l):d.set(l,u),d})},[]),o=M.useCallback((l,c)=>{const i=t.get(l);return i?c?i.has(c):i.size>0:!1},[t]);return{startUpdating:n,stopUpdating:r,isUpdating:o}}function Pt(t,a,n){var h;const r=Ga(t),o=Ha(t,n),l=Ka(t),c=Qa(t,a),i=Wa(t),d=Ja(),u=Ya(),m={[ee.DASHBOARD]:"dashboards",[ee.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:o.mutate,updateResource:l.mutate,deleteResource:c.mutate,duplicateResource:i.mutate,shareResource:d.mutate,removeResourceShares:u.mutate,isCreating:o.isPending,isUpdating:l.isPending,isDeleting:c.isPending,isDuplicating:i.isPending,isSharing:d.isPending,isRemovingShares:u.isPending,isUpdatingShares:d.isPending,refetch:r.refetch}}function sr(t,a){return Pt(ee.DASHBOARD,t,a)}function tr(t,a){return Pt(ee.VISUAL,t,a)}function nr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:async({visualId:n,data:r})=>{const o=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t==null?void 0:t.accessToken}`},body:JSON.stringify(r)});if(!o.ok)throw new Error("Failed to update visual");return o.json()},onSuccess:()=>{s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["visuals"]})},onError:()=>{s.ue.error("Failed to update visual")}})}function ar({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onAddVisual:l,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var E;const{selectVisual:f}=s.useManagementActions(),p=s.useIsVisualSelected(t.id),[g,x]=M.useState(!1),[v,j]=M.useState(!1);M.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Et,{className:"h-3 w-3 text-purple-500"}):e.jsx(je,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),R=()=>{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",p&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:C()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>i==null?void 0:i(t.id,{title:S}),isEditable:t.ownership.isOwner&&p,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:b()})]}),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:S=>i==null?void 0:i(t.id,{description:S}),isEditable:t.ownership.isOwner&&p,isPending:o,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:S=>{S.stopPropagation(),l(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.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:S=>{S.stopPropagation(),l(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),c==null||c(t)},children:[e.jsx(ya,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),m(t)},children:[e.jsx(je,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),d(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{className:"h-3 w-3"}),e.jsx("span",{children:((E=t.ownership.createdBy)==null?void 0:E.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 _t({value:t,onChange:a,placeholder:n="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function es({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:o="",allowDropdown:l=!0}){var d;const c=((d=n.find(u=>u.value===t))==null?void 0:d.label)||t,i=n.filter(u=>u.value!==t);return l?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":""} ${o}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:l}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:u.value,disabled:r}),a(u.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${o}`,children:c})}function Vt({selectedUsers:t,selectedUserObjects:a,onRemove:n,onRoleChange:r,getRoleOptions:o}){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(l=>n(l.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.map(l=>{const c=t.find(d=>d.id===l.id),i=o(l.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[l.name,e.jsx(es,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(l.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>n(l.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},l.id)})}),e.jsx(s.Separator,{})]})}function Ut({usersToRemove:t,allUsers:a,onRemove:n}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>n(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function $t({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const o=r("tenant"),l=i=>{const d=a.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=o.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(je,{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:l(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>n(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function qt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,o=M.useRef(null);return M.useEffect(()=>{const l=c=>{const i=c.target;o.current&&o.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return n&&document.addEventListener(r,l),()=>{document.removeEventListener(r,l)}},[t,n,r]),o}function xe(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function rr(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Gt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function or(t,a,n){const r=Gt(t),o=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(o==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function ir({user:t}){return Gt(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 lr({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:o,handleUpdateAccess:l}){if(!(a!=null&&a.role))return null;const c=rr((r==null?void 0:r.type)||""),i=n.some(h=>h.id===t.id),d=n.find(h=>h.id===t.id),u=d?d.newRole:a==null?void 0:a.role,m=o(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(es,{currentRole:u,onRoleChange:h=>{l(t.id,a.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:xe(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function cr({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),a&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(qe,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function dr({isUserRemoving:t,isSelected:a,hasAccess:n,isRemoving:r,isSharing:o}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),a&&!n&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:o?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 ur({existingShares:t,allUsers:a,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((f,p)=>{var j,b;const g=((j=a.find(C=>C.id===f.orgUserId))==null?void 0:j.name)||"Unknown User",x=((b=a.find(C=>C.id===f.orgUserId))==null?void 0:b.type)||"",v=xe(f.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:g}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},p)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((f,p)=>{var j,b;const g=((j=a.find(C=>C.id===f.tenantUserId))==null?void 0:j.name)||"Unknown User",x=((b=a.find(C=>C.id===f.tenantUserId))==null?void 0:b.type)||"",v=xe(f.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:g}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},p)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((f,p)=>{const g=xe(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},p)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((f,p)=>{const g=xe(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},p)})})]}),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,p)=>{const g=xe(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},p)})})]}),!i.length&&!d.length&&!u.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var p,g;const m=((p=a.find(x=>x.id===d.tenantUserId))==null?void 0:p.name)||"Unknown User",h=((g=a.find(x=>x.id===d.tenantUserId))==null?void 0:g.type)||"",f=xe(d.role,n(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:f})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=xe(d.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const l=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:[l.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",l.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[l.slice(0,3).map((i,d)=>{var f,p;const u=((f=a.find(g=>g.id===i.tenantUserId))==null?void 0:f.name)||"Unknown User",m=((p=a.find(g=>g.id===i.tenantUserId))==null?void 0:p.type)||"",h=xe(i.role,n(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),l.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",l.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=xe(i.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!l.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function mr({isInitialLoading:t,searchQuery:a,availableUsers:n}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function hr({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:o,isSelected:l,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:f,handleUserRoleChange:p}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":l?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:o?!n:l,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{o?n?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(ir,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(es,{currentRole:a==null?void 0:a.role,onRoleChange:g=>f(t.id,a.role,g),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(lr,{user:t,userShare:a,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:f}),l&&!o&&e.jsx("div",{onClick:g=>g.stopPropagation(),children:e.jsx(es,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:g=>p(t.id,g),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(cr,{hasAccess:r,isUserRemoving:n,isSelected:l,hasAccessFromAPI:o}),e.jsx(dr,{isUserRemoving:n,isSelected:l,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Ht({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:o=[],currentUser:l,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),p=s.useShareSearchQuery(),g=s.useShareManagementActions(),x=c||(E=>{const S=m.some(D=>D.id===E),N=h.includes(E);S?g.removeSelectedUser(E):N?g.removeUserFromRemove(E):g.addSelectedUser({id:E,role:"VIEWER"})}),v=i||g.updateSelectedUserRole,j=d||g.addUserToRemove,b=u||((E,S,N)=>{g.addUserToUpdate({id:E,currentRole:S,newRole:N})}),C=o,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 (",(C??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(ur,{existingShares:t,allUsers:o,getRoleOptions:r,currentUser:l})})]})})]}),(C==null?void 0:C.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===C.length?g.setSelectedUsers([]):g.setSelectedUsers(C.map(E=>({id:E.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===C.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(mr,{isInitialLoading:a,isSearching:n,searchQuery:p,availableUsers:C||[]}),!a&&!n&&(C==null?void 0:C.length)>0&&C.map(E=>{const S=t?or(E,t,l):void 0,N=R.includes(E.id),D=!!S,w=D&&!N,L=m.some(A=>A.id===E.id),k=m.find(A=>A.id===E.id),O=r(E.type);return e.jsx(hr,{user:E,userShare:S,isUserRemoving:N,hasAccess:w,hasAccessFromAPI:D,isSelected:L,selectedUser:k,roleOptions:O,currentUser:l,usersToUpdate:f,handleUserToggle:x,handleRemoveAccess:j,handleUpdateAccess:b,handleUserRoleChange:v},E.id)})]})]})}function Kt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const o=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(l=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:l.value,id:l.value,className:"peer sr-only",disabled:l.disabled}),e.jsxs(s.Label,{htmlFor:l.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 ${l.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[l.icon||e.jsx(Se,{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:l.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l.description})]})]})]},l.value))}),!o&&r.some(l=>l.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 De=()=>[{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 xr({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:o=null,allUsersToRemove:l=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=De().filter(b=>b.value==="VIEWER"||b.value==="EDITOR"||b.value==="CONTRIBUTOR"),m=a.role!=="NONE"?a.role:"NONE",h=o?o.newRole:m,f=a.role!=="NONE"&&!l&&(!o||o.newRole===m),p=o!==null&&o.newRole!==m,g=l,x=m==="NONE"||!m,v=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(Ca,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},j=b=>{r(m,b)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",p&&!g&&!x?"border-orange-300 bg-orange-50":f?"border-green-300 bg-green-50":g||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(je,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="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"}),p&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(g||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:g||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:u.map(b=>e.jsxs(s.Button,{variant:h===b.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>j(b.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[v(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 Qt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:l,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=x=>x==="OWNER"?"CONTRIBUTOR":x,h=a?{role:u(a.role)}:{role:"NONE"},f=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,p=(x,v)=>{l(x,v)},g=()=>{c()};return e.jsx(xr,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:p,onRemoveAccess:g,allUsersToUpdate:f,allUsersToRemove:d})}const pr=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function fr(t={}){var r,o,l;const{authToken:a}=s.useSemaphorContext(),n=s.useQuery({queryKey:["unified-users",t],queryFn:()=>pr((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken),retry:(c,i)=>i instanceof Error&&i.message.includes("401")||i instanceof Error&&i.message.includes("403")?!1:c<2,retryDelay:c=>Math.min(1e3*2**c,3e4)});return{users:((r=n.data)==null?void 0:r.users)||[],userContext:(o=n.data)==null?void 0:o.userContext,total:((l=n.data)==null?void 0:l.total)||0,isLoading:n.isLoading,isError:n.isError,isFetching:n.isFetching,error:n.error,refetch:n.refetch}}function we(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=ee.DASHBOARD,userType:o,tenantId:l}=t,c=M.useMemo(()=>({search:a,active:!0,...o?{type:o}:{},...o==="tenant"&&l?{tenantId:l}:{}}),[a,o,l]),{users:i,isLoading:d,isError:u}=fr(c),m=Xa(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function gr({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var W,V;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),f=s.useShareSelectedUsers(),p=s.useShareUsersToRemove(),g=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),v=s.useShareOrgWideRole(),j=s.useShareManagementActions(),[b,C]=M.useState("specific_users"),R=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},E=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:N,isLoadingUsers:D}=we({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:R(),tenantId:E()});M.useEffect(()=>{j.setCurrentContext("org-tab"),j.setCurrentMode(b==="all_users"?"allOrgUsers":"specificOrgUsers")},[j,b]);const w=$=>{var U,H;const q=$;if(C(q),r==null||r(q),j.setCurrentContext("org-tab"),q==="specific_users")j.setCurrentMode("specificOrgUsers");else if(q==="all_users"){j.setCurrentMode("allOrgUsers");const Q=(H=(U=N==null?void 0:N.shares)==null?void 0:U.orgUsersOnly)==null?void 0:H[0];Q&&Q.role!==void 0&&j.setOrgWideRole(Q.role)}},L=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),k=S.filter($=>f.some(q=>q.id===$.id)),O=$=>{var Q,G;const q=f.some(Z=>Z.id===$),U=p.includes($),H=(G=(Q=N==null?void 0:N.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===$);q?j.removeSelectedUser($):U?j.removeUserFromRemove($):H||j.addSelectedUser({id:$,role:"VIEWER"})},A=($,q)=>{j.updateSelectedUserRole($,q)},I=$=>{j.addUserToRemove($),j.removeSelectedUser($)},y=$=>{j.removeUserFromRemove($)},T=$=>{j.removeUserFromUpdate($)},F=($,q)=>{j.setOrgWideRole(q)},z=()=>{j.setOrgWideRole((_==null?void 0:_.role)||"NONE")},_=(V=(W=N==null?void 0:N.shares)==null?void 0:W.orgUsersOnly)==null?void 0:V[0];M.useEffect(()=>{b==="all_users"&&_&&_.role!==void 0&&j.setOrgWideRole(_.role)},[b,_,j]);const P=D,Y=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(Kt,{shareType:b,onShareTypeChange:w,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(je,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),b==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(_t,{value:u,onChange:m}),e.jsx(Vt,{selectedUsers:f,selectedUserObjects:k,onRemove:O,onRoleChange:A,getRoleOptions:De}),e.jsx(Ut,{usersToRemove:p,allUsers:L,onRemove:y}),e.jsx($t,{usersToUpdate:g,allUsers:L,onRemove:T,getRoleOptions:De}),e.jsx(Ht,{existingShares:N,isInitialLoading:P,isSearching:Y,resource:t,onShare:()=>{},getRoleOptions:De,allUsers:L,currentUser:n,handleUserToggle:O,handleUserRoleChange:A,handleRemoveAccess:I,handleUpdateAccess:($,q,U)=>{j.addUserToUpdate({id:$,currentRole:q,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Qt,{currentUser:n,currentShare:_,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:F,onRemoveAccess:z,allUsersToUpdate:x==="allOrgUsers"&&v!==((_==null?void 0:_.role)||"NONE")?{currentRole:(_==null?void 0:_.role)||"NONE",newRole:v}:null,allUsersToRemove:x==="allOrgUsers"&&(_==null?void 0:_.role)===void 0})})]}):null}function ut({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var Q;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),g=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareSelectedTenant(),j=s.useShareManagementActions(),{data:b,isLoading:C}=qa({enabled:(n==null?void 0:n.type)==="organization"}),[R,E]=M.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),j.setCurrentMode("specificTenantUsers")):(j.setCurrentContext("tenant-tab"),j.setCurrentMode("allTenants"))},[j,n==null?void 0:n.type]);const S=G=>{var te,ae,se,oe;E(G);let Z;if(G==="specific_tenant_users"?Z="specific_users":G==="all_tenant_users"||G==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"&&(j.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&j.setSelectedTenant(n.tenantId))):(j.setCurrentContext("tenant-tab"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"?j.setCurrentMode("allTenantUsers"):G==="all_tenants"&&j.setCurrentMode("allTenants")),G==="all_tenant_users"){const K=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0];K&&K.role!==void 0&&j.setTenantWideRole(K.role)}else if(G==="all_tenants"){const K=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:oe[0];K&&K.role!==void 0&&j.setAllTenantsRole(K.role)}},N=G=>{j.setSelectedTenant(G)},{allUsers:D,existingShares:w,isLoadingUsers:L,isErrorLoadingUsers:k,isLoadingShares:O,isErrorLoadingShares:A}=we({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:v}),I=G=>{var se,oe;const Z=m.some(K=>K.id===G),te=h.includes(G),ae=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.specificTenantUsers)==null?void 0:oe.some(K=>K.tenantUserId===G);Z?j.removeSelectedUser(G):te?j.removeUserFromRemove(G):ae||j.addSelectedUser({id:G,role:"VIEWER"})},y=(G,Z)=>{j.updateSelectedUserRole(G,Z)},T=G=>{j.addUserToRemove(G),j.removeSelectedUser(G)},F=G=>{j.removeUserFromRemove(G)},z=G=>{j.removeUserFromUpdate(G)},_=(G,Z,te)=>{j.addUserToUpdate({id:G,currentRole:Z,newRole:te})},P=(G,Z)=>{R==="all_tenant_users"?j.setTenantWideRole(Z):R==="all_tenants"&&j.setAllTenantsRole(Z)},Y=()=>{R==="all_tenant_users"?j.setTenantWideRole("VIEWER"):R==="all_tenants"&&j.setAllTenantsRole("VIEWER")},V=(()=>{var G,Z,te,ae;return p==="allTenants"?(Z=(G=w==null?void 0:w.shares)==null?void 0:G.allTenantsOnly)==null?void 0:Z[0]:p==="allTenantUsers"?(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0]:null})();M.useEffect(()=>{var G,Z,te,ae;if(R==="all_tenant_users"){const se=(Z=(G=w==null?void 0:w.shares)==null?void 0:G.tenantWide)==null?void 0:Z[0];se&&se.role!==void 0&&j.setTenantWideRole(se.role)}else if(R==="all_tenants"){const se=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.allTenantsOnly)==null?void 0:ae[0];se&&se.role!==void 0&&j.setAllTenantsRole(se.role)}},[R,w,j]);const $=D.filter(G=>m.some(Z=>Z.id===G.id)),q=L||O,U=k||A,H=()=>(n==null?void 0:n.type)==="tenant"||R==="all_tenants"?!0:v&&(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&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Kt,{shareType:R,onShareTypeChange:S,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(je,{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(Se,{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(at,{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(Se,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.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:v||"",onValueChange:N,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(Q=b==null?void 0:b.tenants)==null?void 0:Q.map(G=>e.jsx(s.SelectItem,{value:G.id,children:G.name},G.id))})]})]}),H()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(_t,{value:i,onChange:u}),e.jsx(Vt,{selectedUsers:m,selectedUserObjects:$,onRemove:G=>I(G),onRoleChange:y,getRoleOptions:De}),e.jsx(Ut,{usersToRemove:h,allUsers:D,onRemove:F}),e.jsx($t,{usersToUpdate:f,allUsers:D,onRemove:z,getRoleOptions:De}),e.jsx(Ht,{existingShares:w,isInitialLoading:!!q,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:De,allUsers:D,currentUser:n,handleUserToggle:I,handleUserRoleChange:y,handleRemoveAccess:T,handleUpdateAccess:_})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Qt,{currentUser:n,currentShare:V,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:P,onRemoveAccess:Y,allUsersToUpdate:p==="allTenantUsers"&&((V==null?void 0:V.role)===void 0||g!==V.role)||p==="allTenants"&&((V==null?void 0:V.role)===void 0||x!==V.role)?{currentRole:(V==null?void 0:V.role)||"VIEWER",newRole:p==="allTenantUsers"?g:x}:null,allUsersToRemove:p==="allTenantUsers"&&(V==null?void 0:V.role)===void 0||p==="allTenants"&&(V==null?void 0:V.role)===void 0})}):null}):(n==null?void 0:n.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(at,{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 Wt=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),o=s.useShareUsersToUpdate(),l=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),u=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:l,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,a,n,r,o,l,c,i,d]),m=M.useMemo(()=>f=>s.validateShareData(f),[]),h=M.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||o.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!l)return!1}else if(a==="specificTenantUsers")return l?n.length>0||r.length>0||o.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||o.length>0:!0}return!1},[t,a,n,r,o,l]);return{buildShareData:u,validateShareData:m,isCurrentStateValid:h,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:l,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function mt({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:o,onShare:l,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const p=s.useShareSelectedTenant();s.useShareSelectedTab();const g=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareTenantWideRole(),{buildShareData:j,validateShareData:b,isCurrentStateValid:C}=Wt(),R=n||r||o,E=()=>{var L,k,O,A;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 I=m.length+h.length+f.length;return I===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${I} user${I!==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 ${I} user${I!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const I=d.role;return g===I?"Remove Access":"Update Access"}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0)return"Share with All Tenants";const y=I.role;return x===y?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const y=I.role;return v===y?"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 I=m.length+h.length+f.length;return I===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${I} user${I!==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 ${I} user${I!==1?"s":""}`}return"Share"},S=()=>R||!t||i==="all_tenant_users"&&!p||i==="specific_tenant_users"&&!p?!0:!C,N=()=>{const L=j();L&&b(L)&&l(L)},D=()=>{var L,k,O,A;if(i==="all_users")if(!d||d.role===void 0){const I=j();I&&b(I)&&l(I)}else{const I=d.role;if(g===I)u==null||u();else{const T=j();if(T&&b(T)){const F={...T,updateAccess:!0};l(F)}}}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&l(y)}else{const y=I.role;if(x===y)u==null||u();else{const F=j();if(F&&b(F)){const z={...F,updateAccess:!0};l(z)}}}}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&l(y)}else{const y=I.role;if(v===y)u==null||u();else{const F=j();if(F&&b(F)){const z={...F,updateAccess:!0};l(z)}}}}},w=()=>{var L,k,O,A;if(i==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return g===I?"destructive":"default"}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0)return"default";const y=I.role;return x===y?"destructive":"default"}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"default";const y=I.role;return v===y?"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:N,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(qe,{className:"mr-2 h-4 w-4"}),!R&&E()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:D,disabled:S(),variant:w(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(je,{className:"mr-2 h-4 w-4"}),!R&&E()]})]})}function jr({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:o,onClose:l,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:p,isCurrentStateValid:g}=Wt(),x=a||n||r,v=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const E=d.length+u.length+m.length;return E===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${E} user${E!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const E=i.role;return h===E?"Remove Access":"Update Access"}return"Share"},j=()=>x||!t?!0:!g,b=()=>{const E=f();E&&p(E)&&o(E)},C=()=>{if(!i||i.role==="NONE"){const E=f();E&&p(E)&&o(E)}else{const E=i.role;if(h===E){const N=f();if(N&&p(N)){const D={...N,removeAccess:!0};o(D)}}else{const N=f();if(N&&p(N)){const D={...N,updateAccess:!0};o(D)}}}},R=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:l,disabled:x,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.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(qe,{className:"mr-2 h-4 w-4"}),!x&&v()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:C,disabled:j(),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(qe,{className:"mr-2 h-4 w-4"}),!x&&v()]})]})}function Jt({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:o,onClose:l,onShare:c,onRemoveAccess:i}){var N,D,w,L;const{currentUser:d}=cs(),[u,m]=M.useState("specific_users"),[h,f]=M.useState("specific_users"),p=s.useShareManagementActions(),g=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:v}=we({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:j}=we({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),b=(D=(N=v==null?void 0:v.shares)==null?void 0:N.tenantWide)==null?void 0:D[0],C=(L=(w=j==null?void 0:j.shares)==null?void 0:w.orgUsersOnly)==null?void 0:L[0],R=()=>{if(g==="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"}},E=M.useCallback(()=>{p.resetShareState(),l()},[p,l]),S=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:E,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(qe,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:S?"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."})]}),S?e.jsxs(s.Tabs,{value:g,onValueChange:k=>{const O=k;p.setSelectedTab(O),p.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(gr,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:f,isSharing:n,isUpdating:o,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(ut,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:k=>m(k),isSharing:n,isUpdating:o,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(ut,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:k=>m(k),isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?g==="org"?e.jsx(mt,{resource:t,existingShares:j,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:h,currentAllUsersShare:C,onRemoveAccess:i}):e.jsx(mt,{resource:t,existingShares:v,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:R(),currentAllUsersShare:b,onRemoveAccess:i}):e.jsx(jr,{resource:t,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:u,currentAllUsersShare:b,onRemoveAccess:i})})]})})}function me(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Ce(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Yt(t,a){const{resourceType:n,resourceId:r,shareMutation:o,removeMutation:l,existingShares:c,resetUserSelections:i}=a;if(r)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=me(n,r,[{scope:"org_users_only",role:t.orgWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m}=t;if(d&&d.length>0){const h=me(n,r,d.map(f=>({scope:"specific_org_user",orgUserId:f.id,role:f.role})));o(h,{onSuccess:()=>{i()}})}if(u&&u.length>0){const h=Ce(n,r,u.map(f=>{var g,x;const p=(x=(g=c==null?void 0:c.shares)==null?void 0:g.specificOrgUsers)==null?void 0:x.find(v=>v.orgUserId===f);return{scope:"specific_org_user",orgUserId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));l(h,{onSuccess:()=>{i()}})}m&&m.length>0&&m.forEach(h=>{const f=me(n,r,[{scope:"specific_org_user",orgUserId:h.id,role:h.newRole}]);o(f,{onSuccess:()=>{i()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=me(n,r,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="allTenantUsers"){const d=me(n,r,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m,tenantId:h}=t;if(u&&u.length>0){const f=Ce(n,r,u.map(p=>{var x,v;const g=(v=(x=c==null?void 0:c.shares)==null?void 0:x.specificTenantUsers)==null?void 0:v.find(j=>j.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,tenantId:h,role:(g==null?void 0:g.role)||"VIEWER"}}));l(f,{onSuccess:()=>{i()}})}if(m&&m.length>0&&m.forEach(f=>{const p=me(n,r,[{scope:"specific_tenant_user",tenantUserId:f.id,tenantId:h,role:f.newRole}]);o(p,{onSuccess:()=>{i()}})}),d&&d.length>0){const f=me(n,r,d.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.role})));o(f,{onSuccess:()=>{i()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=Ce(n,r,[{scope:"all_tenant_users",role:"VIEWER"}]);l(d,{onSuccess:()=>{i()}})}else if(t.updateAccess){const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else{const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m}=t;if(d&&d.length>0){const h=me(n,r,d.map(f=>({scope:"specific_tenant_user",tenantUserId:f.id,role:f.role})));o(h,{onSuccess:()=>{i()}})}if(u&&u.length>0){const h=Ce(n,r,u.map(f=>{var g,x;const p=(x=(g=c==null?void 0:c.shares)==null?void 0:g.specificTenantUsers)==null?void 0:x.find(v=>v.tenantUserId===f);return{scope:"specific_tenant_user",tenantUserId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));l(h,{onSuccess:()=>{i()}})}m&&m.length>0&&m.forEach(h=>{const f=me(n,r,[{scope:"specific_tenant_user",tenantUserId:h.id,role:h.newRole}]);o(f,{onSuccess:()=>{i()}})})}break}}function Xt(t,a,n,r){var u,m,h,f,p,g;const{resourceType:o,resourceId:l,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(l)if(t.length>0){const x=Ce(o,l,t.map(v=>{var b,C;const j=(C=(b=i==null?void 0:i.shares)==null?void 0:b.specificTenantUsers)==null?void 0:C.find(R=>R.tenantUserId===v);return{scope:"specific_tenant_user",tenantUserId:v,role:(j==null?void 0:j.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:v=>{console.error("Remove access failed:",v)}})}else{const x=a==="tenant"&&n==="allTenants",v=a==="tenant"&&n==="allTenantUsers";if(x){const j=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(j){const b=Ce(o,l,[{scope:"all_tenants_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenants access failed:",C)}})}}else if(v){const j=(f=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:f[0];if(j){const b=Ce(o,l,[{scope:"all_tenant_users",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenant-users access failed:",C)}})}}else{const j=(g=(p=i==null?void 0:i.shares)==null?void 0:p.orgUsersOnly)==null?void 0:g[0];if(j){const b=Ce(o,l,[{scope:"org_users_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove org-wide access failed:",C)}})}}}}function yr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=we({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.DASHBOARD,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(h=>{if(!t)return;const f={resourceType:ee.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Yt(h,f)},[t,a,n,i,d]),m=M.useCallback(()=>{if(!t)return;const h={resourceType:ee.DASHBOARD,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(o,l||"",c||"",h)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:m}}function vr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=we({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.VISUAL,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(h=>{if(!t)return;const f={resourceType:ee.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Yt(h,f)},[t,a,n,i,d]),m=M.useCallback(()=>{if(!t)return;const h={resourceType:ee.VISUAL,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(o,l||"",c||"",h)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:m}}function br(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),o=t.toUpperCase().indexOf("ORDER BY");let l=t.length;if(o!==-1&&(l=o),r!==-1&&r<l&&(l=r),a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,l),i=t.substring(l);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Fs(t){const[a,n]=M.useState(null),[r,o]=M.useState(null);return M.useEffect(()=>{if(!t||t.trim()===""){n(null),o(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),o(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),o(i),n(null)}})()},[t]),a}function Nr(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const l=r.split("__")[0],c=t.find(i=>i.tabTitle===l);return c?c.id:t[0].id}return a}}return t[0].id}async function ht(t,a,n){if(!t||!a)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",a],o=n.getQueryData(r);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const l=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return n.setQueryData(r,i),s.ue.dismiss(l),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(l),c}}function Cr(t,a,n,r,o){const l=t.frameObject;a(l);const c=l.cards.find(i=>i.id===l.activeCardId);c&&n(c),r(!0),o(!0)}function Sr(){var f;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),r=Fs(((f=n.customCardPreferences)==null?void 0:f.url)||""),o=s.useEditorStore(p=>p.selectedSchemaName),l=s.useEditorStore(p=>p.selectedDatamodelId),c=s.useEditorStore(p=>p.selectedDatabaseName),i=s.useEditorStore(p=>p.selectedTableName),d=s.useEditorStore(p=>p.selectedConnectionId),u=s.useEditorStore(p=>p.isShowingVisual),m=n.sql,h=M.useCallback(()=>{var j;let p=m;m&&!m.includes("{{")&&(p=br(m),t(p));const g=(j=r==null?void 0:r.getState())==null?void 0:j.settings,x={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:o,lastSelectedDatamodelId:l,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:p,customCfg:u?n.customCfg:null,...g&&{customCardPreferences:{...n.customCardPreferences,settings:g}}},v=a.cards.map(b=>b.id===n.id?x:b);return{...a,cards:v,activeCardId:Nr(v,a.activeCardId)}},[n,a,u,o,l,c,i,d,t,r,m]);return console.log("getUpdatedFrame",h()),{getUpdatedFrame:h}}function zs(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient(),n=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:o,setCard:l}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:u,setIsDashboardPanelOpen:m}=s.useDashboardActions(),h=s.useDashboardStore(x=>x.selectedSheetId),f=er((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),p=M.useCallback(async x=>{try{r(x);const{data:v,fromCache:j}=await ht((t==null?void 0:t.accessToken)||"",x.id,a);return Cr(v,o,l,c,i),{success:!0,fromCache:j}}catch(v){return console.error("Error editing visual:",v),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,o,l,c,i]),g=M.useCallback(async x=>{try{if(r(x),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:v,fromCache:j}=await ht((t==null?void 0:t.accessToken)||"",x.id,a),b=v.frameObject;if(!b)return{success:!1,error:"Visual has no frame data"};const C={...b,id:s.v4()};return u(h,C,"end"),c(!0),d(C.id),m(!1),{success:!0,fromCache:j}}catch(v){return console.error("Error adding visual:",v),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,h,u,c,d,m]);return{visual:f.data,isLoading:f.isLoading,isError:f.isError,error:f.error,handleEditLibraryVisual:p,handleAddLibraryVisual:g,getUpdatedFrame:Sr().getUpdatedFrame,refetch:f.refetch}}function wr(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),[o,l]=M.useState(""),[c,i]=M.useState(""),[d,u]=M.useState(!1),[m,h]=M.useState(null),[f,p]=M.useState(!1),[g,x]=M.useState(null),[v,j]=M.useState(null),{setIsDashboardEditing:b,setIsVisualEditing:C}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:E}=zs(),{resources:S,isLoading:N,isError:D,createResource:w,updateResource:L,deleteResource:k,duplicateResource:O,shareResource:A,isCreating:I,isDeleting:y,removeResourceShares:T,isSharing:F,isRemovingShares:z,isUpdatingShares:_}=tr(()=>{p(!1),x(null)},()=>{r(!1),l(""),i("")}),{handleShareSubmit:P,handleRemoveAccess:Y}=vr((m==null?void 0:m.id)||null,A,T);cs();const W=S.filter(B=>{var J,ie;return((J=B==null?void 0:B.title)==null?void 0:J.toLowerCase().includes(t.toLowerCase()))||((ie=B==null?void 0:B.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),V=B=>new Date(B).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{o.trim()&&w({title:o,description:c,isPrivate:!1})},q=B=>{x(B),p(!0)},U=()=>{g&&k(g.id)},{startUpdating:H,stopUpdating:Q,isUpdating:G}=zt(),Z=(B,J)=>{const ie=J.title!==void 0?"title":"description";H(B,ie),L({resourceId:B,data:J},{onSuccess:()=>{Q(B,ie)},onError:()=>{Q(B,ie)}})},te=B=>{j(B),O(B,{onSettled:()=>j(null)})},ae=B=>{R(B)},se=B=>{E(B)},oe=B=>{const J=S.find(ie=>ie.id===B);J&&L({resourceId:B,data:{isPrivate:!J.isPrivate}})},K=B=>{h(B),u(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),we({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:ee.VISUAL,userType:"tenant"}),N?e.jsx(Ft,{}):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:n?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:o,onChange:B=>l(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:B=>i(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||I,children:I?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),l(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:I,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),I?"Creating...":"Create New Visual"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:B=>a(B.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:W.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(is,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):W.map(B=>e.jsx(ar,{visual:B,onAddVisual:se,onEditVisual:ae,onUpdateVisual:Z,onDeleteClick:q,onDuplicateVisual:te,onTogglePrivacy:oe,onShareVisual:K,isDeleting:y,isDuplicating:v===B.id,isTitleUpdating:G(B.id,"title"),isDescriptionUpdating:G(B.id,"description"),formatDate:V},B.id))})}),d&&m&&e.jsx(Jt,{resource:m,resourceType:ee.VISUAL,onShare:P,isSharing:F,isRemoving:z,isUpdating:_,onClose:()=>{u(!1),h(null)},onRemoveAccess:Y}),e.jsx(s.AlertDialog,{open:f,onOpenChange:B=>{!B&&y||(p(B),B||x(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',g==null?void 0:g.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:y,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:B=>{B.preventDefault(),B.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,children:y?"Deleting...":"Delete"})]})]})})]})}function kr({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onLoadDashboard:l,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var E;const{selectDashboard:f}=s.useManagementActions(),p=s.useIsDashboardSelected(t.id),[g,x]=M.useState(!1),[v,j]=M.useState(!1);M.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Et,{className:"h-3 w-3 text-purple-500"}):e.jsx(je,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),R=()=>{f(t),l(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",p&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:C()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>c==null?void 0:c(t.id,{title:S}),isEditable:t.permissions.canEdit&&p,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"line-clamp-1 max-w-[220px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),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:S=>c==null?void 0:c(t.id,{description:S}),isEditable:t.permissions.canEdit&&p,isPending:o,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:g,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.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:S=>{S.preventDefault(),S.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),u(t)},children:[e.jsx(je,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),i(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{className:"h-3 w-3"}),e.jsx("span",{children:((E=t.ownership.createdBy)==null?void 0:E.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 Dr({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 Er(t){const[a,n]=M.useState(""),[r,o]=M.useState(!1),[l,c]=M.useState(""),[i,d]=M.useState(""),[u,m]=M.useState(!1),[h,f]=M.useState(null),[p,g]=M.useState(!1),[x,v]=M.useState(null),[j,b]=M.useState(null),C=s.useManagementStore(K=>K.lastSelectedDashboard),R=s.useManagementStore(K=>K.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:E,isLoading:S,isError:N,createResource:D,updateResource:w,deleteResource:L,duplicateResource:k,isCreating:O,isDeleting:A,isSharing:I,isRemovingShares:y,isUpdatingShares:T,shareResource:F,removeResourceShares:z}=sr(()=>{g(!1),v(null),C&&R(C)},()=>{o(!1),c(""),d("")}),{handleShareSubmit:_,handleRemoveAccess:P}=yr((h==null?void 0:h.id)||null,F,z),{currentUser:Y}=cs(),W=E.filter(K=>{var B,J;return((B=K==null?void 0:K.title)==null?void 0:B.toLowerCase().includes(a.toLowerCase()))||((J=K==null?void 0:K.description)==null?void 0:J.toLowerCase().includes(a.toLowerCase()))}),V=K=>new Date(K).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{l.trim()&&D({title:l,description:i,isPrivate:!1})},q=K=>{var B;(B=t.onLoadDashboard)==null||B.call(t,K)},U=K=>{v(K),g(!0)},H=()=>{x&&L(x.id)},Q=K=>{b(K),k(K,{onSettled:()=>b(null)})},{startUpdating:G,stopUpdating:Z,isUpdating:te}=zt(),ae=(K,B)=>{const J=B.title!==void 0?"title":"description";G(K,J),w({resourceId:K,data:B},{onSuccess:()=>{Z(K,J)},onError:()=>{Z(K,J)}})},se=K=>{const B=E.find(J=>J.id===K);B&&w({resourceId:K,data:{isPrivate:!B.isPrivate}})},oe=K=>{f(K),Y==null||Y.type,m(!0)};return we({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ee.DASHBOARD,userType:"tenant"}),S?e.jsx(Ft,{}):N?e.jsx(Dr,{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:l,onChange:K=>c(K.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:K=>d(K.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()||O,children:O?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{o(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:O,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>o(!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:a,onChange:K=>n(K.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:W.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ra,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):W.map(K=>e.jsx(kr,{dashboard:K,isDeleting:A,isDuplicating:j===K.id,isTitleUpdating:te(K.id,"title"),isDescriptionUpdating:te(K.id,"description"),onLoadDashboard:q,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ae,onDeleteClick:U,onDuplicateDashboard:Q,onTogglePrivacy:se,onShareDashboard:oe,formatDate:V,onDashboardItemClick:t.onDashboardItemClick},K.id))})}),u&&h&&e.jsx(Jt,{resource:h,resourceType:ee.DASHBOARD,onShare:_,isSharing:I,isRemoving:y,isUpdating:T,onClose:()=>{m(!1),f(null)},onRemoveAccess:P}),e.jsx(s.AlertDialog,{open:p,onOpenChange:K=>{!K&&A||(g(K),K||v(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:K=>{K.preventDefault(),K.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function Zt({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(p=>p.dashboard);const{setDashboard:o,addSheet:l}=s.useDashboardStore(p=>p.actions),{currentUser:c}=cs(),i=c,[d,u]=s.useLocalStorageState("resource-management-active-tab","dashboards"),m=qt(a,{enabled:t}),h=p=>{},f=p=>{console.log("Editing dashboard:",p)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:m,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"-translate-x-full",n),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children: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:a,tooltip:"Hide Dashboard Management",children:e.jsx(s.X,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:d,onValueChange:u,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(Er,{onLoadDashboard:h,onEditDashboard:f,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(wr,{})})]})})]})})}function Tr(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(T=>T.theme);const n=s.useDashboardStore(T=>T.lenses),r=s.useDashboardStore(T=>T.selectedLensId),o=n==null?void 0:n.find(T=>T.id===r),l=s.useDashboardStore(T=>T.dashboard);s.useDashboardStore(T=>T.selectedSheetId);const c=s.useDashboardStore(T=>T.isDashboardEditing),i=s.useEditorStore(T=>T.card),d=s.useEditorStore(T=>T.selectedConnectionId),[u,m]=M.useState(!1),h=s.useDashboardStore(T=>T.isDashboardPanelOpen),f=s.useDashboardStore(T=>T.actions.setIsDashboardPanelOpen),p=s.useDashboardStore(T=>T.filterValues),g=s.useDashboardStore(T=>T.isVisualEditing),x=s.useDashboardStore(T=>T.showFilters);s.useDashboardStore(T=>T.showDashboardJSON);const v=s.useDashboardStore(T=>T.onSaveFunction),j=s.useDashboardStore(T=>T.actions.setShowFilters),{addFrame:b,setSelectedFrameId:C}=s.useDashboardStore(T=>T.actions),{getSelectedSheet:R,setIsDashboardEditing:E,setShowDashboardJSON:S}=s.useDashboardStore(T=>T.actions),N=R(),{tenantId:D,endUserId:w}=M.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),L=M.useMemo(()=>D||w,[D,w]),k=()=>{if(!c||!N)return;const T={dataSource:i.dataSource,mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},F={id:s.v4(),cards:[T],activeCardId:T.id};b(N.id,F),C(F.id)},O=()=>{E(!0)};async function A(){if(m(!0),!r||!o)return;const T=Bs(l),F=JSON.stringify(T),z={...o,template:F,filterValues:p};await Cs(z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),v==null||v(T),m(!1)}if(g)return null;const I=(o==null?void 0:o.name)||l.title,y=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[y&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(ca,{className:"h-4 w-4"})}),!g&&e.jsx(s.Label,{children:I})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!g&&e.jsx(La,{}),!g&&e.jsx(Bt,{}),c&&!g&&L&&e.jsx(Aa,{}),!g&&L&&e.jsx(Ma,{}),c&&!g&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:k,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!g&&e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2",onClick:O,size:"sm",children:e.jsx(s.Pencil,{className:"h-4 w-4"})}),c&&!g&&e.jsx(s.IconButton,{className:"h-7 p-2",onClick:()=>{E(!1),S(!1)},children:e.jsx(s.Cross2Icon,{className:"h-4 w-4"})}),c&&!g&&L&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",disabled:u,onClick:A,size:"sm",children:e.jsx(It,{className:"h-4 w-4"})}),!x&&!g&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>j(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!g&&c&&!1,!g&&!1,!g&&e.jsx(Zt,{isOpen:h,onClose:()=>f(!1)})]})]})}function Ir({name:t,items:a,value:n,onChange:r,isLoading:o,isError:l,refetch:c,className:i,icon:d,showNone:u=!1}){const m=ue.useRef(null),[h,f]=ue.useState(!1),[p,g]=ue.useState("100%"),x=u?[...a||[],{id:"none",name:"None"}]:a;ue.useLayoutEffect(()=>{m.current&&g(m.current.offsetWidth)},[]);function v(){var b;return o?"Loading...":l?"Error":n?(b=a==null?void 0:a.find(C=>C.id===n))==null?void 0:b.name:`Select ${t}`}function j(b,C){r(C),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:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:v()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:p},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(Tt,{className:s.cn("size-3.5 opacity-50",o&&"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:C=>j(C,b.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===b.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:b.name,children:b.name})]})},b.id))})]})]})})]})}function ze({title:t,items:a,value:n,isLoading:r,isError:o,refetch:l,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":o?"Error":n;function f(){if(t==="Connection")return e.jsx(va,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(ja,{className:"size-4"});if(t==="Table")return e.jsx(ls,{className:"size-4"});if(t==="Model")return e.jsx(Hn,{className:"size-4"})}function p(){return e.jsxs(s.Select,{disabled:u,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":o?"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(Tt,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:l})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((x,v)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},v))]}),(r||o)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function g(){return e.jsx(Ir,{icon:f(),items:a,value:h,onChange:c||(()=>{}),isLoading:r,isError:o,refetch:l,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"?p():g()})})}function Ar({column:t}){const[a,n]=M.useState(!1),r=s.useEditorStore(x=>x.selectedTableName),o=s.useEditorStore(x=>x.selectedSchemaName),l=s.useEditorStore(x=>x.selectedDatabaseName),c=s.useEditorStore(x=>x.selectedDatamodelId),i=s.useEditorStore(x=>x.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),f=s.useEditorStore(x=>x.actions.setRunSql);function p(x,v){var R;const j=s.createSqlGenConfig(x,i,v),b=(R=d==null?void 0:d.find(E=>E.id===c))==null?void 0:R.name;m(j);const C=s.getSql(j,s.fmt(o||""),s.fmt(r),b||"",u,l||"");C&&(h(C),f(!0)),n(!1)}function g(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>p(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>p(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>p(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>p(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>p(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:g()})]})}function Ps({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(Ue,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(Ze,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Kn,{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 xs({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(Ps,{column:t}),e.jsx("span",{children:t.column_name})]})}function Mr({id:t,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:l,transform:c}=s.useDraggable({id:t,data:{type:n}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:l,style:i,...o,...r,children:a})}function Lr({onClick:t,column:a}){const n=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}function u(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(a),className:s.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(xs,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(xs,{column:a})}),e.jsx(Mr,{id:a.column_name,type:"column",children:e.jsx(xs,{column:a})})]})}const ps={id:"__placeholder__",role:"groupby",type:"string"},fs={id:"__placeholder__",role:"groupby",type:"string"},gs={id:"__placeholder__",role:"metric",type:"number"},js={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},en={id:"__placeholder__"},Ee="droppable-group-by",Te="droppable-metrics",Ie="droppable-pivot-by",ss="sortable-group-by",Ss="sortable-metrics",ts="sortable-pivot-by",ws="droppable-filters",ks="sortable-filters",_s="sortable-order-by";function Rr(){const t=s.useDndStore(I=>I.insertIndex),a=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.groupByColumns)||[]}),n=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.metricColumns)||[]}),r=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.filterColumns)||[]}),o=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.orderBy)||[]}),l=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:f,setMetricColumns:p,setFilterColumns:g,setOrderByColumns:x,setPivotByColumns:v}=s.useEditorActions(),{columns:j}=s.useDataColumns(),{formattedTableName:b}=s.useEditorAside(),C=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=I=>{var F;const{active:y,over:T}=I;if(((F=y.data.current)==null?void 0:F.type)==="column"&&T){const z=T.id,_=j.find(V=>V.column_name===y.id);if(!_)return;const P=s.isNumberDataType(_.data_type),Y=s.isTextDataType(_.data_type),W=s.isDateDataType(_.data_type);if(Y||W){if(a.some($=>$.id===z)){const $=a.findIndex(U=>U.id===z);c($);const q=a.filter(U=>U.id!==ps.id);q.splice($,0,ps),d(q)}else if(T.id===Ee){c(a.length);const $=[...a,ps];d($),u(n),m(r)}}if(Y||W){if(l.some($=>$.id===z)){const $=l.findIndex(U=>U.id===z);c($);const q=l.filter(U=>U.id!==fs.id);q.splice($,0,fs),h(q)}else if(T.id===Ie){c(l.length);const $=[...l,fs];h($),d(a),u(n),m(r)}}if(P||Y){if(n.some($=>$.id===z)){console.log("isOverMetricSortable",z);const $=n.findIndex(U=>U.id===z);c($);const q=n.filter(U=>U.id!==gs.id);q.splice($,0,gs),u(q)}else if(T.id===Te){c(n.length);const $=[...n,gs];u($),m(r),d(a),h(l)}}if(S(_)){if(r.some($=>$.id===z)){const $=r.findIndex(U=>U.id===z);c($);const q=r.filter(U=>U.id!==js.id);q.splice($,0,js),m(q)}else if(T.id===ws){c(r.length);const $=[...r,js];m($),u(n),d(a),h(l)}}}else d(a),u(n),m(r),h(l)};function E(I){i(I.active.id),c(null),d(a),u(n),m(r),h(l)}function S(I){return!r.some(y=>y.name===I.column_name)}function N(I,y="SUM"){const{column_name:T,data_type:F}=I,z=[...n],_=t!==null?t:n.length,P={...I,id:pe(T),name:T,label:He(T,y),type:F,role:"metric",aggregate:y};z.splice(_,0,P),p(z)}function D(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...l],F=t!==null?t:l.length;let z;y?z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(F,0,z),v(T)}function w(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...a],F=t!==null?t:a.length;let z;y?z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(F,0,z),f(T)}function L(I){const y=[...r],T=t!==null?t:r.length,F={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,sql:s.getDefaultFilterSql(I.data_type,b,s.fmt(I.column_name)),role:"filter"};y.splice(T,0,F),g(y)}function k(I){var z,_,P,Y,W,V,$,q;const{active:y,over:T}=I,F=y.data.current;if((F==null?void 0:F.type)==="column"&&T){const U=j.find(Z=>Z.column_name===y.id);if(!U)return;const H=s.isNumberDataType(U.data_type),Q=s.isTextDataType(U.data_type),G=s.isDateDataType(U.data_type);(Q||G)&&(T.id===Ee||((z=T.data.current)==null?void 0:z.type)===ss)&&w(U),(Q||G)&&(T.id===Ie||((_=T.data.current)==null?void 0:_.type)===ts)?D(U):(H||Q)&&(T.id===Te||((P=T.data.current)==null?void 0:P.type)===Ss)?(H&&N(U),Q&&N(U,"COUNT")):S(U)&&(T.id===ws||((Y=T.data.current)==null?void 0:Y.type)===ks)&&L(U)}if(T&&((W=T.data.current)==null?void 0:W.type)===ss&&a.some(U=>U.id===y.id)){const U=a.findIndex(Q=>Q.id===y.id),H=a.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...a],[G]=Q.splice(U,1);Q.splice(H,0,G),f(Q)}}if(T&&((V=T.data.current)==null?void 0:V.type)===ts&&l.some(U=>U.id===y.id)){const U=l.findIndex(Q=>Q.id===y.id),H=l.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...l],[G]=Q.splice(U,1);Q.splice(H,0,G),v(Q)}}if(T&&(($=T.data.current)==null?void 0:$.type)===Ss&&n.some(U=>U.id===y.id)){const U=n.findIndex(Q=>Q.id===y.id),H=n.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...n],[G]=Q.splice(U,1);Q.splice(H,0,G),p(Q)}}if(T&&((q=T.data.current)==null?void 0:q.type)===ks&&r.some(U=>U.id===y.id)){const U=r.findIndex(Q=>Q.id===y.id),H=r.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...r],[G]=Q.splice(U,1);Q.splice(H,0,G),g(Q)}}O(I),i(null),c(null),d(a),u(n),m(r),h(l)}function O(I){const{active:y,over:T}=I,F=y.data.current;if((F==null?void 0:F.type)===_s&&T){const z=o.findIndex(P=>Ve(P.columnId)===y.id),_=o.findIndex(P=>Ve(P.columnId)===T.id);if(z!==-1&&_!==-1&&z!==_){const P=[...o],[Y]=P.splice(z,1);P.splice(_,0,Y),x(P)}}}function A(){i(null),c(null),d(a),u(n),m(r)}return{handleDragOver:R,handleDragEnd:k,handleDragStart:E,handleDragCancel:A,sensors:C}}function pe(t){return`${t}-${s.v4()}`}function He(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ve(t){return`${_s}-${t}`}function Pe(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Or({schemaName:t,tableName:a,columns:n,status:r}){const o=s.useEditorStore(y=>y.sqlGen),l=s.useEditorStore(y=>y.isDevMode),c=s.useEditorStore(y=>y.selectedConnectionId),i=s.useEditorStore(y=>{var T,F;return(F=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:F.metricColumns});s.useEditorStore(y=>{var T,F;return(F=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:F.groupByColumns});const d=s.useEditorStore(y=>y.selectedDatabaseName),u=s.useEditorStore(y=>y.selectedSchemaName),m=s.useEditorStore(y=>y.selectedTableName),h=s.useEditorStore(y=>y.selectedDatamodelId),f=s.useDashboardStore(y=>y.dashboard.aiScopeTables),{addToAIScope:p,removeFromAIScope:g}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:v,setCardSql:j,setRunSql:b,setSqlGen:C,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:E,modelItems:S,selectedDatamodelName:N}=s.useEditorAside();function D(y){var T;if(l){const F=s.createSqlGenConfig(y,o);C(F);const z=(T=S==null?void 0:S.find(P=>P.id===h))==null?void 0:T.name,_=s.getSql(F,s.fmt(t),s.fmt(a),z||"",E,d||"");_&&(j(_),b(!0))}if(!l){if(s.isTextDataType(y.data_type))if(i&&i.length>0){const F={...y,role:"groupby",id:pe(y.column_name),name:y.column_name,type:y.data_type};v(F)}else{const F={...y,role:"metric",id:pe(y.column_name),name:y.column_name,label:He(y.column_name,"COUNT"),type:y.data_type,aggregate:"COUNT"};x(F)}if(s.isDateDataType(y.data_type)){const F={...y,role:"groupby",id:pe(y.column_name),name:y.column_name,type:y.data_type,label:Pe(y.column_name,"month"),granularity:"month"};v(F)}if(s.isNumberDataType(y.data_type)){const F={...y,role:"metric",id:pe(y.column_name),name:y.column_name,label:He(y.column_name,"SUM"),type:y.data_type,aggregate:"SUM"};x(F)}}}function w(y){y===!0&&(m||N)&&c?(p({connectionId:c,connectionType:E==="S3"||E==="API"?"DuckDb":E||"",databaseName:d||"",schemaName:u||"",tableName:m||"",datamodelName:s.resolveDatamodelName(N),datamodelId:h||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(g({connectionId:c||"",connectionType:E||"",tableName:m||"",datamodelName:s.resolveDatamodelName(N),datamodelId:h||"",databaseName:d||"",schemaName:u||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function L(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:E,databaseName:d||""});R(!1);const T=E==="MSSQL"?`SELECT top 10 * FROM ${y}`:`SELECT * FROM ${y} LIMIT 10`;j(T),b(!0)}function k(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:E,databaseName:d||""});j(`SELECT COUNT(*) as count FROM ${y}`),b(!0)}function O(){return(f==null?void 0:f.find(y=>y.connectionId===c&&(y.tableName===m||y.datamodelName===N)))!==void 0}function A(y){return l?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>D(y),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ps,{column:y}),e.jsx("span",{children:y.column_name})]}),e.jsx("div",{onClick:T=>T.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(y.data_type)&&e.jsx(Ar,{column:y})})]}):e.jsx(Lr,{onClick:D,column:y})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${O()?"Remove from":"Add to"} Assistant Scope`,pressed:O(),onPressedChange:w,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":O(),"text-muted-foreground":!O()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:L,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(xa,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:k,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(At,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((y,T)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},T))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[l&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:I()}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(y=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:A(y)},y.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function sn({ColumnsComponent:t,type:a}){var ke;const n=s.useEditorStore(ne=>ne.card),r=s.useEditorStore(ne=>ne.selectedConnectionId),o=s.useDashboardStore(ne=>ne.showFilters),l=s.useEditorStore(ne=>ne.selectedDatamodelId),c=s.useEditorStore(ne=>ne.selectedDatabaseName),i=s.useEditorStore(ne=>ne.selectedSchemaName),d=s.useEditorStore(ne=>ne.selectedTableName),u=s.useEditorStore(ne=>ne.isDevMode),{setSelectedTableName:m,setIsDevMode:h,setCardSql:f}=s.useEditorActions(),{connectionItems:p,modelItems:g,schemaItems:x,databaseItems:v,tableItems:j,columns:b,isConnectionsLoading:C,isModelsLoading:R,isConnectionsError:E,isModelsError:S,isDatabasesLoadingOrFetching:N,isDatabaseError:D,isSchemaLoadingOrFetching:w,isSchemaError:L,isColumnsError:k,isColumnsLoadingOrFetching:O,isTableLoadingOrFetching:A,isTableError:I,connectionType:y,isNonDbConnection:T,refetchDatabases:F,refetchModels:z,refetchSchemas:_,refetchTables:P,refetchColumns:Y,refetchConnections:W,handleConnectionChange:V,handleDatabaseChange:$,handleSchemaChange:q,handleDatamodelChange:U,handleTableChange:H,tableName:Q,schemaName:G}=s.useEditorAside(),{data:Z,refetch:te}=s.useDashboardCardQuery(n);function ae(){return t?t(G,Q,b):e.jsx(Or,{schemaName:G,tableName:Q,columns:b,status:O?"Loading...":k?"Error":"Success"})}function se(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function oe(ne){ne===!0?Z&&(f(Z.userSql),setTimeout(()=>{te()},100)):f(""),h(ne)}function K(){if(!r||y==="S3"||y==="API")return null;if(!l||l==="none")return e.jsx(ze,{refetch:F,showNone:!0,onChange:$,isError:D,isLoading:N,items:v,value:c||"",title:"Database",type:"combobox"})}function B(){if(r&&!T&&(!c||c==="none")&&(!l||l==="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 J(){if(!r||y==="S3"||y==="API")return null;if(!c||c==="none")return e.jsx(ze,{refetch:z,showNone:!0,onChange:U,isError:S,isLoading:R,items:g,value:l||"",title:"Model",type:"combobox"})}function ie(){return!r||y==="S3"||y==="API"||!c||c==="none"?null:e.jsx(ze,{refetch:_,onChange:q,isError:L,isLoading:w,items:x,value:i||"",title:"Schema",type:"combobox"})}function ye(){function ne(){let le=!1;return y==="API"?(le=!1,le):((y==="S3"||r&&c&&c!=="none"&&i)&&(le=!0),le)}return ne()?e.jsx(ze,{refetch:P,onChange:H,isError:I,items:j,isLoading:A,value:d||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(ze,{refetch:W,items:p,title:"Connection",value:r||"",onChange:V,isLoading:C,isError:E,type:"combobox",connectionTooltip:((ke=p==null?void 0:p.find(ne=>ne.id===r))==null?void 0:ke.type)||""}),K(),B(),J(),ie(),ye()]}),ae(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:u,onCheckedChange:oe,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:se,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(fa,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function tn({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,l]=M.useState(!1),c=M.useRef(null),i=M.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(f){(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d())}function m(){const f=window.getSelection();if(f&&f.toString().trim()!==""){const p=f.toString();navigator.clipboard.writeText(p),l(!0),i.current=!0,setTimeout(()=>{l(!1),i.current=!1},1e3)}else i.current=!1}function h(){l(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),o&&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 nn({sql:t,error:a,onDebugWithAssistant:n}){const r=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:o,setCardSql:l,setRunSql:c}=s.useEditorActions();function i(){o(!r),l(t),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(tn,{error:a}),t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!r&&t&&e.jsxs(s.Button,{onClick:i,variant:"secondary",size:"sm",children:[e.jsx(sa,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(s.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(la,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function an({sql:t,error:a,onDebugWithAssistant:n}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(kt,{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(nn,{sql:t,error:a,onDebugWithAssistant:n})})]})}var rn={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},xt=M.createContext&&M.createContext(rn),Br=["attr","size","title"];function Fr(t,a){if(t==null)return{};var n=zr(t,a),r,o;if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);for(o=0;o<l.length;o++)r=l[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}function zr(t,a){if(t==null)return{};var n={};for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){if(a.indexOf(r)>=0)continue;n[r]=t[r]}return n}function ns(){return ns=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},ns.apply(this,arguments)}function pt(t,a){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function as(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?pt(Object(n),!0).forEach(function(r){Pr(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):pt(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Pr(t,a,n){return a=_r(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function _r(t){var a=Vr(t,"string");return typeof a=="symbol"?a:a+""}function Vr(t,a){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function on(t){return t&&t.map((a,n)=>M.createElement(a.tag,as({key:n},a.attr),on(a.child)))}function Me(t){return a=>M.createElement(Ur,ns({attr:as({},t.attr)},a),on(t.child))}function Ur(t){var a=n=>{var{attr:r,size:o,title:l}=t,c=Fr(t,Br),i=o||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),M.createElement("svg",ns({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:as(as({color:t.color||n.color},n.style),t.style),height:i,width:i,xmlns:"http://www.w3.org/2000/svg"}),l&&M.createElement("title",null,l),t.children)};return xt!==void 0?M.createElement(xt.Consumer,null,n=>a(n)):a(rn)}function $r(t){return Me({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 ln(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(x=>x.theme),r=s.useEditorStore(x=>x.frame),o=s.useEditorStore(x=>x.card),l=s.useEditorStore(x=>x.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(o),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=M.useRef(),h=M.useRef({}),f=r.cards.find(x=>x.id===l),p=M.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]);M.useEffect(()=>{if(l&&o.id&&o.id!==l){if(m.current&&c){const x=m.current.getModel();x&&(h.current[o.id]=x);let v=h.current[l];if(!v){const j=p();v=c.editor.createModel(j,t),h.current[l]=v}m.current.setModel(v)}d(l,o),u(!0)}},[l,o,d,c,u,t,p]),M.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=n==="system"?x:n;c.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),M.useEffect(()=>{const x=m.current;x&&c&&o&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,o]);function g(x,v){if(m.current=x,!h.current[o.id]){const j=x.getModel(),b=p();h.current[o.id]=j||(v==null?void 0:v.editor.createModel(b,t))||x.getModel()}x.setModel(h.current[o.id])}return{handleEditorDidMount:g}}function qr(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=ln("sql");function l(c){n(c),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:l,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function Gr(){const t=s.useEditorStore(o=>o.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=ln("python");function r(o){a(o)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Hr({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 Vs({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const n=s.useEditorStore(i=>i.card);Fs(((c=n.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),n.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:o}=zs();function l(){const i=o();r==null||r(i)}return e.jsxs(s.Button,{onClick:l,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Kr(){const t=s.useQueryClient(),[a,n]=M.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:l}=zs(),c=s.useSelectedVisual(),i=nr(),d=()=>{const u=l();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{n(!1),o(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{n(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(It,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Us(){const{setTempQueryData:t,setSqlGen:a}=s.useEditorActions(),n=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),o=s.useEditorStore(d=>d.onClose),l=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(l);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&n.setQueryData(d,u)}a({}),o==null||o()}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 ds(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(v=>v.isDevMode),r=s.useEditorStore(v=>v.tempQueryData),o=s.useEditorStore(v=>v.card),{queryKey:l}=s.useDashboardCardQuery(o),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:f,setCardConfig:p,setCardType:g}=s.useEditorActions();function x(){const v=a.getQueryData(l);r!=null&&r.queryData||t({queryKey:l,queryData:v}),a.setQueryData(l,null),a.removeQueries({queryKey:l,exact:!0}),n&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),f(),p(void 0),d(""),u(""),m({}),g("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 Qr(){const t=s.useQueryClient(),[a,n]=M.useState(!1),[r,o]=M.useState(!1);s.useEditorStore(P=>P.frame);const l=s.useEditorStore(P=>P.card);s.useEditorStore(P=>P.isShowingVisual),s.useEditorStore(P=>P.selectedConnectionId),s.useEditorStore(P=>P.tempQueryData),s.useEditorStore(P=>P.selectedDatabaseName),s.useEditorStore(P=>P.selectedDatamodelId),s.useEditorStore(P=>P.selectedSchemaName);const c=s.useEditorStore(P=>P.showAIDialog);s.useEditorStore(P=>P.selectedTableName);const i=s.useEditorStore(P=>{var Y;return(Y=P==null?void 0:P.card)==null?void 0:Y.sql}),d=s.useEditorStore(P=>{var Y;return(Y=P==null?void 0:P.card)==null?void 0:Y.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:f,setTempQueryData:p,setPythonStdOut:g,setCardPreferences:x,setCardType:v,setCardPython:j,runAssistant:b,setShowAIDialog:C}=s.useEditorActions();s.useEditorStore(P=>P.onSave),s.useEditorStore(P=>P.onClose),s.useEditorStore(P=>P.actions.setSqlGen);const R=s.useEditorStore(P=>P.runSql),E=s.useEditorStore(P=>P.actions.setRunSql),S=s.useEditorStore(P=>P.actions.setIsSqlRunning),{data:N,isLoading:D,isFetching:w,isSuccess:L,isError:k,error:O,queryKey:A,refetch:I,errorMessage:y}=s.useDashboardCardQuery(l);M.useEffect(()=>{if(N&&(N.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((N==null?void 0:N.output)||""),N.records.length>0)){const{dimensionKeys:P}=s.getKeys(N.records);h(P)}},[N,h,g]),M.useEffect(()=>{(D||w)&&S(!0),(k||L)&&S(!1),k&&(h([]),g(""))},[D,w,N,g,k,L,S,h,O]),M.useEffect(()=>{R&&(t.getQueryData(A)||I(),E(!1))},[R,I,E,A,t]);async function T(){const P=`Can you help me debug this query in the current table scope?
|
|
406
|
+
*/const je=s.createLucideIcon("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function Bs(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var l;return{...o,cards:(l=o.cards)==null?void 0:l.map(c=>Lt(c))}})}})}}function Lt(t){return{...t,customCfg:Ea(t.customCfg),data:[]}}function Ea(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Ta(t,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:o,filterValues:n,operation:"create"})}async function Cs(t,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:l,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:l,shared:c,operation:"update"})}async function Ia(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Aa(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),o=s.useDashboardStore(x=>x.lenses),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=M.useState(!1),[u,m]=M.useState(!1),h=s.useDashboardStore(x=>x.dashboard),f=s.useDashboardStore(x=>x.filterValues),{authToken:p}=s.useSemaphorContext();async function g(){d(!0);const x=Bs(h),v=await Ta(t,x,f,p==null?void 0:p.accessToken);v&&(l([...o||[],v]),c(v.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:x=>{a(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:g,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Ma(){const[t,a]=M.useState(!1),n=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:o,setSelectedLensId:l}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(m){l(m)}async function d(m){if(await Ia(m,c==null?void 0:c.accessToken)){const f=n==null?void 0:n.filter(p=>p.id!==m);o(f||[]),l("original")}}async function u(m){const h=n==null?void 0:n.map(g=>g.id===m.id?{...g,isDefault:!m.isDefault}:{...g,isDefault:!1});o(h||[]);const f={...m,isDefault:!m.isDefault};await Cs(f,c==null?void 0:c.accessToken);const p=n==null?void 0:n.find(g=>g.isDefault);if(p&&p.id!==m.id){const g={...p,isDefault:!1};await Cs(g,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(oa,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(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(),u(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(),d(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 Rt(){var l;const t=s.useDashboardStore.getState().authToken,a=s.useDashboardStore.getState().theme,n=s.useDashboardStore.getState().filterValues,r=(l=s.useDashboardStore.getState().dashboard)==null?void 0:l.title,o=s.useDashboardStore.getState().selectedSheetId;return{authToken:t,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function Ot(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:l}=Rt();if(t)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",l||"");const i=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;s.useDashboardStore.setState({isDownloadingPdf:!0});const m=(await(await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,h=document.createElement("a");h.href=m;const f=`${o}-${new Date().toISOString()}.pdf`;h.download=f,h.click(),s.useDashboardStore.setState({isDownloadingPdf:!1})}function La({iconClassName:t}){const{authToken:a}=s.useSemaphorContext();s.useDashboardStore(o=>{var l;return(l=o.dashboard)==null?void 0:l.title}),s.useDashboardStore(o=>o.theme),s.useDashboardStore(o=>o.filterValues);const n=s.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await Ot()}return e.jsx(s.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(s.LoaderCircle,{className:s.cn("size-3.5 animate-spin",t)}):e.jsx(s.Download,{className:s.cn("size-4",t)})})}function he({defaultValue:t,label:a,options:n,value:r,onValueChange:o,className:l,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:o,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",l),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const ct=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function Bt({triggerButtonClassName:t}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:l,isDeleting:c}=Ra(),[i,d]=M.useState(""),[u,m]=M.useState(ct[0].value),[h,f]=M.useState("06:00"),[p,g]=M.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"email",children:"Email"}),e.jsx(s.Input,{id:"email",value:i,onChange:x=>d(x.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(s.Input,{id:"subject",placeholder:"Monthly Sales Report",value:p,onChange:x=>{g(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(he,{className:"col-span-2 h-8",label:"Select Frequency",options:ct,value:u,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 n({email:i,frequency:u,time:h,subject:p}),f("00:00"),d(""),g("")},className:"h-8 p-2",disabled:o==="loading"||!i,children:[o==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(kt,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:l})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),s.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(x=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[s.titleCase(x.frequency)," "]}),e.jsx(s.Label,{children:x.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(dt,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Wn,{className:"size-3.5"})}),e.jsx(dt,{tooltip:`${x.endUserEmail}`,children:e.jsx(pa,{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 dt=({children:t,tooltip:a})=>e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:t}),e.jsx(s.TooltipContent,{children:a})]})});function Ra(){const[t,a]=M.useState("idle"),[n,r]=M.useState(""),[o,l]=M.useState(null),c=s.useDashboardStore(C=>C.authToken),i=s.useDashboardStore(C=>C.dashboard.id),d=s.useDashboardStore(C=>C.dashboard.title),{endUserId:u}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),m="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:i,endUserId:u},{data:f,isLoading:p,isError:g,isFetching:x,refetch:v}=s.useQuery({queryKey:["subscriptions",i,u],queryFn:()=>s.getRequest(m,(c==null?void 0:c.accessToken)||"",h),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!u});async function j({email:C,subject:R,frequency:E,time:S}){const{authToken:N,...D}=Rt(),w=Intl.DateTimeFormat().resolvedOptions().timeZone,L={email:C,frequency:E,time:S,timezone:w,endUserId:u,endUserEmail:C,subject:R||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:D};a("loading");const k="https://semaphor.cloud/api/v1/subscriptions/create";try{const O=await s.postRequestRegular(k,(N==null?void 0:N.accessToken)||"",{...L});a("success"),r(""),v(),setTimeout(()=>{a("idle")},2e3)}catch(O){console.error(O),a("error"),r(O.message)}}async function b(C){const R="https://semaphor.cloud/api/v1/subscriptions/delete";l(C);try{await s.postRequestRegular(R,(c==null?void 0:c.accessToken)||"",{id:C}),v(),setTimeout(()=>{l(null)},2e3)}catch(E){console.error(E),l(null),a("error"),r(E.message)}}return{data:f,isLoading:p,isFetching:x,isError:g,isDeleting:o,refetch:v,handleScheduleSubscription:j,handleDeleteSubscription:b,status:t,error:n}}function cs(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();let n=null;a&&(a.endUserId&&a.endUserEmail&&a.tenantId?n={id:a.endUserId,name:a.endUserEmail?String(a.displayName):"",email:a.endUserEmail?String(a.endUserEmail):"",type:"tenant",tenantId:a.tenantId}:a.orgUserId&&a.orgUserEmail&&(n={id:a.orgUserId,name:a.orgUserEmail?String(a.displayName):"",email:a.orgUserEmail?String(a.orgUserEmail):"",type:"organization"}));const{data:r,isLoading:o,isError:l}=s.useQuery({queryKey:["userInfo",n==null?void 0:n.id],queryFn:async()=>{if(!(n!=null&&n.id))return;const i=await fetch(`https://semaphor.cloud/api/management/v1/unified-users/${n.id}`,{headers:{Authorization:`Bearer ${(t==null?void 0:t.accessToken)||""}`,"Content-Type":"application/json"}});if(!i.ok)throw new Error("Failed to fetch user info");return(await i.json()).user},enabled:!!(t!=null&&t.accessToken)&&!!(n!=null&&n.id)});return{currentUser:n?{...n,...r||{}}:null,isLoading:o,isError:l}}function Ft(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,a)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},a))})]})})}var ee=(t=>(t.DASHBOARD="dashboard",t.VISUAL="visual",t))(ee||{});const Oa=async(t,a,n,r,o,l)=>{const c={},i={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${i[a]}`,t,c)},Ba=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}`,t,n)},Fa=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!l.ok){const c=await l.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${l.status}`)}return l.json()},za=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},o=await fetch(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});if(!o.ok){const l=await o.json();throw new Error((l==null?void 0:l.error)||`HTTP error! status: ${o.status}`)}return o.json()},Pa=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/duplicate`,t,{})},_a=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.postRequestRegular(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,t,r)},Va=async(t,a,n,r)=>{const o={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"},l=await fetch(`https://semaphor.cloud/api/management/v1/${o[a]}/${n}/share`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!l.ok){const c=await l.json();throw new Error((c==null?void 0:c.error)||`HTTP error! status: ${l.status}`)}return l.json()},Ua=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}/shares`,t)},$a=async(t,a,n)=>{const r={[ee.DASHBOARD]:"dashboards",[ee.VISUAL]:"visuals"};return s.getRequest(`https://semaphor.cloud/api/management/v1/${r[a]}/${n}`,t)};function qa(t){const{authToken:a}=s.useSemaphorContext();return s.useQuery({queryKey:["tenants"],queryFn:()=>s.getRequest("https://semaphor.cloud/api/management/v1/tenants",(a==null?void 0:a.accessToken)||""),enabled:(t==null?void 0:t.enabled)!==void 0?t.enabled&&!!(a!=null&&a.accessToken):!!(a!=null&&a.accessToken)})}function Ga(t,a,n,r,o){const{authToken:l}=s.useSemaphorContext();return s.useQuery({queryKey:[t,a,n,r,o],queryFn:()=>Oa((l==null?void 0:l.accessToken)||"",t),enabled:!!(l!=null&&l.accessToken)})}function Ha(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>Ba((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} created successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to create ${s.toTitleCase(t)}: ${o.message}`)}})}function Ka(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:({resourceId:r,data:o})=>Fa((a==null?void 0:a.accessToken)||"",t,r,o),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} updated successfully`)},onError:r=>{s.ue.error(`Failed to update ${s.toTitleCase(t)}: ${r.message}`)}})}function Qa(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>za((n==null?void 0:n.accessToken)||"",t,o),onMutate:async()=>{await r.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await r.invalidateQueries({queryKey:[t]}),s.ue.success(`${s.toTitleCase(t)} deleted successfully`),a==null||a()},onError:o=>{s.ue.error(`Failed to delete ${s.toTitleCase(t)}: ${o.message}`)}})}function Wa(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:r=>Pa((a==null?void 0:a.accessToken)||"",t,r),onMutate:async()=>{await n.cancelQueries({queryKey:[t]})},onSuccess:async()=>{await n.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 Ja(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>_a((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to share resource: ${n.message}`)}})}function Ya(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>Va((t==null?void 0:t.accessToken)||"",n,r,o),onMutate:async n=>{await a.cancelQueries({queryKey:["resource-shares",n.resourceType,n.resourceId]})},onSuccess:async(n,r)=>{await a.invalidateQueries({queryKey:["resource-shares",r.resourceType,r.resourceId]}),a.invalidateQueries({queryKey:[r.resourceType]})},onError:n=>{s.ue.error(`Failed to remove resource shares: ${n.message}`)}})}function Xa(t,a){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,a],queryFn:()=>Ua((n==null?void 0:n.accessToken)||"",t,a),enabled:!!(n!=null&&n.accessToken)&&!!a})}function Za(t,a,n){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,a],queryFn:()=>$a((r==null?void 0:r.accessToken)||"",t,a),enabled:(n==null?void 0:n.enabled)!==void 0?n.enabled&&!!(r!=null&&r.accessToken)&&!!a:!!(r!=null&&r.accessToken)&&!!a})}function er(t,a){return Za(ee.VISUAL,t,a)}function zt(){const[t,a]=M.useState(new Map),n=M.useCallback((l,c)=>{a(i=>{const d=new Map(i),u=new Set(d.get(l)||[]);return c?u.add(c):(u.add("title"),u.add("description")),d.set(l,u),d})},[]),r=M.useCallback((l,c)=>{a(i=>{const d=new Map(i),u=new Set(d.get(l)||[]);return c?u.delete(c):u.clear(),u.size===0?d.delete(l):d.set(l,u),d})},[]),o=M.useCallback((l,c)=>{const i=t.get(l);return i?c?i.has(c):i.size>0:!1},[t]);return{startUpdating:n,stopUpdating:r,isUpdating:o}}function Pt(t,a,n){var h;const r=Ga(t),o=Ha(t,n),l=Ka(t),c=Qa(t,a),i=Wa(t),d=Ja(),u=Ya(),m={[ee.DASHBOARD]:"dashboards",[ee.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:o.mutate,updateResource:l.mutate,deleteResource:c.mutate,duplicateResource:i.mutate,shareResource:d.mutate,removeResourceShares:u.mutate,isCreating:o.isPending,isUpdating:l.isPending,isDeleting:c.isPending,isDuplicating:i.isPending,isSharing:d.isPending,isRemovingShares:u.isPending,isUpdatingShares:d.isPending,refetch:r.refetch}}function sr(t,a){return Pt(ee.DASHBOARD,t,a)}function tr(t,a){return Pt(ee.VISUAL,t,a)}function nr(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:async({visualId:n,data:r})=>{const o=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t==null?void 0:t.accessToken}`},body:JSON.stringify(r)});if(!o.ok)throw new Error("Failed to update visual");return o.json()},onSuccess:()=>{s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["visuals"]})},onError:()=>{s.ue.error("Failed to update visual")}})}function ar({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onAddVisual:l,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var E;const{selectVisual:f}=s.useManagementActions(),p=s.useIsVisualSelected(t.id),[g,x]=M.useState(!1),[v,j]=M.useState(!1);M.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Et,{className:"h-3 w-3 text-purple-500"}):e.jsx(je,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),R=()=>{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",p&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:C()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>i==null?void 0:i(t.id,{title:S}),isEditable:t.ownership.isOwner&&p,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:b()})]}),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:S=>i==null?void 0:i(t.id,{description:S}),isEditable:t.ownership.isOwner&&p,isPending:o,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:S=>{S.stopPropagation(),l(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.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:S=>{S.stopPropagation(),l(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),c==null||c(t)},children:[e.jsx(ya,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),m(t)},children:[e.jsx(je,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),d(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{className:"h-3 w-3"}),e.jsx("span",{children:((E=t.ownership.createdBy)==null?void 0:E.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 _t({value:t,onChange:a,placeholder:n="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function es({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:o="",allowDropdown:l=!0}){var d;const c=((d=n.find(u=>u.value===t))==null?void 0:d.label)||t,i=n.filter(u=>u.value!==t);return l?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":""} ${o}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:l}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:u.value,disabled:r}),a(u.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${o}`,children:c})}function Vt({selectedUsers:t,selectedUserObjects:a,onRemove:n,onRoleChange:r,getRoleOptions:o}){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(l=>n(l.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.map(l=>{const c=t.find(d=>d.id===l.id),i=o(l.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[l.name,e.jsx(es,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(l.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>n(l.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},l.id)})}),e.jsx(s.Separator,{})]})}function Ut({usersToRemove:t,allUsers:a,onRemove:n}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>n(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function $t({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const o=r("tenant"),l=i=>{const d=a.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=o.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(je,{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:l(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>n(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function qt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,o=M.useRef(null);return M.useEffect(()=>{const l=c=>{const i=c.target;o.current&&o.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return n&&document.addEventListener(r,l),()=>{document.removeEventListener(r,l)}},[t,n,r]),o}function xe(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function rr(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Gt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function or(t,a,n){const r=Gt(t),o=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(o==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function ir({user:t}){return Gt(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 lr({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:o,handleUpdateAccess:l}){if(!(a!=null&&a.role))return null;const c=rr((r==null?void 0:r.type)||""),i=n.some(h=>h.id===t.id),d=n.find(h=>h.id===t.id),u=d?d.newRole:a==null?void 0:a.role,m=o(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(es,{currentRole:u,onRoleChange:h=>{l(t.id,a.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:xe(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function cr({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),a&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(qe,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function dr({isUserRemoving:t,isSelected:a,hasAccess:n,isRemoving:r,isSharing:o}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),a&&!n&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:o?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 ur({existingShares:t,allUsers:a,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((f,p)=>{var j,b;const g=((j=a.find(C=>C.id===f.orgUserId))==null?void 0:j.name)||"Unknown User",x=((b=a.find(C=>C.id===f.orgUserId))==null?void 0:b.type)||"",v=xe(f.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:g}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},p)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((f,p)=>{var j,b;const g=((j=a.find(C=>C.id===f.tenantUserId))==null?void 0:j.name)||"Unknown User",x=((b=a.find(C=>C.id===f.tenantUserId))==null?void 0:b.type)||"",v=xe(f.role,n(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:g}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:v})]},p)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((f,p)=>{const g=xe(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},p)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((f,p)=>{const g=xe(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},p)})})]}),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,p)=>{const g=xe(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:g})]},p)})})]}),!i.length&&!d.length&&!u.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var p,g;const m=((p=a.find(x=>x.id===d.tenantUserId))==null?void 0:p.name)||"Unknown User",h=((g=a.find(x=>x.id===d.tenantUserId))==null?void 0:g.type)||"",f=xe(d.role,n(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:f})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=xe(d.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const l=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:[l.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",l.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[l.slice(0,3).map((i,d)=>{var f,p;const u=((f=a.find(g=>g.id===i.tenantUserId))==null?void 0:f.name)||"Unknown User",m=((p=a.find(g=>g.id===i.tenantUserId))==null?void 0:p.type)||"",h=xe(i.role,n(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),l.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",l.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=xe(i.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!l.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function mr({isInitialLoading:t,searchQuery:a,availableUsers:n}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function hr({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:o,isSelected:l,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:f,handleUserRoleChange:p}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":l?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:o?!n:l,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{o?n?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(ir,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(es,{currentRole:a==null?void 0:a.role,onRoleChange:g=>f(t.id,a.role,g),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(lr,{user:t,userShare:a,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:f}),l&&!o&&e.jsx("div",{onClick:g=>g.stopPropagation(),children:e.jsx(es,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:g=>p(t.id,g),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(cr,{hasAccess:r,isUserRemoving:n,isSelected:l,hasAccessFromAPI:o}),e.jsx(dr,{isUserRemoving:n,isSelected:l,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Ht({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:o=[],currentUser:l,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),p=s.useShareSearchQuery(),g=s.useShareManagementActions(),x=c||(E=>{const S=m.some(D=>D.id===E),N=h.includes(E);S?g.removeSelectedUser(E):N?g.removeUserFromRemove(E):g.addSelectedUser({id:E,role:"VIEWER"})}),v=i||g.updateSelectedUserRole,j=d||g.addUserToRemove,b=u||((E,S,N)=>{g.addUserToUpdate({id:E,currentRole:S,newRole:N})}),C=o,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 (",(C??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(ur,{existingShares:t,allUsers:o,getRoleOptions:r,currentUser:l})})]})})]}),(C==null?void 0:C.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===C.length?g.setSelectedUsers([]):g.setSelectedUsers(C.map(E=>({id:E.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===C.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(mr,{isInitialLoading:a,isSearching:n,searchQuery:p,availableUsers:C||[]}),!a&&!n&&(C==null?void 0:C.length)>0&&C.map(E=>{const S=t?or(E,t,l):void 0,N=R.includes(E.id),D=!!S,w=D&&!N,L=m.some(A=>A.id===E.id),k=m.find(A=>A.id===E.id),O=r(E.type);return e.jsx(hr,{user:E,userShare:S,isUserRemoving:N,hasAccess:w,hasAccessFromAPI:D,isSelected:L,selectedUser:k,roleOptions:O,currentUser:l,usersToUpdate:f,handleUserToggle:x,handleRemoveAccess:j,handleUpdateAccess:b,handleUserRoleChange:v},E.id)})]})]})}function Kt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const o=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(l=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:l.value,id:l.value,className:"peer sr-only",disabled:l.disabled}),e.jsxs(s.Label,{htmlFor:l.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 ${l.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[l.icon||e.jsx(Se,{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:l.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l.description})]})]})]},l.value))}),!o&&r.some(l=>l.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 De=()=>[{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 xr({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:o=null,allUsersToRemove:l=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=De().filter(b=>b.value==="VIEWER"||b.value==="EDITOR"||b.value==="CONTRIBUTOR"),m=a.role!=="NONE"?a.role:"NONE",h=o?o.newRole:m,f=a.role!=="NONE"&&!l&&(!o||o.newRole===m),p=o!==null&&o.newRole!==m,g=l,x=m==="NONE"||!m,v=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(Ca,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},j=b=>{r(m,b)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",p&&!g&&!x?"border-orange-300 bg-orange-50":f?"border-green-300 bg-green-50":g||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(je,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="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"}),p&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(g||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:g||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:u.map(b=>e.jsxs(s.Button,{variant:h===b.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>j(b.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[v(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 Qt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:l,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=x=>x==="OWNER"?"CONTRIBUTOR":x,h=a?{role:u(a.role)}:{role:"NONE"},f=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,p=(x,v)=>{l(x,v)},g=()=>{c()};return e.jsx(xr,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:p,onRemoveAccess:g,allUsersToUpdate:f,allUsersToRemove:d})}const pr=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function fr(t={}){var r,o,l;const{authToken:a}=s.useSemaphorContext(),n=s.useQuery({queryKey:["unified-users",t],queryFn:()=>pr((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken),retry:(c,i)=>i instanceof Error&&i.message.includes("401")||i instanceof Error&&i.message.includes("403")?!1:c<2,retryDelay:c=>Math.min(1e3*2**c,3e4)});return{users:((r=n.data)==null?void 0:r.users)||[],userContext:(o=n.data)==null?void 0:o.userContext,total:((l=n.data)==null?void 0:l.total)||0,isLoading:n.isLoading,isError:n.isError,isFetching:n.isFetching,error:n.error,refetch:n.refetch}}function we(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=ee.DASHBOARD,userType:o,tenantId:l}=t,c=M.useMemo(()=>({search:a,active:!0,...o?{type:o}:{},...o==="tenant"&&l?{tenantId:l}:{}}),[a,o,l]),{users:i,isLoading:d,isError:u}=fr(c),m=Xa(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function gr({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var W,V;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),f=s.useShareSelectedUsers(),p=s.useShareUsersToRemove(),g=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),v=s.useShareOrgWideRole(),j=s.useShareManagementActions(),[b,C]=M.useState("specific_users"),R=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},E=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:N,isLoadingUsers:D}=we({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:R(),tenantId:E()});M.useEffect(()=>{j.setCurrentContext("org-tab"),j.setCurrentMode(b==="all_users"?"allOrgUsers":"specificOrgUsers")},[j,b]);const w=$=>{var U,H;const q=$;if(C(q),r==null||r(q),j.setCurrentContext("org-tab"),q==="specific_users")j.setCurrentMode("specificOrgUsers");else if(q==="all_users"){j.setCurrentMode("allOrgUsers");const Q=(H=(U=N==null?void 0:N.shares)==null?void 0:U.orgUsersOnly)==null?void 0:H[0];Q&&Q.role!==void 0&&j.setOrgWideRole(Q.role)}},L=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),k=S.filter($=>f.some(q=>q.id===$.id)),O=$=>{var Q,G;const q=f.some(Z=>Z.id===$),U=p.includes($),H=(G=(Q=N==null?void 0:N.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===$);q?j.removeSelectedUser($):U?j.removeUserFromRemove($):H||j.addSelectedUser({id:$,role:"VIEWER"})},A=($,q)=>{j.updateSelectedUserRole($,q)},I=$=>{j.addUserToRemove($),j.removeSelectedUser($)},y=$=>{j.removeUserFromRemove($)},T=$=>{j.removeUserFromUpdate($)},F=($,q)=>{j.setOrgWideRole(q)},z=()=>{j.setOrgWideRole((_==null?void 0:_.role)||"NONE")},_=(V=(W=N==null?void 0:N.shares)==null?void 0:W.orgUsersOnly)==null?void 0:V[0];M.useEffect(()=>{b==="all_users"&&_&&_.role!==void 0&&j.setOrgWideRole(_.role)},[b,_,j]);const P=D,Y=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(Kt,{shareType:b,onShareTypeChange:w,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(Se,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(je,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),b==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(_t,{value:u,onChange:m}),e.jsx(Vt,{selectedUsers:f,selectedUserObjects:k,onRemove:O,onRoleChange:A,getRoleOptions:De}),e.jsx(Ut,{usersToRemove:p,allUsers:L,onRemove:y}),e.jsx($t,{usersToUpdate:g,allUsers:L,onRemove:T,getRoleOptions:De}),e.jsx(Ht,{existingShares:N,isInitialLoading:P,isSearching:Y,resource:t,onShare:()=>{},getRoleOptions:De,allUsers:L,currentUser:n,handleUserToggle:O,handleUserRoleChange:A,handleRemoveAccess:I,handleUpdateAccess:($,q,U)=>{j.addUserToUpdate({id:$,currentRole:q,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Qt,{currentUser:n,currentShare:_,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:F,onRemoveAccess:z,allUsersToUpdate:x==="allOrgUsers"&&v!==((_==null?void 0:_.role)||"NONE")?{currentRole:(_==null?void 0:_.role)||"NONE",newRole:v}:null,allUsersToRemove:x==="allOrgUsers"&&(_==null?void 0:_.role)===void 0})})]}):null}function ut({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var Q;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),g=s.useShareTenantWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareSelectedTenant(),j=s.useShareManagementActions(),{data:b,isLoading:C}=qa({enabled:(n==null?void 0:n.type)==="organization"}),[R,E]=M.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),j.setCurrentMode("specificTenantUsers")):(j.setCurrentContext("tenant-tab"),j.setCurrentMode("allTenants"))},[j,n==null?void 0:n.type]);const S=G=>{var te,ae,se,oe;E(G);let Z;if(G==="specific_tenant_users"?Z="specific_users":G==="all_tenant_users"||G==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"&&(j.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&j.setSelectedTenant(n.tenantId))):(j.setCurrentContext("tenant-tab"),G==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):G==="all_tenant_users"?j.setCurrentMode("allTenantUsers"):G==="all_tenants"&&j.setCurrentMode("allTenants")),G==="all_tenant_users"){const K=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0];K&&K.role!==void 0&&j.setTenantWideRole(K.role)}else if(G==="all_tenants"){const K=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:oe[0];K&&K.role!==void 0&&j.setAllTenantsRole(K.role)}},N=G=>{j.setSelectedTenant(G)},{allUsers:D,existingShares:w,isLoadingUsers:L,isErrorLoadingUsers:k,isLoadingShares:O,isErrorLoadingShares:A}=we({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:v}),I=G=>{var se,oe;const Z=m.some(K=>K.id===G),te=h.includes(G),ae=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.specificTenantUsers)==null?void 0:oe.some(K=>K.tenantUserId===G);Z?j.removeSelectedUser(G):te?j.removeUserFromRemove(G):ae||j.addSelectedUser({id:G,role:"VIEWER"})},y=(G,Z)=>{j.updateSelectedUserRole(G,Z)},T=G=>{j.addUserToRemove(G),j.removeSelectedUser(G)},F=G=>{j.removeUserFromRemove(G)},z=G=>{j.removeUserFromUpdate(G)},_=(G,Z,te)=>{j.addUserToUpdate({id:G,currentRole:Z,newRole:te})},P=(G,Z)=>{R==="all_tenant_users"?j.setTenantWideRole(Z):R==="all_tenants"&&j.setAllTenantsRole(Z)},Y=()=>{R==="all_tenant_users"?j.setTenantWideRole("VIEWER"):R==="all_tenants"&&j.setAllTenantsRole("VIEWER")},V=(()=>{var G,Z,te,ae;return p==="allTenants"?(Z=(G=w==null?void 0:w.shares)==null?void 0:G.allTenantsOnly)==null?void 0:Z[0]:p==="allTenantUsers"?(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0]:null})();M.useEffect(()=>{var G,Z,te,ae;if(R==="all_tenant_users"){const se=(Z=(G=w==null?void 0:w.shares)==null?void 0:G.tenantWide)==null?void 0:Z[0];se&&se.role!==void 0&&j.setTenantWideRole(se.role)}else if(R==="all_tenants"){const se=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.allTenantsOnly)==null?void 0:ae[0];se&&se.role!==void 0&&j.setAllTenantsRole(se.role)}},[R,w,j]);const $=D.filter(G=>m.some(Z=>Z.id===G.id)),q=L||O,U=k||A,H=()=>(n==null?void 0:n.type)==="tenant"||R==="all_tenants"?!0:v&&(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&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Kt,{shareType:R,onShareTypeChange:S,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(je,{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(Se,{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(at,{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(Se,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.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:v||"",onValueChange:N,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(Q=b==null?void 0:b.tenants)==null?void 0:Q.map(G=>e.jsx(s.SelectItem,{value:G.id,children:G.name},G.id))})]})]}),H()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(_t,{value:i,onChange:u}),e.jsx(Vt,{selectedUsers:m,selectedUserObjects:$,onRemove:G=>I(G),onRoleChange:y,getRoleOptions:De}),e.jsx(Ut,{usersToRemove:h,allUsers:D,onRemove:F}),e.jsx($t,{usersToUpdate:f,allUsers:D,onRemove:z,getRoleOptions:De}),e.jsx(Ht,{existingShares:w,isInitialLoading:!!q,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:De,allUsers:D,currentUser:n,handleUserToggle:I,handleUserRoleChange:y,handleRemoveAccess:T,handleUpdateAccess:_})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Qt,{currentUser:n,currentShare:V,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:P,onRemoveAccess:Y,allUsersToUpdate:p==="allTenantUsers"&&((V==null?void 0:V.role)===void 0||g!==V.role)||p==="allTenants"&&((V==null?void 0:V.role)===void 0||x!==V.role)?{currentRole:(V==null?void 0:V.role)||"VIEWER",newRole:p==="allTenantUsers"?g:x}:null,allUsersToRemove:p==="allTenantUsers"&&(V==null?void 0:V.role)===void 0||p==="allTenants"&&(V==null?void 0:V.role)===void 0})}):null}):(n==null?void 0:n.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(at,{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 Wt=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),o=s.useShareUsersToUpdate(),l=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),u=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:l,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,a,n,r,o,l,c,i,d]),m=M.useMemo(()=>f=>s.validateShareData(f),[]),h=M.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||o.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!l)return!1}else if(a==="specificTenantUsers")return l?n.length>0||r.length>0||o.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||o.length>0:!0}return!1},[t,a,n,r,o,l]);return{buildShareData:u,validateShareData:m,isCurrentStateValid:h,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:o,selectedTenant:l,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function mt({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:o,onShare:l,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const p=s.useShareSelectedTenant();s.useShareSelectedTab();const g=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),v=s.useShareTenantWideRole(),{buildShareData:j,validateShareData:b,isCurrentStateValid:C}=Wt(),R=n||r||o,E=()=>{var L,k,O,A;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 I=m.length+h.length+f.length;return I===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${I} user${I!==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 ${I} user${I!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const I=d.role;return g===I?"Remove Access":"Update Access"}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0)return"Share with All Tenants";const y=I.role;return x===y?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"Share with All Tenant Users";const y=I.role;return v===y?"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 I=m.length+h.length+f.length;return I===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${I} user${I!==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 ${I} user${I!==1?"s":""}`}return"Share"},S=()=>R||!t||i==="all_tenant_users"&&!p||i==="specific_tenant_users"&&!p?!0:!C,N=()=>{const L=j();L&&b(L)&&l(L)},D=()=>{var L,k,O,A;if(i==="all_users")if(!d||d.role===void 0){const I=j();I&&b(I)&&l(I)}else{const I=d.role;if(g===I)u==null||u();else{const T=j();if(T&&b(T)){const F={...T,updateAccess:!0};l(F)}}}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&l(y)}else{const y=I.role;if(x===y)u==null||u();else{const F=j();if(F&&b(F)){const z={...F,updateAccess:!0};l(z)}}}}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0){const y=j();y&&b(y)&&l(y)}else{const y=I.role;if(v===y)u==null||u();else{const F=j();if(F&&b(F)){const z={...F,updateAccess:!0};l(z)}}}}},w=()=>{var L,k,O,A;if(i==="all_users"){if(!d||d.role===void 0)return"default";const I=d.role;return g===I?"destructive":"default"}else if(i==="all_tenants"){const I=(k=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:k[0];if(!I||I.role===void 0)return"default";const y=I.role;return x===y?"destructive":"default"}else if(i==="all_tenant_users"){const I=(A=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:A[0];if(!I||I.role===void 0)return"default";const y=I.role;return v===y?"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:N,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(qe,{className:"mr-2 h-4 w-4"}),!R&&E()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:D,disabled:S(),variant:w(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(je,{className:"mr-2 h-4 w-4"}),!R&&E()]})]})}function jr({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:o,onClose:l,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:p,isCurrentStateValid:g}=Wt(),x=a||n||r,v=()=>{if(x)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const E=d.length+u.length+m.length;return E===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${E} user${E!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const E=i.role;return h===E?"Remove Access":"Update Access"}return"Share"},j=()=>x||!t?!0:!g,b=()=>{const E=f();E&&p(E)&&o(E)},C=()=>{if(!i||i.role==="NONE"){const E=f();E&&p(E)&&o(E)}else{const E=i.role;if(h===E){const N=f();if(N&&p(N)){const D={...N,removeAccess:!0};o(D)}}else{const N=f();if(N&&p(N)){const D={...N,updateAccess:!0};o(D)}}}},R=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:l,disabled:x,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.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(qe,{className:"mr-2 h-4 w-4"}),!x&&v()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:C,disabled:j(),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(qe,{className:"mr-2 h-4 w-4"}),!x&&v()]})]})}function Jt({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:o,onClose:l,onShare:c,onRemoveAccess:i}){var N,D,w,L;const{currentUser:d}=cs(),[u,m]=M.useState("specific_users"),[h,f]=M.useState("specific_users"),p=s.useShareManagementActions(),g=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:v}=we({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:j}=we({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),b=(D=(N=v==null?void 0:v.shares)==null?void 0:N.tenantWide)==null?void 0:D[0],C=(L=(w=j==null?void 0:j.shares)==null?void 0:w.orgUsersOnly)==null?void 0:L[0],R=()=>{if(g==="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"}},E=M.useCallback(()=>{p.resetShareState(),l()},[p,l]),S=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:E,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(qe,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:S?"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."})]}),S?e.jsxs(s.Tabs,{value:g,onValueChange:k=>{const O=k;p.setSelectedTab(O),p.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(gr,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:f,isSharing:n,isUpdating:o,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(ut,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:k=>m(k),isSharing:n,isUpdating:o,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(ut,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:k=>m(k),isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?g==="org"?e.jsx(mt,{resource:t,existingShares:j,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:h,currentAllUsersShare:C,onRemoveAccess:i}):e.jsx(mt,{resource:t,existingShares:v,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:R(),currentAllUsersShare:b,onRemoveAccess:i}):e.jsx(jr,{resource:t,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:u,currentAllUsersShare:b,onRemoveAccess:i})})]})})}function me(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Ce(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Yt(t,a){const{resourceType:n,resourceId:r,shareMutation:o,removeMutation:l,existingShares:c,resetUserSelections:i}=a;if(r)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const d=me(n,r,[{scope:"org_users_only",role:t.orgWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m}=t;if(d&&d.length>0){const h=me(n,r,d.map(f=>({scope:"specific_org_user",orgUserId:f.id,role:f.role})));o(h,{onSuccess:()=>{i()}})}if(u&&u.length>0){const h=Ce(n,r,u.map(f=>{var g,x;const p=(x=(g=c==null?void 0:c.shares)==null?void 0:g.specificOrgUsers)==null?void 0:x.find(v=>v.orgUserId===f);return{scope:"specific_org_user",orgUserId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));l(h,{onSuccess:()=>{i()}})}m&&m.length>0&&m.forEach(h=>{const f=me(n,r,[{scope:"specific_org_user",orgUserId:h.id,role:h.newRole}]);o(f,{onSuccess:()=>{i()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const d=me(n,r,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="allTenantUsers"){const d=me(n,r,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m,tenantId:h}=t;if(u&&u.length>0){const f=Ce(n,r,u.map(p=>{var x,v;const g=(v=(x=c==null?void 0:c.shares)==null?void 0:x.specificTenantUsers)==null?void 0:v.find(j=>j.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,tenantId:h,role:(g==null?void 0:g.role)||"VIEWER"}}));l(f,{onSuccess:()=>{i()}})}if(m&&m.length>0&&m.forEach(f=>{const p=me(n,r,[{scope:"specific_tenant_user",tenantUserId:f.id,tenantId:h,role:f.newRole}]);o(p,{onSuccess:()=>{i()}})}),d&&d.length>0){const f=me(n,r,d.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.role})));o(f,{onSuccess:()=>{i()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const d=Ce(n,r,[{scope:"all_tenant_users",role:"VIEWER"}]);l(d,{onSuccess:()=>{i()}})}else if(t.updateAccess){const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else{const d=me(n,r,[{scope:"all_tenant_users",role:t.tenantWideRole}]);o(d,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:d,usersToRemove:u,usersToUpdate:m}=t;if(d&&d.length>0){const h=me(n,r,d.map(f=>({scope:"specific_tenant_user",tenantUserId:f.id,role:f.role})));o(h,{onSuccess:()=>{i()}})}if(u&&u.length>0){const h=Ce(n,r,u.map(f=>{var g,x;const p=(x=(g=c==null?void 0:c.shares)==null?void 0:g.specificTenantUsers)==null?void 0:x.find(v=>v.tenantUserId===f);return{scope:"specific_tenant_user",tenantUserId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));l(h,{onSuccess:()=>{i()}})}m&&m.length>0&&m.forEach(h=>{const f=me(n,r,[{scope:"specific_tenant_user",tenantUserId:h.id,role:h.newRole}]);o(f,{onSuccess:()=>{i()}})})}break}}function Xt(t,a,n,r){var u,m,h,f,p,g;const{resourceType:o,resourceId:l,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(l)if(t.length>0){const x=Ce(o,l,t.map(v=>{var b,C;const j=(C=(b=i==null?void 0:i.shares)==null?void 0:b.specificTenantUsers)==null?void 0:C.find(R=>R.tenantUserId===v);return{scope:"specific_tenant_user",tenantUserId:v,role:(j==null?void 0:j.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:v=>{console.error("Remove access failed:",v)}})}else{const x=a==="tenant"&&n==="allTenants",v=a==="tenant"&&n==="allTenantUsers";if(x){const j=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(j){const b=Ce(o,l,[{scope:"all_tenants_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenants access failed:",C)}})}}else if(v){const j=(f=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:f[0];if(j){const b=Ce(o,l,[{scope:"all_tenant_users",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove all-tenant-users access failed:",C)}})}}else{const j=(g=(p=i==null?void 0:i.shares)==null?void 0:p.orgUsersOnly)==null?void 0:g[0];if(j){const b=Ce(o,l,[{scope:"org_users_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove org-wide access failed:",C)}})}}}}function yr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=we({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.DASHBOARD,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(h=>{if(!t)return;const f={resourceType:ee.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Yt(h,f)},[t,a,n,i,d]),m=M.useCallback(()=>{if(!t)return;const h={resourceType:ee.DASHBOARD,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(o,l||"",c||"",h)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:m}}function vr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=we({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.VISUAL,userType:"tenant"}),d=M.useCallback(()=>{r.resetUserSelections()},[r]),u=M.useCallback(h=>{if(!t)return;const f={resourceType:ee.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Yt(h,f)},[t,a,n,i,d]),m=M.useCallback(()=>{if(!t)return;const h={resourceType:ee.VISUAL,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(o,l||"",c||"",h)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:m}}function br(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),o=t.toUpperCase().indexOf("ORDER BY");let l=t.length;if(o!==-1&&(l=o),r!==-1&&r<l&&(l=r),a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,l),i=t.substring(l);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Fs(t){const[a,n]=M.useState(null),[r,o]=M.useState(null);return M.useEffect(()=>{if(!t||t.trim()===""){n(null),o(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),o(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),o(i),n(null)}})()},[t]),a}function Nr(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const l=r.split("__")[0],c=t.find(i=>i.tabTitle===l);return c?c.id:t[0].id}return a}}return t[0].id}async function ht(t,a,n){if(!t||!a)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",a],o=n.getQueryData(r);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const l=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return n.setQueryData(r,i),s.ue.dismiss(l),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(l),c}}function Cr(t,a,n,r,o){const l=t.frameObject;a(l);const c=l.cards.find(i=>i.id===l.activeCardId);c&&n(c),r(!0),o(!0)}function Sr(){var f;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),r=Fs(((f=n.customCardPreferences)==null?void 0:f.url)||""),o=s.useEditorStore(p=>p.selectedSchemaName),l=s.useEditorStore(p=>p.selectedDatamodelId),c=s.useEditorStore(p=>p.selectedDatabaseName),i=s.useEditorStore(p=>p.selectedTableName),d=s.useEditorStore(p=>p.selectedConnectionId),u=s.useEditorStore(p=>p.isShowingVisual),m=n.sql;return{getUpdatedFrame:M.useCallback(()=>{var j;let p=m;m&&!m.includes("{{")&&(p=br(m),t(p));const g=(j=r==null?void 0:r.getState())==null?void 0:j.settings,x={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:o,lastSelectedDatamodelId:l,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:p,customCfg:u?n.customCfg:null,...g&&{customCardPreferences:{...n.customCardPreferences,settings:g}}},v=a.cards.map(b=>b.id===n.id?x:b);return{...a,cards:v,activeCardId:Nr(v,a.activeCardId)}},[n,a,u,o,l,c,i,d,t,r,m])}}function zs(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient(),n=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:o,setCard:l}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:u,setIsDashboardPanelOpen:m}=s.useDashboardActions(),h=s.useDashboardStore(x=>x.selectedSheetId),f=er((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),p=M.useCallback(async x=>{try{r(x);const{data:v,fromCache:j}=await ht((t==null?void 0:t.accessToken)||"",x.id,a);return Cr(v,o,l,c,i),{success:!0,fromCache:j}}catch(v){return console.error("Error editing visual:",v),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,o,l,c,i]),g=M.useCallback(async x=>{try{if(r(x),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:v,fromCache:j}=await ht((t==null?void 0:t.accessToken)||"",x.id,a),b=v.frameObject;if(!b)return{success:!1,error:"Visual has no frame data"};const C={...b,id:s.v4()};return u(h,C,"end"),c(!0),d(C.id),m(!1),{success:!0,fromCache:j}}catch(v){return console.error("Error adding visual:",v),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,h,u,c,d,m]);return{visual:f.data,isLoading:f.isLoading,isError:f.isError,error:f.error,handleEditLibraryVisual:p,handleAddLibraryVisual:g,getUpdatedFrame:Sr().getUpdatedFrame,refetch:f.refetch}}function wr(){const[t,a]=M.useState(""),[n,r]=M.useState(!1),[o,l]=M.useState(""),[c,i]=M.useState(""),[d,u]=M.useState(!1),[m,h]=M.useState(null),[f,p]=M.useState(!1),[g,x]=M.useState(null),[v,j]=M.useState(null),{setIsDashboardEditing:b,setIsVisualEditing:C}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:E}=zs(),{resources:S,isLoading:N,isError:D,createResource:w,updateResource:L,deleteResource:k,duplicateResource:O,shareResource:A,isCreating:I,isDeleting:y,removeResourceShares:T,isSharing:F,isRemovingShares:z,isUpdatingShares:_}=tr(()=>{p(!1),x(null)},()=>{r(!1),l(""),i("")}),{handleShareSubmit:P,handleRemoveAccess:Y}=vr((m==null?void 0:m.id)||null,A,T);cs();const W=S.filter(B=>{var J,ie;return((J=B==null?void 0:B.title)==null?void 0:J.toLowerCase().includes(t.toLowerCase()))||((ie=B==null?void 0:B.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),V=B=>new Date(B).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{o.trim()&&w({title:o,description:c,isPrivate:!1})},q=B=>{x(B),p(!0)},U=()=>{g&&k(g.id)},{startUpdating:H,stopUpdating:Q,isUpdating:G}=zt(),Z=(B,J)=>{const ie=J.title!==void 0?"title":"description";H(B,ie),L({resourceId:B,data:J},{onSuccess:()=>{Q(B,ie)},onError:()=>{Q(B,ie)}})},te=B=>{j(B),O(B,{onSettled:()=>j(null)})},ae=B=>{R(B)},se=B=>{E(B)},oe=B=>{const J=S.find(ie=>ie.id===B);J&&L({resourceId:B,data:{isPrivate:!J.isPrivate}})},K=B=>{h(B),u(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),we({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:ee.VISUAL,userType:"tenant"}),N?e.jsx(Ft,{}):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:n?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:o,onChange:B=>l(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:B=>i(B.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||I,children:I?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),l(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:I,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),I?"Creating...":"Create New Visual"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:B=>a(B.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:W.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(is,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):W.map(B=>e.jsx(ar,{visual:B,onAddVisual:se,onEditVisual:ae,onUpdateVisual:Z,onDeleteClick:q,onDuplicateVisual:te,onTogglePrivacy:oe,onShareVisual:K,isDeleting:y,isDuplicating:v===B.id,isTitleUpdating:G(B.id,"title"),isDescriptionUpdating:G(B.id,"description"),formatDate:V},B.id))})}),d&&m&&e.jsx(Jt,{resource:m,resourceType:ee.VISUAL,onShare:P,isSharing:F,isRemoving:z,isUpdating:_,onClose:()=>{u(!1),h(null)},onRemoveAccess:Y}),e.jsx(s.AlertDialog,{open:f,onOpenChange:B=>{!B&&y||(p(B),B||x(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',g==null?void 0:g.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:y,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:B=>{B.preventDefault(),B.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,children:y?"Deleting...":"Delete"})]})]})})]})}function kr({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onLoadDashboard:l,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var E;const{selectDashboard:f}=s.useManagementActions(),p=s.useIsDashboardSelected(t.id),[g,x]=M.useState(!1),[v,j]=M.useState(!1);M.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Et,{className:"h-3 w-3 text-purple-500"}):e.jsx(je,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(Se,{className:"h-3.5 w-3.5 text-slate-500"}),C=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),R=()=>{f(t),l(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",p&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:R,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:C()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:S=>c==null?void 0:c(t.id,{title:S}),isEditable:t.permissions.canEdit&&p,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"line-clamp-1 max-w-[220px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:b()})]}),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:S=>c==null?void 0:c(t.id,{description:S}),isEditable:t.permissions.canEdit&&p,isPending:o,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:g,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:S=>S.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:S=>{S.preventDefault(),S.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),u(t)},children:[e.jsx(je,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),i(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{className:"h-3 w-3"}),e.jsx("span",{children:((E=t.ownership.createdBy)==null?void 0:E.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 Dr({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 Er(t){const[a,n]=M.useState(""),[r,o]=M.useState(!1),[l,c]=M.useState(""),[i,d]=M.useState(""),[u,m]=M.useState(!1),[h,f]=M.useState(null),[p,g]=M.useState(!1),[x,v]=M.useState(null),[j,b]=M.useState(null),C=s.useManagementStore(K=>K.lastSelectedDashboard),R=s.useManagementStore(K=>K.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:E,isLoading:S,isError:N,createResource:D,updateResource:w,deleteResource:L,duplicateResource:k,isCreating:O,isDeleting:A,isSharing:I,isRemovingShares:y,isUpdatingShares:T,shareResource:F,removeResourceShares:z}=sr(()=>{g(!1),v(null),C&&R(C)},()=>{o(!1),c(""),d("")}),{handleShareSubmit:_,handleRemoveAccess:P}=yr((h==null?void 0:h.id)||null,F,z),{currentUser:Y}=cs(),W=E.filter(K=>{var B,J;return((B=K==null?void 0:K.title)==null?void 0:B.toLowerCase().includes(a.toLowerCase()))||((J=K==null?void 0:K.description)==null?void 0:J.toLowerCase().includes(a.toLowerCase()))}),V=K=>new Date(K).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{l.trim()&&D({title:l,description:i,isPrivate:!1})},q=K=>{var B;(B=t.onLoadDashboard)==null||B.call(t,K)},U=K=>{v(K),g(!0)},H=()=>{x&&L(x.id)},Q=K=>{b(K),k(K,{onSettled:()=>b(null)})},{startUpdating:G,stopUpdating:Z,isUpdating:te}=zt(),ae=(K,B)=>{const J=B.title!==void 0?"title":"description";G(K,J),w({resourceId:K,data:B},{onSuccess:()=>{Z(K,J)},onError:()=>{Z(K,J)}})},se=K=>{const B=E.find(J=>J.id===K);B&&w({resourceId:K,data:{isPrivate:!B.isPrivate}})},oe=K=>{f(K),Y==null||Y.type,m(!0)};return we({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ee.DASHBOARD,userType:"tenant"}),S?e.jsx(Ft,{}):N?e.jsx(Dr,{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:l,onChange:K=>c(K.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:K=>d(K.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()||O,children:O?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{o(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:O,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>o(!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:a,onChange:K=>n(K.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:W.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ra,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):W.map(K=>e.jsx(kr,{dashboard:K,isDeleting:A,isDuplicating:j===K.id,isTitleUpdating:te(K.id,"title"),isDescriptionUpdating:te(K.id,"description"),onLoadDashboard:q,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ae,onDeleteClick:U,onDuplicateDashboard:Q,onTogglePrivacy:se,onShareDashboard:oe,formatDate:V,onDashboardItemClick:t.onDashboardItemClick},K.id))})}),u&&h&&e.jsx(Jt,{resource:h,resourceType:ee.DASHBOARD,onShare:_,isSharing:I,isRemoving:y,isUpdating:T,onClose:()=>{m(!1),f(null)},onRemoveAccess:P}),e.jsx(s.AlertDialog,{open:p,onOpenChange:K=>{!K&&A||(g(K),K||v(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:K=>{K.preventDefault(),K.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function Zt({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(p=>p.dashboard);const{setDashboard:o,addSheet:l}=s.useDashboardStore(p=>p.actions),{currentUser:c}=cs(),i=c,[d,u]=s.useLocalStorageState("resource-management-active-tab","dashboards"),m=qt(a,{enabled:t}),h=p=>{},f=p=>{console.log("Editing dashboard:",p)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:m,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"-translate-x-full",n),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children: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:a,tooltip:"Hide Dashboard Management",children:e.jsx(s.X,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:d,onValueChange:u,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(Er,{onLoadDashboard:h,onEditDashboard:f,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(wr,{})})]})})]})})}function Tr(){const{authToken:t,tokenProps:a}=s.useSemaphorContext();s.useDashboardStore(T=>T.theme);const n=s.useDashboardStore(T=>T.lenses),r=s.useDashboardStore(T=>T.selectedLensId),o=n==null?void 0:n.find(T=>T.id===r),l=s.useDashboardStore(T=>T.dashboard);s.useDashboardStore(T=>T.selectedSheetId);const c=s.useDashboardStore(T=>T.isDashboardEditing),i=s.useEditorStore(T=>T.card),d=s.useEditorStore(T=>T.selectedConnectionId),[u,m]=M.useState(!1),h=s.useDashboardStore(T=>T.isDashboardPanelOpen),f=s.useDashboardStore(T=>T.actions.setIsDashboardPanelOpen),p=s.useDashboardStore(T=>T.filterValues),g=s.useDashboardStore(T=>T.isVisualEditing),x=s.useDashboardStore(T=>T.showFilters);s.useDashboardStore(T=>T.showDashboardJSON);const v=s.useDashboardStore(T=>T.onSaveFunction),j=s.useDashboardStore(T=>T.actions.setShowFilters),{addFrame:b,setSelectedFrameId:C}=s.useDashboardStore(T=>T.actions),{getSelectedSheet:R,setIsDashboardEditing:E,setShowDashboardJSON:S}=s.useDashboardStore(T=>T.actions),N=R(),{tenantId:D,endUserId:w}=M.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),L=M.useMemo(()=>D||w,[D,w]),k=()=>{if(!c||!N)return;const T={dataSource:i.dataSource,mode:"explorer",connectionId:d,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},F={id:s.v4(),cards:[T],activeCardId:T.id};b(N.id,F),C(F.id)},O=()=>{E(!0)};async function A(){if(m(!0),!r||!o)return;const T=Bs(l),F=JSON.stringify(T),z={...o,template:F,filterValues:p};await Cs(z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),v==null||v(T),m(!1)}if(g)return null;const I=(o==null?void 0:o.name)||l.title,y=a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail;return e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[y&&e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(ca,{className:"h-4 w-4"})}),!g&&e.jsx(s.Label,{children:I})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!g&&e.jsx(La,{}),!g&&e.jsx(Bt,{}),c&&!g&&L&&e.jsx(Aa,{}),!g&&L&&e.jsx(Ma,{}),c&&!g&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:k,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!g&&e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2",onClick:O,size:"sm",children:e.jsx(s.Pencil,{className:"h-4 w-4"})}),c&&!g&&e.jsx(s.IconButton,{className:"h-7 p-2",onClick:()=>{E(!1),S(!1)},children:e.jsx(s.Cross2Icon,{className:"h-4 w-4"})}),c&&!g&&L&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",disabled:u,onClick:A,size:"sm",children:e.jsx(It,{className:"h-4 w-4"})}),!x&&!g&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>j(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!g&&c&&!1,!g&&!1,!g&&e.jsx(Zt,{isOpen:h,onClose:()=>f(!1)})]})]})}function Ir({name:t,items:a,value:n,onChange:r,isLoading:o,isError:l,refetch:c,className:i,icon:d,showNone:u=!1}){const m=ue.useRef(null),[h,f]=ue.useState(!1),[p,g]=ue.useState("100%"),x=u?[...a||[],{id:"none",name:"None"}]:a;ue.useLayoutEffect(()=>{m.current&&g(m.current.offsetWidth)},[]);function v(){var b;return o?"Loading...":l?"Error":n?(b=a==null?void 0:a.find(C=>C.id===n))==null?void 0:b.name:`Select ${t}`}function j(b,C){r(C),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:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:v()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:p},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(Tt,{className:s.cn("size-3.5 opacity-50",o&&"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:C=>j(C,b.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===b.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:b.name,children:b.name})]})},b.id))})]})]})})]})}function ze({title:t,items:a,value:n,isLoading:r,isError:o,refetch:l,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":o?"Error":n;function f(){if(t==="Connection")return e.jsx(va,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(ja,{className:"size-4"});if(t==="Table")return e.jsx(ls,{className:"size-4"});if(t==="Model")return e.jsx(Hn,{className:"size-4"})}function p(){return e.jsxs(s.Select,{disabled:u,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":o?"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(Tt,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:l})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((x,v)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},v))]}),(r||o)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function g(){return e.jsx(Ir,{icon:f(),items:a,value:h,onChange:c||(()=>{}),isLoading:r,isError:o,refetch:l,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"?p():g()})})}function Ar({column:t}){const[a,n]=M.useState(!1),r=s.useEditorStore(x=>x.selectedTableName),o=s.useEditorStore(x=>x.selectedSchemaName),l=s.useEditorStore(x=>x.selectedDatabaseName),c=s.useEditorStore(x=>x.selectedDatamodelId),i=s.useEditorStore(x=>x.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),f=s.useEditorStore(x=>x.actions.setRunSql);function p(x,v){var R;const j=s.createSqlGenConfig(x,i,v),b=(R=d==null?void 0:d.find(E=>E.id===c))==null?void 0:R.name;m(j);const C=s.getSql(j,s.fmt(o||""),s.fmt(r),b||"",u,l||"");C&&(h(C),f(!0)),n(!1)}function g(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>p(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>p(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>p(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>p(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>p(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:g()})]})}function Ps({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(Ue,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(Ze,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Kn,{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 xs({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(Ps,{column:t}),e.jsx("span",{children:t.column_name})]})}function Mr({id:t,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:l,transform:c}=s.useDraggable({id:t,data:{type:n}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:l,style:i,...o,...r,children:a})}function Lr({onClick:t,column:a}){const n=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}function u(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(a),className:s.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(xs,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(xs,{column:a})}),e.jsx(Mr,{id:a.column_name,type:"column",children:e.jsx(xs,{column:a})})]})}const ps={id:"__placeholder__",role:"groupby",type:"string"},fs={id:"__placeholder__",role:"groupby",type:"string"},gs={id:"__placeholder__",role:"metric",type:"number"},js={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},en={id:"__placeholder__"},Ee="droppable-group-by",Te="droppable-metrics",Ie="droppable-pivot-by",ss="sortable-group-by",Ss="sortable-metrics",ts="sortable-pivot-by",ws="droppable-filters",ks="sortable-filters",_s="sortable-order-by";function Rr(){const t=s.useDndStore(I=>I.insertIndex),a=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.groupByColumns)||[]}),n=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.metricColumns)||[]}),r=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.filterColumns)||[]}),o=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.orderBy)||[]}),l=s.useEditorStore(I=>{var y;return((y=I.card.queryConfig)==null?void 0:y.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:f,setMetricColumns:p,setFilterColumns:g,setOrderByColumns:x,setPivotByColumns:v}=s.useEditorActions(),{columns:j}=s.useDataColumns(),{formattedTableName:b}=s.useEditorAside(),C=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=I=>{var F;const{active:y,over:T}=I;if(((F=y.data.current)==null?void 0:F.type)==="column"&&T){const z=T.id,_=j.find(V=>V.column_name===y.id);if(!_)return;const P=s.isNumberDataType(_.data_type),Y=s.isTextDataType(_.data_type),W=s.isDateDataType(_.data_type);if(Y||W){if(a.some($=>$.id===z)){const $=a.findIndex(U=>U.id===z);c($);const q=a.filter(U=>U.id!==ps.id);q.splice($,0,ps),d(q)}else if(T.id===Ee){c(a.length);const $=[...a,ps];d($),u(n),m(r)}}if(Y||W){if(l.some($=>$.id===z)){const $=l.findIndex(U=>U.id===z);c($);const q=l.filter(U=>U.id!==fs.id);q.splice($,0,fs),h(q)}else if(T.id===Ie){c(l.length);const $=[...l,fs];h($),d(a),u(n),m(r)}}if(P||Y){if(n.some($=>$.id===z)){console.log("isOverMetricSortable",z);const $=n.findIndex(U=>U.id===z);c($);const q=n.filter(U=>U.id!==gs.id);q.splice($,0,gs),u(q)}else if(T.id===Te){c(n.length);const $=[...n,gs];u($),m(r),d(a),h(l)}}if(S(_)){if(r.some($=>$.id===z)){const $=r.findIndex(U=>U.id===z);c($);const q=r.filter(U=>U.id!==js.id);q.splice($,0,js),m(q)}else if(T.id===ws){c(r.length);const $=[...r,js];m($),u(n),d(a),h(l)}}}else d(a),u(n),m(r),h(l)};function E(I){i(I.active.id),c(null),d(a),u(n),m(r),h(l)}function S(I){return!r.some(y=>y.name===I.column_name)}function N(I,y="SUM"){const{column_name:T,data_type:F}=I,z=[...n],_=t!==null?t:n.length,P={...I,id:pe(T),name:T,label:He(T,y),type:F,role:"metric",aggregate:y};z.splice(_,0,P),p(z)}function D(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...l],F=t!==null?t:l.length;let z;y?z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(F,0,z),v(T)}function w(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...a],F=t!==null?t:a.length;let z;y?z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(F,0,z),f(T)}function L(I){const y=[...r],T=t!==null?t:r.length,F={...I,id:pe(I.column_name),name:I.column_name,type:I.data_type,sql:s.getDefaultFilterSql(I.data_type,b,s.fmt(I.column_name)),role:"filter"};y.splice(T,0,F),g(y)}function k(I){var z,_,P,Y,W,V,$,q;const{active:y,over:T}=I,F=y.data.current;if((F==null?void 0:F.type)==="column"&&T){const U=j.find(Z=>Z.column_name===y.id);if(!U)return;const H=s.isNumberDataType(U.data_type),Q=s.isTextDataType(U.data_type),G=s.isDateDataType(U.data_type);(Q||G)&&(T.id===Ee||((z=T.data.current)==null?void 0:z.type)===ss)&&w(U),(Q||G)&&(T.id===Ie||((_=T.data.current)==null?void 0:_.type)===ts)?D(U):(H||Q)&&(T.id===Te||((P=T.data.current)==null?void 0:P.type)===Ss)?(H&&N(U),Q&&N(U,"COUNT")):S(U)&&(T.id===ws||((Y=T.data.current)==null?void 0:Y.type)===ks)&&L(U)}if(T&&((W=T.data.current)==null?void 0:W.type)===ss&&a.some(U=>U.id===y.id)){const U=a.findIndex(Q=>Q.id===y.id),H=a.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...a],[G]=Q.splice(U,1);Q.splice(H,0,G),f(Q)}}if(T&&((V=T.data.current)==null?void 0:V.type)===ts&&l.some(U=>U.id===y.id)){const U=l.findIndex(Q=>Q.id===y.id),H=l.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...l],[G]=Q.splice(U,1);Q.splice(H,0,G),v(Q)}}if(T&&(($=T.data.current)==null?void 0:$.type)===Ss&&n.some(U=>U.id===y.id)){const U=n.findIndex(Q=>Q.id===y.id),H=n.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...n],[G]=Q.splice(U,1);Q.splice(H,0,G),p(Q)}}if(T&&((q=T.data.current)==null?void 0:q.type)===ks&&r.some(U=>U.id===y.id)){const U=r.findIndex(Q=>Q.id===y.id),H=r.findIndex(Q=>Q.id===T.id);if(U!==-1&&H!==-1&&U!==H){const Q=[...r],[G]=Q.splice(U,1);Q.splice(H,0,G),g(Q)}}O(I),i(null),c(null),d(a),u(n),m(r),h(l)}function O(I){const{active:y,over:T}=I,F=y.data.current;if((F==null?void 0:F.type)===_s&&T){const z=o.findIndex(P=>Ve(P.columnId)===y.id),_=o.findIndex(P=>Ve(P.columnId)===T.id);if(z!==-1&&_!==-1&&z!==_){const P=[...o],[Y]=P.splice(z,1);P.splice(_,0,Y),x(P)}}}function A(){i(null),c(null),d(a),u(n),m(r)}return{handleDragOver:R,handleDragEnd:k,handleDragStart:E,handleDragCancel:A,sensors:C}}function pe(t){return`${t}-${s.v4()}`}function He(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ve(t){return`${_s}-${t}`}function Pe(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Or({schemaName:t,tableName:a,columns:n,status:r}){const o=s.useEditorStore(y=>y.sqlGen),l=s.useEditorStore(y=>y.isDevMode),c=s.useEditorStore(y=>y.selectedConnectionId),i=s.useEditorStore(y=>{var T,F;return(F=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:F.metricColumns});s.useEditorStore(y=>{var T,F;return(F=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:F.groupByColumns});const d=s.useEditorStore(y=>y.selectedDatabaseName),u=s.useEditorStore(y=>y.selectedSchemaName),m=s.useEditorStore(y=>y.selectedTableName),h=s.useEditorStore(y=>y.selectedDatamodelId),f=s.useDashboardStore(y=>y.dashboard.aiScopeTables),{addToAIScope:p,removeFromAIScope:g}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:v,setCardSql:j,setRunSql:b,setSqlGen:C,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:E,modelItems:S,selectedDatamodelName:N}=s.useEditorAside();function D(y){var T;if(l){const F=s.createSqlGenConfig(y,o);C(F);const z=(T=S==null?void 0:S.find(P=>P.id===h))==null?void 0:T.name,_=s.getSql(F,s.fmt(t),s.fmt(a),z||"",E,d||"");_&&(j(_),b(!0))}if(!l){if(s.isTextDataType(y.data_type))if(i&&i.length>0){const F={...y,role:"groupby",id:pe(y.column_name),name:y.column_name,type:y.data_type};v(F)}else{const F={...y,role:"metric",id:pe(y.column_name),name:y.column_name,label:He(y.column_name,"COUNT"),type:y.data_type,aggregate:"COUNT"};x(F)}if(s.isDateDataType(y.data_type)){const F={...y,role:"groupby",id:pe(y.column_name),name:y.column_name,type:y.data_type,label:Pe(y.column_name,"month"),granularity:"month"};v(F)}if(s.isNumberDataType(y.data_type)){const F={...y,role:"metric",id:pe(y.column_name),name:y.column_name,label:He(y.column_name,"SUM"),type:y.data_type,aggregate:"SUM"};x(F)}}}function w(y){y===!0&&(m||N)&&c?(p({connectionId:c,connectionType:E==="S3"||E==="API"?"DuckDb":E||"",databaseName:d||"",schemaName:u||"",tableName:m||"",datamodelName:s.resolveDatamodelName(N),datamodelId:h||""}),s.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(g({connectionId:c||"",connectionType:E||"",tableName:m||"",datamodelName:s.resolveDatamodelName(N),datamodelId:h||"",databaseName:d||"",schemaName:u||""}),s.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function L(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:E,databaseName:d||""});R(!1);const T=E==="MSSQL"?`SELECT top 10 * FROM ${y}`:`SELECT * FROM ${y} LIMIT 10`;j(T),b(!0)}function k(){const y=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:N,connectionType:E,databaseName:d||""});j(`SELECT COUNT(*) as count FROM ${y}`),b(!0)}function O(){return(f==null?void 0:f.find(y=>y.connectionId===c&&(y.tableName===m||y.datamodelName===N)))!==void 0}function A(y){return l?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>D(y),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ps,{column:y}),e.jsx("span",{children:y.column_name})]}),e.jsx("div",{onClick:T=>T.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(y.data_type)&&e.jsx(Ar,{column:y})})]}):e.jsx(Lr,{onClick:D,column:y})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(s.Toggle,{title:`${O()?"Remove from":"Add to"} Assistant Scope`,pressed:O(),onPressedChange:w,variant:"outline",className:s.cn("h-9 px-2",{}),children:[e.jsx(s.Plus,{className:s.cn("mr-1 size-4",{"text-green-400":O(),"text-muted-foreground":!O()})}),"AI"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:L,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(xa,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:k,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(At,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((y,T)=>e.jsx(s.Skeleton,{className:"h-7 w-full"},T))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[l&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:I()}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(y=>e.jsx("div",{className:s.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:A(y)},y.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function sn({ColumnsComponent:t,type:a}){var ke;const n=s.useEditorStore(ne=>ne.card),r=s.useEditorStore(ne=>ne.selectedConnectionId),o=s.useDashboardStore(ne=>ne.showFilters),l=s.useEditorStore(ne=>ne.selectedDatamodelId),c=s.useEditorStore(ne=>ne.selectedDatabaseName),i=s.useEditorStore(ne=>ne.selectedSchemaName),d=s.useEditorStore(ne=>ne.selectedTableName),u=s.useEditorStore(ne=>ne.isDevMode),{setSelectedTableName:m,setIsDevMode:h,setCardSql:f}=s.useEditorActions(),{connectionItems:p,modelItems:g,schemaItems:x,databaseItems:v,tableItems:j,columns:b,isConnectionsLoading:C,isModelsLoading:R,isConnectionsError:E,isModelsError:S,isDatabasesLoadingOrFetching:N,isDatabaseError:D,isSchemaLoadingOrFetching:w,isSchemaError:L,isColumnsError:k,isColumnsLoadingOrFetching:O,isTableLoadingOrFetching:A,isTableError:I,connectionType:y,isNonDbConnection:T,refetchDatabases:F,refetchModels:z,refetchSchemas:_,refetchTables:P,refetchColumns:Y,refetchConnections:W,handleConnectionChange:V,handleDatabaseChange:$,handleSchemaChange:q,handleDatamodelChange:U,handleTableChange:H,tableName:Q,schemaName:G}=s.useEditorAside(),{data:Z,refetch:te}=s.useDashboardCardQuery(n);function ae(){return t?t(G,Q,b):e.jsx(Or,{schemaName:G,tableName:Q,columns:b,status:O?"Loading...":k?"Error":"Success"})}function se(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function oe(ne){ne===!0?Z&&(f(Z.userSql),setTimeout(()=>{te()},100)):f(""),h(ne)}function K(){if(!r||y==="S3"||y==="API")return null;if(!l||l==="none")return e.jsx(ze,{refetch:F,showNone:!0,onChange:$,isError:D,isLoading:N,items:v,value:c||"",title:"Database",type:"combobox"})}function B(){if(r&&!T&&(!c||c==="none")&&(!l||l==="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 J(){if(!r||y==="S3"||y==="API")return null;if(!c||c==="none")return e.jsx(ze,{refetch:z,showNone:!0,onChange:U,isError:S,isLoading:R,items:g,value:l||"",title:"Model",type:"combobox"})}function ie(){return!r||y==="S3"||y==="API"||!c||c==="none"?null:e.jsx(ze,{refetch:_,onChange:q,isError:L,isLoading:w,items:x,value:i||"",title:"Schema",type:"combobox"})}function ye(){function ne(){let le=!1;return y==="API"?(le=!1,le):((y==="S3"||r&&c&&c!=="none"&&i)&&(le=!0),le)}return ne()?e.jsx(ze,{refetch:P,onChange:H,isError:I,items:j,isLoading:A,value:d||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(ze,{refetch:W,items:p,title:"Connection",value:r||"",onChange:V,isLoading:C,isError:E,type:"combobox",connectionTooltip:((ke=p==null?void 0:p.find(ne=>ne.id===r))==null?void 0:ke.type)||""}),K(),B(),J(),ie(),ye()]}),ae(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:u,onCheckedChange:oe,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:se,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(fa,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function tn({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,l]=M.useState(!1),c=M.useRef(null),i=M.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(f){(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d())}function m(){const f=window.getSelection();if(f&&f.toString().trim()!==""){const p=f.toString();navigator.clipboard.writeText(p),l(!0),i.current=!0,setTimeout(()=>{l(!1),i.current=!1},1e3)}else i.current=!1}function h(){l(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),o&&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 nn({sql:t,error:a,onDebugWithAssistant:n}){const r=s.useEditorStore(d=>d.isDevMode),{setIsDevMode:o,setCardSql:l,setRunSql:c}=s.useEditorActions();function i(){o(!r),l(t),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(tn,{error:a}),t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!r&&t&&e.jsxs(s.Button,{onClick:i,variant:"secondary",size:"sm",children:[e.jsx(sa,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(s.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(la,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function an({sql:t,error:a,onDebugWithAssistant:n}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(kt,{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(nn,{sql:t,error:a,onDebugWithAssistant:n})})]})}var rn={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},xt=M.createContext&&M.createContext(rn),Br=["attr","size","title"];function Fr(t,a){if(t==null)return{};var n=zr(t,a),r,o;if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);for(o=0;o<l.length;o++)r=l[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}function zr(t,a){if(t==null)return{};var n={};for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){if(a.indexOf(r)>=0)continue;n[r]=t[r]}return n}function ns(){return ns=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},ns.apply(this,arguments)}function pt(t,a){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function as(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?pt(Object(n),!0).forEach(function(r){Pr(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):pt(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Pr(t,a,n){return a=_r(a),a in t?Object.defineProperty(t,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[a]=n,t}function _r(t){var a=Vr(t,"string");return typeof a=="symbol"?a:a+""}function Vr(t,a){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function on(t){return t&&t.map((a,n)=>M.createElement(a.tag,as({key:n},a.attr),on(a.child)))}function Me(t){return a=>M.createElement(Ur,ns({attr:as({},t.attr)},a),on(t.child))}function Ur(t){var a=n=>{var{attr:r,size:o,title:l}=t,c=Fr(t,Br),i=o||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),M.createElement("svg",ns({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:as(as({color:t.color||n.color},n.style),t.style),height:i,width:i,xmlns:"http://www.w3.org/2000/svg"}),l&&M.createElement("title",null,l),t.children)};return xt!==void 0?M.createElement(xt.Consumer,null,n=>a(n)):a(rn)}function $r(t){return Me({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 ln(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(x=>x.theme),r=s.useEditorStore(x=>x.frame),o=s.useEditorStore(x=>x.card),l=s.useEditorStore(x=>x.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(o),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=M.useRef(),h=M.useRef({}),f=r.cards.find(x=>x.id===l),p=M.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]);M.useEffect(()=>{if(l&&o.id&&o.id!==l){if(m.current&&c){const x=m.current.getModel();x&&(h.current[o.id]=x);let v=h.current[l];if(!v){const j=p();v=c.editor.createModel(j,t),h.current[l]=v}m.current.setModel(v)}d(l,o),u(!0)}},[l,o,d,c,u,t,p]),M.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=n==="system"?x:n;c.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),M.useEffect(()=>{const x=m.current;x&&c&&o&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,o]);function g(x,v){if(m.current=x,!h.current[o.id]){const j=x.getModel(),b=p();h.current[o.id]=j||(v==null?void 0:v.editor.createModel(b,t))||x.getModel()}x.setModel(h.current[o.id])}return{handleEditorDidMount:g}}function qr(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=ln("sql");function l(c){n(c),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:l,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function Gr(){const t=s.useEditorStore(o=>o.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=ln("python");function r(o){a(o)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Hr({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 Vs({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const n=s.useEditorStore(i=>i.card);Fs(((c=n.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),n.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:o}=zs();function l(){const i=o();r==null||r(i)}return e.jsxs(s.Button,{onClick:l,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Kr(){const t=s.useQueryClient(),[a,n]=M.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:l}=zs(),c=s.useSelectedVisual(),i=nr(),d=()=>{const u=l();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{n(!1),o(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{n(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(It,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Us(){const{setTempQueryData:t,setSqlGen:a}=s.useEditorActions(),n=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),o=s.useEditorStore(d=>d.onClose),l=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(l);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&n.setQueryData(d,u)}a({}),o==null||o()}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 ds(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(v=>v.isDevMode),r=s.useEditorStore(v=>v.tempQueryData),o=s.useEditorStore(v=>v.card),{queryKey:l}=s.useDashboardCardQuery(o),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:f,setCardConfig:p,setCardType:g}=s.useEditorActions();function x(){const v=a.getQueryData(l);r!=null&&r.queryData||t({queryKey:l,queryData:v}),a.setQueryData(l,null),a.removeQueries({queryKey:l,exact:!0}),n&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),f(),p(void 0),d(""),u(""),m({}),g("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 Qr(){const t=s.useQueryClient(),[a,n]=M.useState(!1),[r,o]=M.useState(!1);s.useEditorStore(P=>P.frame);const l=s.useEditorStore(P=>P.card);s.useEditorStore(P=>P.isShowingVisual),s.useEditorStore(P=>P.selectedConnectionId),s.useEditorStore(P=>P.tempQueryData),s.useEditorStore(P=>P.selectedDatabaseName),s.useEditorStore(P=>P.selectedDatamodelId),s.useEditorStore(P=>P.selectedSchemaName);const c=s.useEditorStore(P=>P.showAIDialog);s.useEditorStore(P=>P.selectedTableName);const i=s.useEditorStore(P=>{var Y;return(Y=P==null?void 0:P.card)==null?void 0:Y.sql}),d=s.useEditorStore(P=>{var Y;return(Y=P==null?void 0:P.card)==null?void 0:Y.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:f,setTempQueryData:p,setPythonStdOut:g,setCardPreferences:x,setCardType:v,setCardPython:j,runAssistant:b,setShowAIDialog:C}=s.useEditorActions();s.useEditorStore(P=>P.onSave),s.useEditorStore(P=>P.onClose),s.useEditorStore(P=>P.actions.setSqlGen);const R=s.useEditorStore(P=>P.runSql),E=s.useEditorStore(P=>P.actions.setRunSql),S=s.useEditorStore(P=>P.actions.setIsSqlRunning),{data:N,isLoading:D,isFetching:w,isSuccess:L,isError:k,error:O,queryKey:A,refetch:I,errorMessage:y}=s.useDashboardCardQuery(l);M.useEffect(()=>{if(N&&(N.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((N==null?void 0:N.output)||""),N.records.length>0)){const{dimensionKeys:P}=s.getKeys(N.records);h(P)}},[N,h,g]),M.useEffect(()=>{(D||w)&&S(!0),(k||L)&&S(!1),k&&(h([]),g(""))},[D,w,N,g,k,L,S,h,O]),M.useEffect(()=>{R&&(t.getQueryData(A)||I(),E(!1))},[R,I,E,A,t]);async function T(){const P=`Can you help me debug this query in the current table scope?
|
|
407
407
|
|
|
408
408
|
Error:
|
|
409
409
|
|