react-semaphor 0.0.549 → 0.0.550

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.
@@ -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 ve=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=>Rt(c))}})}})}}function Rt(t){return{...t,customCfg:Ta(t.customCfg),data:[]}}function Ta(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 Ia(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 Ss(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 Ma(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Aa(){const[t,a]=A.useState(""),[n,r]=A.useState(!1),o=s.useDashboardStore(x=>x.lenses),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=A.useState(!1),[u,m]=A.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 Ia(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 La(){const[t,a]=A.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 Ma(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 Ss(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 Ss(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(ia,{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 Ot(){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 Ft(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:l}=Ot();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 Ra({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 Ft()}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 dt=[{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}=Oa(),[i,d]=A.useState(""),[u,m]=A.useState(dt[0].value),[h,f]=A.useState("06:00"),[p,g]=A.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"email",children:"Email"}),e.jsx(s.Input,{id:"email",value:i,onChange:x=>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:dt,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(ut,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Wn,{className:"size-3.5"})}),e.jsx(ut,{tooltip:`${x.endUserEmail}`,children:e.jsx(fa,{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 ut=({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 Oa(){const[t,a]=A.useState("idle"),[n,r]=A.useState(""),[o,l]=A.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,...k}=Ot(),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:k};a("loading");const D="https://semaphor.cloud/api/v1/subscriptions/create";try{const O=await s.postRequestRegular(D,(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 ds(){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 zt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,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 Fa=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)},za=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()},Pa=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()},Va=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)},Ua=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()},$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}/shares`,t)},qa=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 Ya(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:()=>Fa((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 Qa(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:({resourceId:r,data:o})=>za((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 Ka(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>Pa((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=>Va((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 Xa(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>Ua((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 Za(t,a){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,a],queryFn:()=>$a((n==null?void 0:n.accessToken)||"",t,a),enabled:!!(n!=null&&n.accessToken)&&!!a})}function er(t,a,n){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,a],queryFn:()=>qa((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 sr(t,a){return er(ee.VISUAL,t,a)}function Pt(){const[t,a]=A.useState(new Map),n=A.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=A.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=A.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 Vt(t,a,n){var h;const r=Ga(t),o=Ha(t,n),l=Qa(t),c=Ka(t,a),i=Wa(t),d=Ja(),u=Xa(),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 tr(t,a){return Vt(ee.DASHBOARD,t,a)}function nr(t,a){return Vt(ee.VISUAL,t,a)}function ar(){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 rr({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]=A.useState(!1),[v,j]=A.useState(!1);A.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Tt,{className:"h-3 w-3 text-purple-500"}):e.jsx(ve,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(we,{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(va,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),m(t)},children:[e.jsx(ve,{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(we,{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 ss({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 Ut({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(ss,{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 $t({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 qt({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(ve,{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 Yt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,o=A.useRef(null);return A.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 pe(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function or(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Gt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function ir(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 lr({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 cr({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:o,handleUpdateAccess:l}){if(!(a!=null&&a.role))return null;const c=or((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(ss,{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:pe(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function dr({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(Ye,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function ur({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 mr({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=pe(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=pe(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=pe(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=pe(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=pe(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=pe(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=pe(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=pe(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=pe(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 hr({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 xr({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(lr,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(ss,{currentRole:a==null?void 0:a.role,onRoleChange:g=>f(t.id,a.role,g),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(cr,{user:t,userShare:a,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:f}),l&&!o&&e.jsx("div",{onClick:g=>g.stopPropagation(),children:e.jsx(ss,{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(dr,{hasAccess:r,isUserRemoving:n,isSelected:l,hasAccessFromAPI:o}),e.jsx(ur,{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(k=>k.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(mr,{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(hr,{isInitialLoading:a,isSearching:n,searchQuery:p,availableUsers:C||[]}),!a&&!n&&(C==null?void 0:C.length)>0&&C.map(E=>{const S=t?ir(E,t,l):void 0,N=R.includes(E.id),k=!!S,w=k&&!N,L=m.some(M=>M.id===E.id),D=m.find(M=>M.id===E.id),O=r(E.type);return e.jsx(xr,{user:E,userShare:S,isUserRemoving:N,hasAccess:w,hasAccessFromAPI:k,isSelected:L,selectedUser:D,roleOptions:O,currentUser:l,usersToUpdate:f,handleUserToggle:x,handleRemoveAccess:j,handleUpdateAccess:b,handleUserRoleChange:v},E.id)})]})]})}function Qt({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(we,{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 Ee=()=>[{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 pr({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=Ee().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(Sa,{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(ve,{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 Kt({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(pr,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:p,onRemoveAccess:g,allUsersToUpdate:f,allUsersToRemove:d})}const fr=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 gr(t={}){var r,o,l;const{authToken:a}=s.useSemaphorContext(),n=s.useQuery({queryKey:["unified-users",t],queryFn:()=>fr((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 De(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=ee.DASHBOARD,userType:o,tenantId:l}=t,c=A.useMemo(()=>({search:a,active:!0,...o?{type:o}:{},...o==="tenant"&&l?{tenantId:l}:{}}),[a,o,l]),{users:i,isLoading:d,isError:u}=gr(c),m=Za(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function jr({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var K,_;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]=A.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:k}=De({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:R(),tenantId:E()});A.useEffect(()=>{j.setCurrentContext("org-tab"),j.setCurrentMode(b==="all_users"?"allOrgUsers":"specificOrgUsers")},[j,b]);const w=$=>{var U,G;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=(G=(U=N==null?void 0:N.shares)==null?void 0:U.orgUsersOnly)==null?void 0:G[0];Q&&Q.role!==void 0&&j.setOrgWideRole(Q.role)}},L=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),D=S.filter($=>f.some(q=>q.id===$.id)),O=$=>{var Q,Y;const q=f.some(Z=>Z.id===$),U=p.includes($),G=(Y=(Q=N==null?void 0:N.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:Y.some(Z=>Z.orgUserId===$);q?j.removeSelectedUser($):U?j.removeUserFromRemove($):G||j.addSelectedUser({id:$,role:"VIEWER"})},M=($,q)=>{j.updateSelectedUserRole($,q)},I=$=>{j.addUserToRemove($),j.removeSelectedUser($)},y=$=>{j.removeUserFromRemove($)},T=$=>{j.removeUserFromUpdate($)},B=($,q)=>{j.setOrgWideRole(q)},z=()=>{j.setOrgWideRole((V==null?void 0:V.role)||"NONE")},V=(_=(K=N==null?void 0:N.shares)==null?void 0:K.orgUsersOnly)==null?void 0:_[0];A.useEffect(()=>{b==="all_users"&&V&&V.role!==void 0&&j.setOrgWideRole(V.role)},[b,V,j]);const P=k,X=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(Qt,{shareType:b,onShareTypeChange:w,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(we,{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(ve,{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(Ut,{selectedUsers:f,selectedUserObjects:D,onRemove:O,onRoleChange:M,getRoleOptions:Ee}),e.jsx($t,{usersToRemove:p,allUsers:L,onRemove:y}),e.jsx(qt,{usersToUpdate:g,allUsers:L,onRemove:T,getRoleOptions:Ee}),e.jsx(Ht,{existingShares:N,isInitialLoading:P,isSearching:X,resource:t,onShare:()=>{},getRoleOptions:Ee,allUsers:L,currentUser:n,handleUserToggle:O,handleUserRoleChange:M,handleRemoveAccess:I,handleUpdateAccess:($,q,U)=>{j.addUserToUpdate({id:$,currentRole:q,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Kt,{currentUser:n,currentShare:V,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:B,onRemoveAccess:z,allUsersToUpdate:x==="allOrgUsers"&&v!==((V==null?void 0:V.role)||"NONE")?{currentRole:(V==null?void 0:V.role)||"NONE",newRole:v}:null,allUsersToRemove:x==="allOrgUsers"&&(V==null?void 0:V.role)===void 0})})]}):null}function mt({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}=Ya({enabled:(n==null?void 0:n.type)==="organization"}),[R,E]=A.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");A.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=Y=>{var te,ae,se,oe;E(Y);let Z;if(Y==="specific_tenant_users"?Z="specific_users":Y==="all_tenant_users"||Y==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),Y==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):Y==="all_tenant_users"&&(j.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&j.setSelectedTenant(n.tenantId))):(j.setCurrentContext("tenant-tab"),Y==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):Y==="all_tenant_users"?j.setCurrentMode("allTenantUsers"):Y==="all_tenants"&&j.setCurrentMode("allTenants")),Y==="all_tenant_users"){const H=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0];H&&H.role!==void 0&&j.setTenantWideRole(H.role)}else if(Y==="all_tenants"){const H=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:oe[0];H&&H.role!==void 0&&j.setAllTenantsRole(H.role)}},N=Y=>{j.setSelectedTenant(Y)},{allUsers:k,existingShares:w,isLoadingUsers:L,isErrorLoadingUsers:D,isLoadingShares:O,isErrorLoadingShares:M}=De({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=Y=>{var se,oe;const Z=m.some(H=>H.id===Y),te=h.includes(Y),ae=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.specificTenantUsers)==null?void 0:oe.some(H=>H.tenantUserId===Y);Z?j.removeSelectedUser(Y):te?j.removeUserFromRemove(Y):ae||j.addSelectedUser({id:Y,role:"VIEWER"})},y=(Y,Z)=>{j.updateSelectedUserRole(Y,Z)},T=Y=>{j.addUserToRemove(Y),j.removeSelectedUser(Y)},B=Y=>{j.removeUserFromRemove(Y)},z=Y=>{j.removeUserFromUpdate(Y)},V=(Y,Z,te)=>{j.addUserToUpdate({id:Y,currentRole:Z,newRole:te})},P=(Y,Z)=>{R==="all_tenant_users"?j.setTenantWideRole(Z):R==="all_tenants"&&j.setAllTenantsRole(Z)},X=()=>{R==="all_tenant_users"?j.setTenantWideRole("VIEWER"):R==="all_tenants"&&j.setAllTenantsRole("VIEWER")},_=(()=>{var Y,Z,te,ae;return p==="allTenants"?(Z=(Y=w==null?void 0:w.shares)==null?void 0:Y.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})();A.useEffect(()=>{var Y,Z,te,ae;if(R==="all_tenant_users"){const se=(Z=(Y=w==null?void 0:w.shares)==null?void 0:Y.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 $=k.filter(Y=>m.some(Z=>Z.id===Y.id)),q=L||O,U=D||M,G=()=>(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(Qt,{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(ve,{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(we,{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(rt,{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(we,{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(Y=>e.jsx(s.SelectItem,{value:Y.id,children:Y.name},Y.id))})]})]}),G()?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(Ut,{selectedUsers:m,selectedUserObjects:$,onRemove:Y=>I(Y),onRoleChange:y,getRoleOptions:Ee}),e.jsx($t,{usersToRemove:h,allUsers:k,onRemove:B}),e.jsx(qt,{usersToUpdate:f,allUsers:k,onRemove:z,getRoleOptions:Ee}),e.jsx(Ht,{existingShares:w,isInitialLoading:!!q,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Ee,allUsers:k,currentUser:n,handleUserToggle:I,handleUserRoleChange:y,handleRemoveAccess:T,handleUpdateAccess:V})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Kt,{currentUser:n,currentShare:_,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:P,onRemoveAccess:X,allUsersToUpdate:p==="allTenantUsers"&&((_==null?void 0:_.role)===void 0||g!==_.role)||p==="allTenants"&&((_==null?void 0:_.role)===void 0||x!==_.role)?{currentRole:(_==null?void 0:_.role)||"VIEWER",newRole:p==="allTenantUsers"?g:x}:null,allUsersToRemove:p==="allTenantUsers"&&(_==null?void 0:_.role)===void 0||p==="allTenants"&&(_==null?void 0:_.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(rt,{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=A.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=A.useMemo(()=>f=>s.validateShareData(f),[]),h=A.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 ht({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,D,O,M;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=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[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=(M=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:M[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)},k=()=>{var L,D,O,M;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 B={...T,updateAccess:!0};l(B)}}}else if(i==="all_tenants"){const I=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[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 B=j();if(B&&b(B)){const z={...B,updateAccess:!0};l(z)}}}}else if(i==="all_tenant_users"){const I=(M=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:M[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 B=j();if(B&&b(B)){const z={...B,updateAccess:!0};l(z)}}}}},w=()=>{var L,D,O,M;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=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[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=(M=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:M[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(Ye,{className:"mr-2 h-4 w-4"}),!R&&E()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,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(ve,{className:"mr-2 h-4 w-4"}),!R&&E()]})]})}function yr({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 k={...N,removeAccess:!0};o(k)}}else{const N=f();if(N&&p(N)){const k={...N,updateAccess:!0};o(k)}}}},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(Ye,{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(Ye,{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,k,w,L;const{currentUser:d}=ds(),[u,m]=A.useState("specific_users"),[h,f]=A.useState("specific_users"),p=s.useShareManagementActions(),g=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:v}=De({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:j}=De({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),b=(k=(N=v==null?void 0:v.shares)==null?void 0:N.tenantWide)==null?void 0:k[0],C=(L=(w=j==null?void 0:j.shares)==null?void 0:w.orgUsersOnly)==null?void 0:L[0],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=A.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(Ye,{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:D=>{const O=D;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(jr,{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(mt,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:D=>m(D),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(mt,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:D=>m(D),isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?g==="org"?e.jsx(ht,{resource:t,existingShares:j,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:h,currentAllUsersShare:C,onRemoveAccess:i}):e.jsx(ht,{resource:t,existingShares:v,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:R(),currentAllUsersShare:b,onRemoveAccess:i}):e.jsx(yr,{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 Se(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Xt(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=Se(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=Se(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=Se(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=Se(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 Zt(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=Se(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=Se(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=Se(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=Se(o,l,[{scope:"org_users_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove org-wide access failed:",C)}})}}}}function vr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=De({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.DASHBOARD,userType:"tenant"}),d=A.useCallback(()=>{r.resetUserSelections()},[r]),u=A.useCallback(h=>{if(!t)return;const f={resourceType:ee.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(h,f)},[t,a,n,i,d]),m=A.useCallback(()=>{if(!t)return;const h={resourceType:ee.DASHBOARD,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Zt(o,l||"",c||"",h)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:m}}function br(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=De({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.VISUAL,userType:"tenant"}),d=A.useCallback(()=>{r.resetUserSelections()},[r]),u=A.useCallback(h=>{if(!t)return;const f={resourceType:ee.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(h,f)},[t,a,n,i,d]),m=A.useCallback(()=>{if(!t)return;const h={resourceType:ee.VISUAL,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Zt(o,l||"",c||"",h)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:m}}function Nr(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 zs(t){const[a,n]=A.useState(null),[r,o]=A.useState(null);return A.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 Cr(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 xt(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 Sr(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 wr(){var f;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),r=zs(((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:A.useCallback(()=>{var j;let p=m;m&&!m.includes("{{")&&(p=Nr(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:Cr(v,a.activeCardId)}},[n,a,u,o,l,c,i,d,t,r,m])}}function Ps(){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=sr((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),p=A.useCallback(async x=>{try{r(x);const{data:v,fromCache:j}=await xt((t==null?void 0:t.accessToken)||"",x.id,a);return Sr(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=A.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 xt((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:wr().getUpdatedFrame,refetch:f.refetch}}function Dr(){const[t,a]=A.useState(""),[n,r]=A.useState(!1),[o,l]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(!1),[m,h]=A.useState(null),[f,p]=A.useState(!1),[g,x]=A.useState(null),[v,j]=A.useState(null),{setIsDashboardEditing:b,setIsVisualEditing:C}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:E}=Ps(),{resources:S,isLoading:N,isError:k,createResource:w,updateResource:L,deleteResource:D,duplicateResource:O,shareResource:M,isCreating:I,isDeleting:y,removeResourceShares:T,isSharing:B,isRemovingShares:z,isUpdatingShares:V}=nr(()=>{p(!1),x(null)},()=>{r(!1),l(""),i("")}),{handleShareSubmit:P,handleRemoveAccess:X}=br((m==null?void 0:m.id)||null,M,T);ds();const K=S.filter(F=>{var J,ie;return((J=F==null?void 0:F.title)==null?void 0:J.toLowerCase().includes(t.toLowerCase()))||((ie=F==null?void 0:F.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),_=F=>new Date(F).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{o.trim()&&w({title:o,description:c,isPrivate:!1})},q=F=>{x(F),p(!0)},U=()=>{g&&D(g.id)},{startUpdating:G,stopUpdating:Q,isUpdating:Y}=Pt(),Z=(F,J)=>{const ie=J.title!==void 0?"title":"description";G(F,ie),L({resourceId:F,data:J},{onSuccess:()=>{Q(F,ie)},onError:()=>{Q(F,ie)}})},te=F=>{j(F),O(F,{onSettled:()=>j(null)})},ae=F=>{R(F)},se=F=>{E(F)},oe=F=>{const J=S.find(ie=>ie.id===F);J&&L({resourceId:F,data:{isPrivate:!J.isPrivate}})},H=F=>{h(F),u(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),De({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:ee.VISUAL,userType:"tenant"}),N?e.jsx(zt,{}):k?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:n?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:o,onChange:F=>l(F.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:F=>i(F.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:F=>a(F.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:K.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ls,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):K.map(F=>e.jsx(rr,{visual:F,onAddVisual:se,onEditVisual:ae,onUpdateVisual:Z,onDeleteClick:q,onDuplicateVisual:te,onTogglePrivacy:oe,onShareVisual:H,isDeleting:y,isDuplicating:v===F.id,isTitleUpdating:Y(F.id,"title"),isDescriptionUpdating:Y(F.id,"description"),formatDate:_},F.id))})}),d&&m&&e.jsx(Jt,{resource:m,resourceType:ee.VISUAL,onShare:P,isSharing:B,isRemoving:z,isUpdating:V,onClose:()=>{u(!1),h(null)},onRemoveAccess:X}),e.jsx(s.AlertDialog,{open:f,onOpenChange:F=>{!F&&y||(p(F),F||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:F=>{F.preventDefault(),F.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]=A.useState(!1),[v,j]=A.useState(!1);A.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Tt,{className:"h-3 w-3 text-purple-500"}):e.jsx(ve,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(we,{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(ve,{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(we,{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 Er({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 Tr(t){const[a,n]=A.useState(""),[r,o]=A.useState(!1),[l,c]=A.useState(""),[i,d]=A.useState(""),[u,m]=A.useState(!1),[h,f]=A.useState(null),[p,g]=A.useState(!1),[x,v]=A.useState(null),[j,b]=A.useState(null),C=s.useManagementStore(H=>H.lastSelectedDashboard),R=s.useManagementStore(H=>H.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:E,isLoading:S,isError:N,createResource:k,updateResource:w,deleteResource:L,duplicateResource:D,isCreating:O,isDeleting:M,isSharing:I,isRemovingShares:y,isUpdatingShares:T,shareResource:B,removeResourceShares:z}=tr(()=>{g(!1),v(null),C&&R(C)},()=>{o(!1),c(""),d("")}),{handleShareSubmit:V,handleRemoveAccess:P}=vr((h==null?void 0:h.id)||null,B,z),{currentUser:X}=ds(),K=E.filter(H=>{var F,J;return((F=H==null?void 0:H.title)==null?void 0:F.toLowerCase().includes(a.toLowerCase()))||((J=H==null?void 0:H.description)==null?void 0:J.toLowerCase().includes(a.toLowerCase()))}),_=H=>new Date(H).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{l.trim()&&k({title:l,description:i,isPrivate:!1})},q=H=>{var F;(F=t.onLoadDashboard)==null||F.call(t,H)},U=H=>{v(H),g(!0)},G=()=>{x&&L(x.id)},Q=H=>{b(H),D(H,{onSettled:()=>b(null)})},{startUpdating:Y,stopUpdating:Z,isUpdating:te}=Pt(),ae=(H,F)=>{const J=F.title!==void 0?"title":"description";Y(H,J),w({resourceId:H,data:F},{onSuccess:()=>{Z(H,J)},onError:()=>{Z(H,J)}})},se=H=>{const F=E.find(J=>J.id===H);F&&w({resourceId:H,data:{isPrivate:!F.isPrivate}})},oe=H=>{f(H),X==null||X.type,m(!0)};return De({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ee.DASHBOARD,userType:"tenant"}),S?e.jsx(zt,{}):N?e.jsx(Er,{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:H=>c(H.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:H=>d(H.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!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:H=>n(H.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:K.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(oa,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):K.map(H=>e.jsx(kr,{dashboard:H,isDeleting:M,isDuplicating:j===H.id,isTitleUpdating:te(H.id,"title"),isDescriptionUpdating:te(H.id,"description"),onLoadDashboard:q,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ae,onDeleteClick:U,onDuplicateDashboard:Q,onTogglePrivacy:se,onShareDashboard:oe,formatDate:_,onDashboardItemClick:t.onDashboardItemClick},H.id))})}),u&&h&&e.jsx(Jt,{resource:h,resourceType:ee.DASHBOARD,onShare:V,isSharing:I,isRemoving:y,isUpdating:T,onClose:()=>{m(!1),f(null)},onRemoveAccess:P}),e.jsx(s.AlertDialog,{open:p,onOpenChange:H=>{!H&&M||(g(H),H||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:M,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:H=>{H.preventDefault(),H.stopPropagation(),G()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:M,children:M?"Deleting...":"Delete"})]})]})})]})}function en({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}=ds(),i=c,[d,u]=s.useLocalStorageState("resource-management-active-tab","dashboards"),m=Yt(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(Tr,{onLoadDashboard:h,onEditDashboard:f,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Dr,{})})]})})]})})}function Ir(){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]=A.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:k,endUserId:w}=A.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),L=A.useMemo(()=>k||w,[k,w]),D=()=>{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:[]},B={id:s.v4(),cards:[T],activeCardId:T.id};b(N.id,B),C(B.id)},O=()=>{E(!0)};async function M(){if(m(!0),!r||!o)return;const T=Bs(l),B=JSON.stringify(T),z={...o,template:B,filterValues:p};await Ss(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(da,{className:"h-4 w-4"})}),!g&&e.jsx(s.Label,{children:I})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!g&&e.jsx(Ra,{}),!g&&e.jsx(Bt,{}),c&&!g&&L&&e.jsx(Aa,{}),!g&&L&&e.jsx(La,{}),c&&!g&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:D,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:M,size:"sm",children:e.jsx(Mt,{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(en,{isOpen:h,onClose:()=>f(!1)})]})]})}function Mr({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(It,{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(ba,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(ya,{className:"size-4"});if(t==="Table")return e.jsx(cs,{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(It,{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(Mr,{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]=A.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 Vs({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($e,{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(es,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Qn,{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 ps({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(Vs,{column:t}),e.jsx("span",{children:t.column_name})]})}function Lr({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 Rr({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(ps,{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(ps,{column:a})}),e.jsx(Lr,{id:a.column_name,type:"column",children:e.jsx(ps,{column:a})})]})}const fs={id:"__placeholder__",role:"groupby",type:"string"},gs={id:"__placeholder__",role:"groupby",type:"string"},js={id:"__placeholder__",role:"metric",type:"number"},ys={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},sn={id:"__placeholder__"},Te="droppable-group-by",Ie="droppable-metrics",Me="droppable-pivot-by",ts="sortable-group-by",ws="sortable-metrics",ns="sortable-pivot-by",Ds="droppable-filters",ks="sortable-filters",_s="sortable-order-by";function Or(){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 B;const{active:y,over:T}=I;if(((B=y.data.current)==null?void 0:B.type)==="column"&&T){const z=T.id,V=j.find(_=>_.column_name===y.id);if(!V)return;const P=s.isNumberDataType(V.data_type),X=s.isTextDataType(V.data_type),K=s.isDateDataType(V.data_type);if(X||K){if(a.some($=>$.id===z)){const $=a.findIndex(U=>U.id===z);c($);const q=a.filter(U=>U.id!==fs.id);q.splice($,0,fs),d(q)}else if(T.id===Te){c(a.length);const $=[...a,fs];d($),u(n),m(r)}}if(X||K){if(l.some($=>$.id===z)){const $=l.findIndex(U=>U.id===z);c($);const q=l.filter(U=>U.id!==gs.id);q.splice($,0,gs),h(q)}else if(T.id===Me){c(l.length);const $=[...l,gs];h($),d(a),u(n),m(r)}}if(P||X){if(n.some($=>$.id===z)){console.log("isOverMetricSortable",z);const $=n.findIndex(U=>U.id===z);c($);const q=n.filter(U=>U.id!==js.id);q.splice($,0,js),u(q)}else if(T.id===Ie){c(n.length);const $=[...n,js];u($),m(r),d(a),h(l)}}if(S(V)){if(r.some($=>$.id===z)){const $=r.findIndex(U=>U.id===z);c($);const q=r.filter(U=>U.id!==ys.id);q.splice($,0,ys),m(q)}else if(T.id===Ds){c(r.length);const $=[...r,ys];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:B}=I,z=[...n],V=t!==null?t:n.length,P={...I,id:fe(T),name:T,label:He(T,y),type:B,role:"metric",aggregate:y};z.splice(V,0,P),p(z)}function k(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...l],B=t!==null?t:l.length;let z;y?z={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(B,0,z),v(T)}function w(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...a],B=t!==null?t:a.length;let z;y?z={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(B,0,z),f(T)}function L(I){const y=[...r],T=t!==null?t:r.length,B={...I,id:fe(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,B),g(y)}function D(I){var z,V,P,X,K,_,$,q;const{active:y,over:T}=I,B=y.data.current;if((B==null?void 0:B.type)==="column"&&T){const U=j.find(Z=>Z.column_name===y.id);if(!U)return;const G=s.isNumberDataType(U.data_type),Q=s.isTextDataType(U.data_type),Y=s.isDateDataType(U.data_type);(Q||Y)&&(T.id===Te||((z=T.data.current)==null?void 0:z.type)===ts)&&w(U),(Q||Y)&&(T.id===Me||((V=T.data.current)==null?void 0:V.type)===ns)?k(U):(G||Q)&&(T.id===Ie||((P=T.data.current)==null?void 0:P.type)===ws)?(G&&N(U),Q&&N(U,"COUNT")):S(U)&&(T.id===Ds||((X=T.data.current)==null?void 0:X.type)===ks)&&L(U)}if(T&&((K=T.data.current)==null?void 0:K.type)===ts&&a.some(U=>U.id===y.id)){const U=a.findIndex(Q=>Q.id===y.id),G=a.findIndex(Q=>Q.id===T.id);if(U!==-1&&G!==-1&&U!==G){const Q=[...a],[Y]=Q.splice(U,1);Q.splice(G,0,Y),f(Q)}}if(T&&((_=T.data.current)==null?void 0:_.type)===ns&&l.some(U=>U.id===y.id)){const U=l.findIndex(Q=>Q.id===y.id),G=l.findIndex(Q=>Q.id===T.id);if(U!==-1&&G!==-1&&U!==G){const Q=[...l],[Y]=Q.splice(U,1);Q.splice(G,0,Y),v(Q)}}if(T&&(($=T.data.current)==null?void 0:$.type)===ws&&n.some(U=>U.id===y.id)){const U=n.findIndex(Q=>Q.id===y.id),G=n.findIndex(Q=>Q.id===T.id);if(U!==-1&&G!==-1&&U!==G){const Q=[...n],[Y]=Q.splice(U,1);Q.splice(G,0,Y),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),G=r.findIndex(Q=>Q.id===T.id);if(U!==-1&&G!==-1&&U!==G){const Q=[...r],[Y]=Q.splice(U,1);Q.splice(G,0,Y),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,B=y.data.current;if((B==null?void 0:B.type)===_s&&T){const z=o.findIndex(P=>Ue(P.columnId)===y.id),V=o.findIndex(P=>Ue(P.columnId)===T.id);if(z!==-1&&V!==-1&&z!==V){const P=[...o],[X]=P.splice(z,1);P.splice(V,0,X),x(P)}}}function M(){i(null),c(null),d(a),u(n),m(r)}return{handleDragOver:R,handleDragEnd:D,handleDragStart:E,handleDragCancel:M,sensors:C}}function fe(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 Ue(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 Fr({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,B;return(B=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:B.metricColumns});s.useEditorStore(y=>{var T,B;return(B=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:B.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 k(y){var T;if(l){const B=s.createSqlGenConfig(y,o);C(B);const z=(T=S==null?void 0:S.find(P=>P.id===h))==null?void 0:T.name,V=s.getSql(B,s.fmt(t),s.fmt(a),z||"",E,d||"");V&&(j(V),b(!0))}if(!l){if(s.isTextDataType(y.data_type))if(i&&i.length>0){const B={...y,role:"groupby",id:fe(y.column_name),name:y.column_name,type:y.data_type};v(B)}else{const B={...y,role:"metric",id:fe(y.column_name),name:y.column_name,label:He(y.column_name,"COUNT"),type:y.data_type,aggregate:"COUNT"};x(B)}if(s.isDateDataType(y.data_type)){const B={...y,role:"groupby",id:fe(y.column_name),name:y.column_name,type:y.data_type,label:Pe(y.column_name,"month"),granularity:"month"};v(B)}if(s.isNumberDataType(y.data_type)){const B={...y,role:"metric",id:fe(y.column_name),name:y.column_name,label:He(y.column_name,"SUM"),type:y.data_type,aggregate:"SUM"};x(B)}}}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 D(){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 M(y){return l?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>k(y),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Vs,{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(Rr,{onClick:k,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(pa,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:D,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:M(y)},y.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function tn({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:k,isSchemaLoadingOrFetching:w,isSchemaError:L,isColumnsError:D,isColumnsLoadingOrFetching:O,isTableLoadingOrFetching:M,isTableError:I,connectionType:y,isNonDbConnection:T,refetchDatabases:B,refetchModels:z,refetchSchemas:V,refetchTables:P,refetchColumns:X,refetchConnections:K,handleConnectionChange:_,handleDatabaseChange:$,handleSchemaChange:q,handleDatamodelChange:U,handleTableChange:G,tableName:Q,schemaName:Y}=s.useEditorAside(),{data:Z,refetch:te}=s.useDashboardCardQuery(n);function ae(){return t?t(Y,Q,b):e.jsx(Fr,{schemaName:Y,tableName:Q,columns:b,status:O?"Loading...":D?"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 H(){if(!r||y==="S3"||y==="API")return null;if(!l||l==="none")return e.jsx(ze,{refetch:B,showNone:!0,onChange:$,isError:k,isLoading:N,items:v,value:c||"",title:"Database",type:"combobox"})}function F(){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:V,onChange:q,isError:L,isLoading:w,items:x,value:i||"",title:"Schema",type:"combobox"})}function be(){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:G,isError:I,items:j,isLoading:M,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:K,items:p,title:"Connection",value:r||"",onChange:_,isLoading:C,isError:E,type:"combobox",connectionTooltip:((ke=p==null?void 0:p.find(ne=>ne.id===r))==null?void 0:ke.type)||""}),H(),F(),J(),ie(),be()]}),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(ga,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function nn({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,l]=A.useState(!1),c=A.useRef(null),i=A.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 an({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(nn,{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(ta,{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(ca,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function rn({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(an,{sql:t,error:a,onDebugWithAssistant:n})})]})}var on={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},pt=A.createContext&&A.createContext(on),Br=["attr","size","title"];function zr(t,a){if(t==null)return{};var n=Pr(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 Pr(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 as(){return as=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},as.apply(this,arguments)}function ft(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 rs(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?ft(Object(n),!0).forEach(function(r){Vr(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):ft(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Vr(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=Ur(t,"string");return typeof a=="symbol"?a:a+""}function Ur(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 ln(t){return t&&t.map((a,n)=>A.createElement(a.tag,rs({key:n},a.attr),ln(a.child)))}function Le(t){return a=>A.createElement($r,as({attr:rs({},t.attr)},a),ln(t.child))}function $r(t){var a=n=>{var{attr:r,size:o,title:l}=t,c=zr(t,Br),i=o||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),A.createElement("svg",as({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:rs(rs({color:t.color||n.color},n.style),t.style),height:i,width:i,xmlns:"http://www.w3.org/2000/svg"}),l&&A.createElement("title",null,l),t.children)};return pt!==void 0?A.createElement(pt.Consumer,null,n=>a(n)):a(on)}function qr(t){return Le({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 cn(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=A.useRef(),h=A.useRef({}),f=r.cards.find(x=>x.id===l),p=A.useCallback(()=>{let x="";return t==="python"&&(x=(f==null?void 0:f.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(f==null?void 0:f.sql)||""),x},[t,f]);A.useEffect(()=>{if(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]),A.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]),A.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 Yr(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=cn("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}=cn("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 Us({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const n=s.useEditorStore(i=>i.card);zs(((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}=Ps();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 Qr(){const t=s.useQueryClient(),[a,n]=A.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:l}=Ps(),c=s.useSelectedVisual(),i=ar(),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(Mt,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function $s(){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 us(){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 Kr(){const t=s.useQueryClient(),[a,n]=A.useState(!1),[r,o]=A.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 X;return(X=P==null?void 0:P.card)==null?void 0:X.sql}),d=s.useEditorStore(P=>{var X;return(X=P==null?void 0:P.card)==null?void 0:X.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:k,isFetching:w,isSuccess:L,isError:D,error:O,queryKey:M,refetch:I,errorMessage:y}=s.useDashboardCardQuery(l);A.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]),A.useEffect(()=>{(k||w)&&S(!0),(D||L)&&S(!1),D&&(h([]),g(""))},[k,w,N,g,D,L,S,h,O]),A.useEffect(()=>{R&&(t.getQueryData(M)||I(),E(!1))},[R,I,E,M,t]);async function T(){const P=`Can you help me debug this query in the current table scope?
406
+ */const ve=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=>Rt(c))}})}})}}function Rt(t){return{...t,customCfg:Ta(t.customCfg),data:[]}}function Ta(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 Ia(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 Ss(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 Ma(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Aa(){const[t,a]=A.useState(""),[n,r]=A.useState(!1),o=s.useDashboardStore(x=>x.lenses),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=A.useState(!1),[u,m]=A.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 Ia(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 La(){const[t,a]=A.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 Ma(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 Ss(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 Ss(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(ia,{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 Ot(){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 Ft(){const t=s.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:l}=Ot();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 Ra({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 Ft()}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 dt=[{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}=Oa(),[i,d]=A.useState(""),[u,m]=A.useState(dt[0].value),[h,f]=A.useState("06:00"),[p,g]=A.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"email",children:"Email"}),e.jsx(s.Input,{id:"email",value:i,onChange:x=>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:dt,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(ut,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(Wn,{className:"size-3.5"})}),e.jsx(ut,{tooltip:`${x.endUserEmail}`,children:e.jsx(fa,{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 ut=({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 Oa(){const[t,a]=A.useState("idle"),[n,r]=A.useState(""),[o,l]=A.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,...k}=Ot(),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:k};a("loading");const D="https://semaphor.cloud/api/v1/subscriptions/create";try{const O=await s.postRequestRegular(D,(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 ds(){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 zt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,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 Fa=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)},za=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()},Pa=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()},Va=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)},Ua=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()},$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}/shares`,t)},qa=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 Ya(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:()=>Fa((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 Qa(t){const{authToken:a}=s.useSemaphorContext(),n=s.useQueryClient();return Ae({mutationFn:({resourceId:r,data:o})=>za((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 Ka(t,a){const{authToken:n}=s.useSemaphorContext(),r=s.useQueryClient();return Ae({mutationFn:o=>Pa((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=>Va((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 Xa(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient();return Ae({mutationFn:({resourceType:n,resourceId:r,data:o})=>Ua((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 Za(t,a){const{authToken:n}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-shares",t,a],queryFn:()=>$a((n==null?void 0:n.accessToken)||"",t,a),enabled:!!(n!=null&&n.accessToken)&&!!a})}function er(t,a,n){const{authToken:r}=s.useSemaphorContext();return s.useQuery({queryKey:["resource-by-id",t,a],queryFn:()=>qa((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 sr(t,a){return er(ee.VISUAL,t,a)}function Pt(){const[t,a]=A.useState(new Map),n=A.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=A.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=A.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 Vt(t,a,n){var h;const r=Ga(t),o=Ha(t,n),l=Qa(t),c=Ka(t,a),i=Wa(t),d=Ja(),u=Xa(),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 tr(t,a){return Vt(ee.DASHBOARD,t,a)}function nr(t,a){return Vt(ee.VISUAL,t,a)}function ar(){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 rr({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]=A.useState(!1),[v,j]=A.useState(!1);A.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Tt,{className:"h-3 w-3 text-purple-500"}):e.jsx(ve,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(we,{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(va,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:S=>{S.stopPropagation(),m(t)},children:[e.jsx(ve,{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(we,{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 ss({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 Ut({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(ss,{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 $t({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 qt({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(ve,{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 Yt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,o=A.useRef(null);return A.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 pe(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function or(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Gt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function ir(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 lr({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 cr({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:o,handleUpdateAccess:l}){if(!(a!=null&&a.role))return null;const c=or((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(ss,{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:pe(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function dr({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(Ye,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function ur({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 mr({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=pe(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=pe(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=pe(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=pe(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=pe(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=pe(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=pe(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=pe(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=pe(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 hr({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 xr({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(lr,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(ss,{currentRole:a==null?void 0:a.role,onRoleChange:g=>f(t.id,a.role,g),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(cr,{user:t,userShare:a,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:f}),l&&!o&&e.jsx("div",{onClick:g=>g.stopPropagation(),children:e.jsx(ss,{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(dr,{hasAccess:r,isUserRemoving:n,isSelected:l,hasAccessFromAPI:o}),e.jsx(ur,{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(k=>k.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(mr,{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(hr,{isInitialLoading:a,isSearching:n,searchQuery:p,availableUsers:C||[]}),!a&&!n&&(C==null?void 0:C.length)>0&&C.map(E=>{const S=t?ir(E,t,l):void 0,N=R.includes(E.id),k=!!S,w=k&&!N,L=m.some(M=>M.id===E.id),D=m.find(M=>M.id===E.id),O=r(E.type);return e.jsx(xr,{user:E,userShare:S,isUserRemoving:N,hasAccess:w,hasAccessFromAPI:k,isSelected:L,selectedUser:D,roleOptions:O,currentUser:l,usersToUpdate:f,handleUserToggle:x,handleRemoveAccess:j,handleUpdateAccess:b,handleUserRoleChange:v},E.id)})]})]})}function Qt({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(we,{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 Ee=()=>[{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 pr({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=Ee().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(Sa,{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(ve,{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 Kt({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(pr,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:o,onUpdateAccess:p,onRemoveAccess:g,allUsersToUpdate:f,allUsersToRemove:d})}const fr=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 gr(t={}){var r,o,l;const{authToken:a}=s.useSemaphorContext(),n=s.useQuery({queryKey:["unified-users",t],queryFn:()=>fr((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 De(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=ee.DASHBOARD,userType:o,tenantId:l}=t,c=A.useMemo(()=>({search:a,active:!0,...o?{type:o}:{},...o==="tenant"&&l?{tenantId:l}:{}}),[a,o,l]),{users:i,isLoading:d,isError:u}=gr(c),m=Za(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function jr({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var K,_;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]=A.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:k}=De({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:R(),tenantId:E()});A.useEffect(()=>{j.setCurrentContext("org-tab"),j.setCurrentMode(b==="all_users"?"allOrgUsers":"specificOrgUsers")},[j,b]);const w=$=>{var U,G;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=(G=(U=N==null?void 0:N.shares)==null?void 0:U.orgUsersOnly)==null?void 0:G[0];Q&&Q.role!==void 0&&j.setOrgWideRole(Q.role)}},L=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),D=S.filter($=>f.some(q=>q.id===$.id)),O=$=>{var Q,Y;const q=f.some(Z=>Z.id===$),U=p.includes($),G=(Y=(Q=N==null?void 0:N.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:Y.some(Z=>Z.orgUserId===$);q?j.removeSelectedUser($):U?j.removeUserFromRemove($):G||j.addSelectedUser({id:$,role:"VIEWER"})},M=($,q)=>{j.updateSelectedUserRole($,q)},I=$=>{j.addUserToRemove($),j.removeSelectedUser($)},y=$=>{j.removeUserFromRemove($)},T=$=>{j.removeUserFromUpdate($)},B=($,q)=>{j.setOrgWideRole(q)},z=()=>{j.setOrgWideRole((V==null?void 0:V.role)||"NONE")},V=(_=(K=N==null?void 0:N.shares)==null?void 0:K.orgUsersOnly)==null?void 0:_[0];A.useEffect(()=>{b==="all_users"&&V&&V.role!==void 0&&j.setOrgWideRole(V.role)},[b,V,j]);const P=k,X=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(Qt,{shareType:b,onShareTypeChange:w,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(we,{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(ve,{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(Ut,{selectedUsers:f,selectedUserObjects:D,onRemove:O,onRoleChange:M,getRoleOptions:Ee}),e.jsx($t,{usersToRemove:p,allUsers:L,onRemove:y}),e.jsx(qt,{usersToUpdate:g,allUsers:L,onRemove:T,getRoleOptions:Ee}),e.jsx(Ht,{existingShares:N,isInitialLoading:P,isSearching:X,resource:t,onShare:()=>{},getRoleOptions:Ee,allUsers:L,currentUser:n,handleUserToggle:O,handleUserRoleChange:M,handleRemoveAccess:I,handleUpdateAccess:($,q,U)=>{j.addUserToUpdate({id:$,currentRole:q,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Kt,{currentUser:n,currentShare:V,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:B,onRemoveAccess:z,allUsersToUpdate:x==="allOrgUsers"&&v!==((V==null?void 0:V.role)||"NONE")?{currentRole:(V==null?void 0:V.role)||"NONE",newRole:v}:null,allUsersToRemove:x==="allOrgUsers"&&(V==null?void 0:V.role)===void 0})})]}):null}function mt({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}=Ya({enabled:(n==null?void 0:n.type)==="organization"}),[R,E]=A.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");A.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=Y=>{var te,ae,se,oe;E(Y);let Z;if(Y==="specific_tenant_users"?Z="specific_users":Y==="all_tenant_users"||Y==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(j.setCurrentContext("tenant-dialog"),Y==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):Y==="all_tenant_users"&&(j.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&j.setSelectedTenant(n.tenantId))):(j.setCurrentContext("tenant-tab"),Y==="specific_tenant_users"?j.setCurrentMode("specificTenantUsers"):Y==="all_tenant_users"?j.setCurrentMode("allTenantUsers"):Y==="all_tenants"&&j.setCurrentMode("allTenants")),Y==="all_tenant_users"){const H=(ae=(te=w==null?void 0:w.shares)==null?void 0:te.tenantWide)==null?void 0:ae[0];H&&H.role!==void 0&&j.setTenantWideRole(H.role)}else if(Y==="all_tenants"){const H=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.allTenantsOnly)==null?void 0:oe[0];H&&H.role!==void 0&&j.setAllTenantsRole(H.role)}},N=Y=>{j.setSelectedTenant(Y)},{allUsers:k,existingShares:w,isLoadingUsers:L,isErrorLoadingUsers:D,isLoadingShares:O,isErrorLoadingShares:M}=De({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=Y=>{var se,oe;const Z=m.some(H=>H.id===Y),te=h.includes(Y),ae=(oe=(se=w==null?void 0:w.shares)==null?void 0:se.specificTenantUsers)==null?void 0:oe.some(H=>H.tenantUserId===Y);Z?j.removeSelectedUser(Y):te?j.removeUserFromRemove(Y):ae||j.addSelectedUser({id:Y,role:"VIEWER"})},y=(Y,Z)=>{j.updateSelectedUserRole(Y,Z)},T=Y=>{j.addUserToRemove(Y),j.removeSelectedUser(Y)},B=Y=>{j.removeUserFromRemove(Y)},z=Y=>{j.removeUserFromUpdate(Y)},V=(Y,Z,te)=>{j.addUserToUpdate({id:Y,currentRole:Z,newRole:te})},P=(Y,Z)=>{R==="all_tenant_users"?j.setTenantWideRole(Z):R==="all_tenants"&&j.setAllTenantsRole(Z)},X=()=>{R==="all_tenant_users"?j.setTenantWideRole("VIEWER"):R==="all_tenants"&&j.setAllTenantsRole("VIEWER")},_=(()=>{var Y,Z,te,ae;return p==="allTenants"?(Z=(Y=w==null?void 0:w.shares)==null?void 0:Y.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})();A.useEffect(()=>{var Y,Z,te,ae;if(R==="all_tenant_users"){const se=(Z=(Y=w==null?void 0:w.shares)==null?void 0:Y.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 $=k.filter(Y=>m.some(Z=>Z.id===Y.id)),q=L||O,U=D||M,G=()=>(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(Qt,{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(ve,{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(we,{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(rt,{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(we,{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(Y=>e.jsx(s.SelectItem,{value:Y.id,children:Y.name},Y.id))})]})]}),G()?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(Ut,{selectedUsers:m,selectedUserObjects:$,onRemove:Y=>I(Y),onRoleChange:y,getRoleOptions:Ee}),e.jsx($t,{usersToRemove:h,allUsers:k,onRemove:B}),e.jsx(qt,{usersToUpdate:f,allUsers:k,onRemove:z,getRoleOptions:Ee}),e.jsx(Ht,{existingShares:w,isInitialLoading:!!q,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Ee,allUsers:k,currentUser:n,handleUserToggle:I,handleUserRoleChange:y,handleRemoveAccess:T,handleUpdateAccess:V})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Kt,{currentUser:n,currentShare:_,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:P,onRemoveAccess:X,allUsersToUpdate:p==="allTenantUsers"&&((_==null?void 0:_.role)===void 0||g!==_.role)||p==="allTenants"&&((_==null?void 0:_.role)===void 0||x!==_.role)?{currentRole:(_==null?void 0:_.role)||"VIEWER",newRole:p==="allTenantUsers"?g:x}:null,allUsersToRemove:p==="allTenantUsers"&&(_==null?void 0:_.role)===void 0||p==="allTenants"&&(_==null?void 0:_.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(rt,{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=A.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=A.useMemo(()=>f=>s.validateShareData(f),[]),h=A.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 ht({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,D,O,M;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=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[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=(M=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:M[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)},k=()=>{var L,D,O,M;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 B={...T,updateAccess:!0};l(B)}}}else if(i==="all_tenants"){const I=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[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 B=j();if(B&&b(B)){const z={...B,updateAccess:!0};l(z)}}}}else if(i==="all_tenant_users"){const I=(M=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:M[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 B=j();if(B&&b(B)){const z={...B,updateAccess:!0};l(z)}}}}},w=()=>{var L,D,O,M;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=(D=(L=a==null?void 0:a.shares)==null?void 0:L.allTenantsOnly)==null?void 0:D[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=(M=(O=a==null?void 0:a.shares)==null?void 0:O.tenantWide)==null?void 0:M[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(Ye,{className:"mr-2 h-4 w-4"}),!R&&E()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,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(ve,{className:"mr-2 h-4 w-4"}),!R&&E()]})]})}function yr({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 k={...N,removeAccess:!0};o(k)}}else{const N=f();if(N&&p(N)){const k={...N,updateAccess:!0};o(k)}}}},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(Ye,{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(Ye,{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,k,w,L;const{currentUser:d}=ds(),[u,m]=A.useState("specific_users"),[h,f]=A.useState("specific_users"),p=s.useShareManagementActions(),g=s.useShareSelectedTab(),x=s.useShareCurrentMode(),{existingShares:v}=De({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:j}=De({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),b=(k=(N=v==null?void 0:v.shares)==null?void 0:N.tenantWide)==null?void 0:k[0],C=(L=(w=j==null?void 0:j.shares)==null?void 0:w.orgUsersOnly)==null?void 0:L[0],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=A.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(Ye,{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:D=>{const O=D;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(jr,{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(mt,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:D=>m(D),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(mt,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:D=>m(D),isSharing:n,isUpdating:o,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?g==="org"?e.jsx(ht,{resource:t,existingShares:j,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:h,currentAllUsersShare:C,onRemoveAccess:i}):e.jsx(ht,{resource:t,existingShares:v,isSharing:n,isRemoving:r,isUpdating:o,onShare:c,onClose:l,shareTabType:R(),currentAllUsersShare:b,onRemoveAccess:i}):e.jsx(yr,{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 Se(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function Xt(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=Se(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=Se(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=Se(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=Se(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 Zt(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=Se(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=Se(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=Se(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=Se(o,l,[{scope:"org_users_only",role:j.role}]);c(b,{onSuccess:()=>{d()},onError:C=>{console.error("Remove org-wide access failed:",C)}})}}}}function vr(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=De({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.DASHBOARD,userType:"tenant"}),d=A.useCallback(()=>{r.resetUserSelections()},[r]),u=A.useCallback(h=>{if(!t)return;const f={resourceType:ee.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(h,f)},[t,a,n,i,d]),m=A.useCallback(()=>{if(!t)return;const h={resourceType:ee.DASHBOARD,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Zt(o,l||"",c||"",h)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:m}}function br(t,a,n){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{existingShares:i}=De({debouncedSearchQuery:"",resourceId:t||"",resourceType:ee.VISUAL,userType:"tenant"}),d=A.useCallback(()=>{r.resetUserSelections()},[r]),u=A.useCallback(h=>{if(!t)return;const f={resourceType:ee.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:i,resetUserSelections:d};Xt(h,f)},[t,a,n,i,d]),m=A.useCallback(()=>{if(!t)return;const h={resourceType:ee.VISUAL,resourceId:t,removeMutation:n,existingShares:i,resetUserSelections:d};Zt(o,l||"",c||"",h)},[t,a,n,i,d,o,l,c]);return{handleShareSubmit:u,handleRemoveAccess:m}}function Nr(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 zs(t){const[a,n]=A.useState(null),[r,o]=A.useState(null);return A.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 Cr(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 xt(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 Sr(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 wr(){var f;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),r=zs(((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:A.useCallback(()=>{var j;let p=m;m&&!m.includes("{{")&&(p=Nr(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:Cr(v,a.activeCardId)}},[n,a,u,o,l,c,i,d,t,r,m])}}function Ps(){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=sr((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),p=A.useCallback(async x=>{try{r(x);const{data:v,fromCache:j}=await xt((t==null?void 0:t.accessToken)||"",x.id,a);return Sr(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=A.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 xt((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:wr().getUpdatedFrame,refetch:f.refetch}}function Dr(){const[t,a]=A.useState(""),[n,r]=A.useState(!1),[o,l]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(!1),[m,h]=A.useState(null),[f,p]=A.useState(!1),[g,x]=A.useState(null),[v,j]=A.useState(null),{setIsDashboardEditing:b,setIsVisualEditing:C}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:E}=Ps(),{resources:S,isLoading:N,isError:k,createResource:w,updateResource:L,deleteResource:D,duplicateResource:O,shareResource:M,isCreating:I,isDeleting:y,removeResourceShares:T,isSharing:B,isRemovingShares:z,isUpdatingShares:V}=nr(()=>{p(!1),x(null)},()=>{r(!1),l(""),i("")}),{handleShareSubmit:P,handleRemoveAccess:X}=br((m==null?void 0:m.id)||null,M,T);ds();const K=S.filter(F=>{var J,ie;return((J=F==null?void 0:F.title)==null?void 0:J.toLowerCase().includes(t.toLowerCase()))||((ie=F==null?void 0:F.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),_=F=>new Date(F).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{o.trim()&&w({title:o,description:c,isPrivate:!1})},q=F=>{x(F),p(!0)},U=()=>{g&&D(g.id)},{startUpdating:G,stopUpdating:Q,isUpdating:Y}=Pt(),Z=(F,J)=>{const ie=J.title!==void 0?"title":"description";G(F,ie),L({resourceId:F,data:J},{onSuccess:()=>{Q(F,ie)},onError:()=>{Q(F,ie)}})},te=F=>{j(F),O(F,{onSettled:()=>j(null)})},ae=F=>{R(F)},se=F=>{E(F)},oe=F=>{const J=S.find(ie=>ie.id===F);J&&L({resourceId:F,data:{isPrivate:!J.isPrivate}})},H=F=>{h(F),u(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),De({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:ee.VISUAL,userType:"tenant"}),N?e.jsx(zt,{}):k?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:n?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:o,onChange:F=>l(F.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:F=>i(F.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:F=>a(F.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:K.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ls,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):K.map(F=>e.jsx(rr,{visual:F,onAddVisual:se,onEditVisual:ae,onUpdateVisual:Z,onDeleteClick:q,onDuplicateVisual:te,onTogglePrivacy:oe,onShareVisual:H,isDeleting:y,isDuplicating:v===F.id,isTitleUpdating:Y(F.id,"title"),isDescriptionUpdating:Y(F.id,"description"),formatDate:_},F.id))})}),d&&m&&e.jsx(Jt,{resource:m,resourceType:ee.VISUAL,onShare:P,isSharing:B,isRemoving:z,isUpdating:V,onClose:()=>{u(!1),h(null)},onRemoveAccess:X}),e.jsx(s.AlertDialog,{open:f,onOpenChange:F=>{!F&&y||(p(F),F||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:F=>{F.preventDefault(),F.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]=A.useState(!1),[v,j]=A.useState(!1);A.useEffect(()=>{n?(x(!0),j(!0)):v&&(x(!1),j(!1))},[n,v]);const b=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(Tt,{className:"h-3 w-3 text-purple-500"}):e.jsx(ve,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(we,{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(ve,{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(we,{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 Er({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 Tr(t){const[a,n]=A.useState(""),[r,o]=A.useState(!1),[l,c]=A.useState(""),[i,d]=A.useState(""),[u,m]=A.useState(!1),[h,f]=A.useState(null),[p,g]=A.useState(!1),[x,v]=A.useState(null),[j,b]=A.useState(null),C=s.useManagementStore(H=>H.lastSelectedDashboard),R=s.useManagementStore(H=>H.actions.selectDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{resources:E,isLoading:S,isError:N,createResource:k,updateResource:w,deleteResource:L,duplicateResource:D,isCreating:O,isDeleting:M,isSharing:I,isRemovingShares:y,isUpdatingShares:T,shareResource:B,removeResourceShares:z}=tr(()=>{g(!1),v(null),C&&R(C)},()=>{o(!1),c(""),d("")}),{handleShareSubmit:V,handleRemoveAccess:P}=vr((h==null?void 0:h.id)||null,B,z),{currentUser:X}=ds(),K=E.filter(H=>{var F,J;return((F=H==null?void 0:H.title)==null?void 0:F.toLowerCase().includes(a.toLowerCase()))||((J=H==null?void 0:H.description)==null?void 0:J.toLowerCase().includes(a.toLowerCase()))}),_=H=>new Date(H).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{l.trim()&&k({title:l,description:i,isPrivate:!1})},q=H=>{var F;(F=t.onLoadDashboard)==null||F.call(t,H)},U=H=>{v(H),g(!0)},G=()=>{x&&L(x.id)},Q=H=>{b(H),D(H,{onSettled:()=>b(null)})},{startUpdating:Y,stopUpdating:Z,isUpdating:te}=Pt(),ae=(H,F)=>{const J=F.title!==void 0?"title":"description";Y(H,J),w({resourceId:H,data:F},{onSuccess:()=>{Z(H,J)},onError:()=>{Z(H,J)}})},se=H=>{const F=E.find(J=>J.id===H);F&&w({resourceId:H,data:{isPrivate:!F.isPrivate}})},oe=H=>{f(H),X==null||X.type,m(!0)};return De({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:ee.DASHBOARD,userType:"tenant"}),S?e.jsx(zt,{}):N?e.jsx(Er,{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:H=>c(H.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:H=>d(H.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!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:H=>n(H.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:K.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(oa,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):K.map(H=>e.jsx(kr,{dashboard:H,isDeleting:M,isDuplicating:j===H.id,isTitleUpdating:te(H.id,"title"),isDescriptionUpdating:te(H.id,"description"),onLoadDashboard:q,onEditDashboard:t.onEditDashboard,onUpdateDashboard:ae,onDeleteClick:U,onDuplicateDashboard:Q,onTogglePrivacy:se,onShareDashboard:oe,formatDate:_,onDashboardItemClick:t.onDashboardItemClick},H.id))})}),u&&h&&e.jsx(Jt,{resource:h,resourceType:ee.DASHBOARD,onShare:V,isSharing:I,isRemoving:y,isUpdating:T,onClose:()=>{m(!1),f(null)},onRemoveAccess:P}),e.jsx(s.AlertDialog,{open:p,onOpenChange:H=>{!H&&M||(g(H),H||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:M,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:H=>{H.preventDefault(),H.stopPropagation(),G()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:M,children:M?"Deleting...":"Delete"})]})]})})]})}function en({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}=ds(),i=c,[d,u]=s.useLocalStorageState("resource-management-active-tab","dashboards"),m=Yt(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":"hidden -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(Tr,{onLoadDashboard:h,onEditDashboard:f,onDashboardItemClick:r})}),e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Dr,{})})]})})]})})}function Ir(){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]=A.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:k,endUserId:w}=A.useMemo(()=>s.getTenantAndEndUserId(t==null?void 0:t.accessToken),[t==null?void 0:t.accessToken]),L=A.useMemo(()=>k||w,[k,w]),D=()=>{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:[]},B={id:s.v4(),cards:[T],activeCardId:T.id};b(N.id,B),C(B.id)},O=()=>{E(!0)};async function M(){if(m(!0),!r||!o)return;const T=Bs(l),B=JSON.stringify(T),z={...o,template:B,filterValues:p};await Ss(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(da,{className:"h-4 w-4"})}),!g&&e.jsx(s.Label,{children:I})]}),e.jsxs("div",{className:"flex gap-2",children:[!1,!g&&e.jsx(Ra,{}),!g&&e.jsx(Bt,{}),c&&!g&&L&&e.jsx(Aa,{}),!g&&L&&e.jsx(La,{}),c&&!g&&e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!c,onClick:D,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:M,size:"sm",children:e.jsx(Mt,{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(en,{isOpen:h,onClose:()=>f(!1)})]})]})}function Mr({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(It,{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(ba,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(ya,{className:"size-4"});if(t==="Table")return e.jsx(cs,{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(It,{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(Mr,{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]=A.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 Vs({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($e,{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(es,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(Qn,{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 ps({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(Vs,{column:t}),e.jsx("span",{children:t.column_name})]})}function Lr({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 Rr({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(ps,{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(ps,{column:a})}),e.jsx(Lr,{id:a.column_name,type:"column",children:e.jsx(ps,{column:a})})]})}const fs={id:"__placeholder__",role:"groupby",type:"string"},gs={id:"__placeholder__",role:"groupby",type:"string"},js={id:"__placeholder__",role:"metric",type:"number"},ys={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},sn={id:"__placeholder__"},Te="droppable-group-by",Ie="droppable-metrics",Me="droppable-pivot-by",ts="sortable-group-by",ws="sortable-metrics",ns="sortable-pivot-by",Ds="droppable-filters",ks="sortable-filters",_s="sortable-order-by";function Or(){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 B;const{active:y,over:T}=I;if(((B=y.data.current)==null?void 0:B.type)==="column"&&T){const z=T.id,V=j.find(_=>_.column_name===y.id);if(!V)return;const P=s.isNumberDataType(V.data_type),X=s.isTextDataType(V.data_type),K=s.isDateDataType(V.data_type);if(X||K){if(a.some($=>$.id===z)){const $=a.findIndex(U=>U.id===z);c($);const q=a.filter(U=>U.id!==fs.id);q.splice($,0,fs),d(q)}else if(T.id===Te){c(a.length);const $=[...a,fs];d($),u(n),m(r)}}if(X||K){if(l.some($=>$.id===z)){const $=l.findIndex(U=>U.id===z);c($);const q=l.filter(U=>U.id!==gs.id);q.splice($,0,gs),h(q)}else if(T.id===Me){c(l.length);const $=[...l,gs];h($),d(a),u(n),m(r)}}if(P||X){if(n.some($=>$.id===z)){console.log("isOverMetricSortable",z);const $=n.findIndex(U=>U.id===z);c($);const q=n.filter(U=>U.id!==js.id);q.splice($,0,js),u(q)}else if(T.id===Ie){c(n.length);const $=[...n,js];u($),m(r),d(a),h(l)}}if(S(V)){if(r.some($=>$.id===z)){const $=r.findIndex(U=>U.id===z);c($);const q=r.filter(U=>U.id!==ys.id);q.splice($,0,ys),m(q)}else if(T.id===Ds){c(r.length);const $=[...r,ys];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:B}=I,z=[...n],V=t!==null?t:n.length,P={...I,id:fe(T),name:T,label:He(T,y),type:B,role:"metric",aggregate:y};z.splice(V,0,P),p(z)}function k(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...l],B=t!==null?t:l.length;let z;y?z={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(B,0,z),v(T)}function w(I){const y=s.isTextDataType(I.data_type);s.isDateDataType(I.data_type);const T=[...a],B=t!==null?t:a.length;let z;y?z={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:z={...I,id:fe(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Pe(I.column_name,"month"),granularity:"month"},T.splice(B,0,z),f(T)}function L(I){const y=[...r],T=t!==null?t:r.length,B={...I,id:fe(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,B),g(y)}function D(I){var z,V,P,X,K,_,$,q;const{active:y,over:T}=I,B=y.data.current;if((B==null?void 0:B.type)==="column"&&T){const U=j.find(Z=>Z.column_name===y.id);if(!U)return;const G=s.isNumberDataType(U.data_type),Q=s.isTextDataType(U.data_type),Y=s.isDateDataType(U.data_type);(Q||Y)&&(T.id===Te||((z=T.data.current)==null?void 0:z.type)===ts)&&w(U),(Q||Y)&&(T.id===Me||((V=T.data.current)==null?void 0:V.type)===ns)?k(U):(G||Q)&&(T.id===Ie||((P=T.data.current)==null?void 0:P.type)===ws)?(G&&N(U),Q&&N(U,"COUNT")):S(U)&&(T.id===Ds||((X=T.data.current)==null?void 0:X.type)===ks)&&L(U)}if(T&&((K=T.data.current)==null?void 0:K.type)===ts&&a.some(U=>U.id===y.id)){const U=a.findIndex(Q=>Q.id===y.id),G=a.findIndex(Q=>Q.id===T.id);if(U!==-1&&G!==-1&&U!==G){const Q=[...a],[Y]=Q.splice(U,1);Q.splice(G,0,Y),f(Q)}}if(T&&((_=T.data.current)==null?void 0:_.type)===ns&&l.some(U=>U.id===y.id)){const U=l.findIndex(Q=>Q.id===y.id),G=l.findIndex(Q=>Q.id===T.id);if(U!==-1&&G!==-1&&U!==G){const Q=[...l],[Y]=Q.splice(U,1);Q.splice(G,0,Y),v(Q)}}if(T&&(($=T.data.current)==null?void 0:$.type)===ws&&n.some(U=>U.id===y.id)){const U=n.findIndex(Q=>Q.id===y.id),G=n.findIndex(Q=>Q.id===T.id);if(U!==-1&&G!==-1&&U!==G){const Q=[...n],[Y]=Q.splice(U,1);Q.splice(G,0,Y),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),G=r.findIndex(Q=>Q.id===T.id);if(U!==-1&&G!==-1&&U!==G){const Q=[...r],[Y]=Q.splice(U,1);Q.splice(G,0,Y),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,B=y.data.current;if((B==null?void 0:B.type)===_s&&T){const z=o.findIndex(P=>Ue(P.columnId)===y.id),V=o.findIndex(P=>Ue(P.columnId)===T.id);if(z!==-1&&V!==-1&&z!==V){const P=[...o],[X]=P.splice(z,1);P.splice(V,0,X),x(P)}}}function M(){i(null),c(null),d(a),u(n),m(r)}return{handleDragOver:R,handleDragEnd:D,handleDragStart:E,handleDragCancel:M,sensors:C}}function fe(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 Ue(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 Fr({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,B;return(B=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:B.metricColumns});s.useEditorStore(y=>{var T,B;return(B=(T=y.card)==null?void 0:T.queryConfig)==null?void 0:B.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 k(y){var T;if(l){const B=s.createSqlGenConfig(y,o);C(B);const z=(T=S==null?void 0:S.find(P=>P.id===h))==null?void 0:T.name,V=s.getSql(B,s.fmt(t),s.fmt(a),z||"",E,d||"");V&&(j(V),b(!0))}if(!l){if(s.isTextDataType(y.data_type))if(i&&i.length>0){const B={...y,role:"groupby",id:fe(y.column_name),name:y.column_name,type:y.data_type};v(B)}else{const B={...y,role:"metric",id:fe(y.column_name),name:y.column_name,label:He(y.column_name,"COUNT"),type:y.data_type,aggregate:"COUNT"};x(B)}if(s.isDateDataType(y.data_type)){const B={...y,role:"groupby",id:fe(y.column_name),name:y.column_name,type:y.data_type,label:Pe(y.column_name,"month"),granularity:"month"};v(B)}if(s.isNumberDataType(y.data_type)){const B={...y,role:"metric",id:fe(y.column_name),name:y.column_name,label:He(y.column_name,"SUM"),type:y.data_type,aggregate:"SUM"};x(B)}}}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 D(){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 M(y){return l?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>k(y),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Vs,{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(Rr,{onClick:k,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(pa,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:D,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:M(y)},y.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function tn({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:k,isSchemaLoadingOrFetching:w,isSchemaError:L,isColumnsError:D,isColumnsLoadingOrFetching:O,isTableLoadingOrFetching:M,isTableError:I,connectionType:y,isNonDbConnection:T,refetchDatabases:B,refetchModels:z,refetchSchemas:V,refetchTables:P,refetchColumns:X,refetchConnections:K,handleConnectionChange:_,handleDatabaseChange:$,handleSchemaChange:q,handleDatamodelChange:U,handleTableChange:G,tableName:Q,schemaName:Y}=s.useEditorAside(),{data:Z,refetch:te}=s.useDashboardCardQuery(n);function ae(){return t?t(Y,Q,b):e.jsx(Fr,{schemaName:Y,tableName:Q,columns:b,status:O?"Loading...":D?"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 H(){if(!r||y==="S3"||y==="API")return null;if(!l||l==="none")return e.jsx(ze,{refetch:B,showNone:!0,onChange:$,isError:k,isLoading:N,items:v,value:c||"",title:"Database",type:"combobox"})}function F(){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:V,onChange:q,isError:L,isLoading:w,items:x,value:i||"",title:"Schema",type:"combobox"})}function be(){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:G,isError:I,items:j,isLoading:M,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:K,items:p,title:"Connection",value:r||"",onChange:_,isLoading:C,isError:E,type:"combobox",connectionTooltip:((ke=p==null?void 0:p.find(ne=>ne.id===r))==null?void 0:ke.type)||""}),H(),F(),J(),ie(),be()]}),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(ga,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function nn({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,l]=A.useState(!1),c=A.useRef(null),i=A.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 an({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(nn,{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(ta,{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(ca,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function rn({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(an,{sql:t,error:a,onDebugWithAssistant:n})})]})}var on={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},pt=A.createContext&&A.createContext(on),Br=["attr","size","title"];function zr(t,a){if(t==null)return{};var n=Pr(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 Pr(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 as(){return as=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},as.apply(this,arguments)}function ft(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 rs(t){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?ft(Object(n),!0).forEach(function(r){Vr(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):ft(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Vr(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=Ur(t,"string");return typeof a=="symbol"?a:a+""}function Ur(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 ln(t){return t&&t.map((a,n)=>A.createElement(a.tag,rs({key:n},a.attr),ln(a.child)))}function Le(t){return a=>A.createElement($r,as({attr:rs({},t.attr)},a),ln(t.child))}function $r(t){var a=n=>{var{attr:r,size:o,title:l}=t,c=zr(t,Br),i=o||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),A.createElement("svg",as({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:d,style:rs(rs({color:t.color||n.color},n.style),t.style),height:i,width:i,xmlns:"http://www.w3.org/2000/svg"}),l&&A.createElement("title",null,l),t.children)};return pt!==void 0?A.createElement(pt.Consumer,null,n=>a(n)):a(on)}function qr(t){return Le({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 cn(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=A.useRef(),h=A.useRef({}),f=r.cards.find(x=>x.id===l),p=A.useCallback(()=>{let x="";return t==="python"&&(x=(f==null?void 0:f.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(f==null?void 0:f.sql)||""),x},[t,f]);A.useEffect(()=>{if(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]),A.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]),A.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 Yr(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=cn("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}=cn("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 Us({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const n=s.useEditorStore(i=>i.card);zs(((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}=Ps();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 Qr(){const t=s.useQueryClient(),[a,n]=A.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:l}=Ps(),c=s.useSelectedVisual(),i=ar(),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(Mt,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function $s(){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 us(){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 Kr(){const t=s.useQueryClient(),[a,n]=A.useState(!1),[r,o]=A.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 X;return(X=P==null?void 0:P.card)==null?void 0:X.sql}),d=s.useEditorStore(P=>{var X;return(X=P==null?void 0:P.card)==null?void 0:X.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:k,isFetching:w,isSuccess:L,isError:D,error:O,queryKey:M,refetch:I,errorMessage:y}=s.useDashboardCardQuery(l);A.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]),A.useEffect(()=>{(k||w)&&S(!0),(D||L)&&S(!1),D&&(h([]),g(""))},[k,w,N,g,D,L,S,h,O]),A.useEffect(()=>{R&&(t.getQueryData(M)||I(),E(!1))},[R,I,E,M,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
 
@@ -422,4 +422,4 @@ ${w.joinType} JOIN ${L.name}
422
422
  ON ${O}`}),k},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(w=>!w.source.name||!w.target.name)||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.length===0))||n.joins.some(w=>w.joinKeyGroups.some(L=>L.keys.some(D=>!D.source.name||!D.target.name||!D.operator))))}}function oi({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:l}=s.useEditorActions();s.useEditorStore(D=>D.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:f,moveJoinUp:p,moveJoinDown:g,toggleJoinExpansion:x,getAvailableSourceEntities:v,getAvailableTargetEntities:j,addJoinKeyGroup:b,updateGroupOperator:C,removeJoinKeyGroup:R,addJoinKey:E,updateJoinKey:S,removeJoinKey:N,generateSQLPreview:k,isValidConfiguration:w}=ri({initialJoinPlan:t,availableDataSources:a}),L=D=>{const O=c.find(M=>M.entityName===D);return(O==null?void 0:O.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:D=>{const O=a.find(M=>M.name===D);u({...i,baseEntity:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:D,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(D=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:D.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:D.type}),D.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},D.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:k()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(D=>{const O=a.find(y=>y.name===D.source.name),M=a.find(y=>y.name===D.target.name),I=d.has(D.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:D.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",D.sequence,O&&M&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",O.name," → ",M.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(D.id),disabled:D.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(D.id),disabled:D.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(D.id),children:I?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(D.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),I&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:D.source.name,onValueChange:y=>{const T=a.find(B=>B.name===y);f(D.id,{source:{connectionId:(T==null?void 0:T.connectionId)||"",connectionType:(T==null?void 0:T.connectionType)||"none",type:(T==null?void 0:T.type)||"table",name:y,database:T==null?void 0:T.database,schema:T==null?void 0:T.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(D.id).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name]})},y.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:D.joinType,onValueChange:y=>f(D.id,{joinType:y}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:D.target.name,onValueChange:y=>{const T=a.find(B=>B.name===y);f(D.id,{target:{connectionId:(T==null?void 0:T.connectionId)||"",connectionType:(T==null?void 0:T.connectionType)||"none",type:(T==null?void 0:T.type)||"table",name:y,database:T==null?void 0:T.database,schema:T==null?void 0:T.schema}})},disabled:!D.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:D.source.name?j(D.source.name).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,y.name===D.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},y.name)):[]})]})]})]}),D.source.name&&D.target.name&&O&&M&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>b(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),D.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:D.joinKeyGroups.map((y,T)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",T+1]}),T>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:y.operator,onValueChange:B=>C(D.id,T,B),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(D.id,T),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[y.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:y.keys.map((B,z)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[z>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:y.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:B.source.name,onValueChange:V=>S(D.id,T,z,"sourceColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:L(D.source.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:B.operator,onValueChange:V=>S(D.id,T,z,"operator",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:B.target.name,onValueChange:V=>S(D.id,T,z,"targetColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:L(D.target.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>N(D.id,T,z),children:e.jsx(s.X,{className:"size-3.5"})})]},B.id||z))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>E(D.id,T),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},y.id))})]})]})]},D.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(i),disabled:!w(),children:"Save"})]})]})}function yt({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:l,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(oi,{joinPlan:r,availableDataSources:o,onSave:c,onCancel:i,onRemove:l})]}),t]})}function ii({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const o=[...t].sort((c,i)=>c.sequence-i.sequence),l=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:l==null?void 0:l.type}),e.jsx("span",{className:"text-xs font-medium",children:l==null?void 0:l.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(c=>{const i=n.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((o,l)=>o.sequence-l.sequence).map((o,l)=>{const c=n.find(d=>d.name===o.source.name),i=n.find(d=>d.name===o.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:l+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},o.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function li(){var m,h;const t=s.useEditorStore(f=>f.card),a=s.useEditorStore(f=>f.actions.updateCardConfig),n=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,o]=A.useState(!1),l=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=f=>{a(t.id,{...t==null?void 0:t.config,joinPlan:f}),o(!1)},i=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{o(!1)},u=()=>{const f=[...n.joins].sort((x,v)=>x.sequence-v.sequence),p=n.baseEntity;if(!p.name)return"SELECT * FROM table -- Please select a base entity";let g=`SELECT *
423
423
  FROM ${p.name}`;return f.forEach(x=>{const v=l.find(C=>C.name===x.target.name);if(!v)return;const j=x.joinKeyGroups.filter(C=>C.keys&&C.keys.length>0).map(C=>{const R=C.keys.filter(E=>{var S,N,k,w;return((S=E.source)==null?void 0:S.name)&&((N=E.target)==null?void 0:N.name)&&((k=E.source)==null?void 0:k.entityName)&&((w=E.target)==null?void 0:w.entityName)}).map(E=>`${E.source.entityName}.${E.source.name} ${E.operator} ${E.target.entityName}.${E.target.name}`);return R.length>1?`(${R.join(` ${C.operator} `)})`:R[0]}).filter(Boolean),b=j.length>1?j.join(" OR "):j[0]||"condition_here";g+=`
424
424
  ${x.joinType} JOIN ${v.name}
425
- ON ${b}`}),g};return l.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>o(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(ii,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:l,generateSQLPreview:u})})]})}),e.jsx(yt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(yt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>o(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function ci({entity:t,title:a,maxDetails:n=10}){const o=s.getEntityDetails(t).slice(0,n),l=o.find(i=>i.label==="Description"),c=o.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a||s.getDisplayName(t)}),l&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function di({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((a,n)=>{const r=s.getEntityDetails(a),o=r.find(c=>c.label==="Description"),l=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(a)}),o&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),l.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:l.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function ui({isVisible:t,onToggleVisibility:a}){s.useEditorStore(m=>m.isDevMode),s.useEditorStore(m=>m.card.connectionId),s.useDashboardStore(m=>m.isVisualEditing);const[n,r]=A.useState(!1),[o,l]=A.useState(!0),c=s.useEditorStore(m=>m.card.dataSource),{updateDataSource:i}=s.useEditorActions(),d={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},u={...d,...c,selectedEntities:(c==null?void 0:c.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!o}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>l(!o),className:"h-6 w-6 p-0",children:o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${o?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[u.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[u.selectedEntities.slice(0,3).map((m,h)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(m),e.jsx("button",{onClick:f=>{f.stopPropagation();const p=u.selectedEntities.filter(g=>!(g.name===m.name&&g.type===m.type));i({...d,...c,selectedEntities:p})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(ci,{entity:m})]},`${m.type}-${m.name}-${h}`)),u.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",u.selectedEntities.length-3," more"]})}),e.jsx(di,{entities:u.selectedEntities.slice(3)})]})]})}),e.jsx(li,{})]})]}),e.jsx(ai,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(c==null?void 0:c.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:u,fallbackDataSource:d})]})}const Ze=[{id:"table",icon:cs,label:"Table"},{id:"bar",icon:os,label:"Bar Chart"},{id:"line",icon:is,label:"Line Chart"},{id:"area",icon:Dt,label:"Area Chart"},{id:"stackedBar",icon:Is,label:"Stacked Bar Chart"},{id:"combo",icon:Kn,label:"Combo Chart"},{id:"stackedLine",icon:Qs,label:"Stacked Line Chart"},{id:"scatter",icon:As,label:"Scatter Chart"},{id:"bubble",icon:Gs,label:"Bubble Chart"},{id:"pie",icon:ls,label:"Pie Chart"},{id:"doughnut",icon:Ls,label:"Doughnut Chart"},{id:"funnel",icon:Hs,label:"Funnel Chart"},{id:"radar",icon:Os,label:"Radar Chart"},{id:"polarArea",icon:Ys,label:"Polar Area Chart"},{id:"tornado",icon:Fs,label:"Tornado Chart"},{id:"range",icon:Ms,label:"Range Chart"},{id:"kpi",icon:Ks,label:"KPI"},{id:"text",icon:St,label:"Text"},{id:"map",icon:Rs,label:"Map"}],Zs=t=>{const a=t.toLowerCase();for(const n of Ze)if(n.id==="doughnut"){if(a.includes("doughnut")||a.includes("donut")){const r=n.icon;return A.createElement(r,{className:"h-4 w-4"})}}else if(a.includes(n.id.toLowerCase())){const r=n.icon;return A.createElement(r,{className:"h-4 w-4"})}return null},mi="chart-selector-standard-first";function hi(){const[t,a]=s.useLocalStorageState(mi,!0);return{standardFirst:t,updatePreference:a}}const vt=({pluginVisual:t,index:a,onSelect:n})=>{const r=ms(t.icon||""),o=t.name.charAt(0).toUpperCase(),l=Zs(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):l||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:o}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},bt=["default","standardPlugin","customPlugin"];function xi({selectedChart:t,onChartChange:a}){var S;const[n,r]=A.useState([]),[o,l]=A.useState(!1),{data:c}=qs();hi();const d=((S=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:S.url)||"";zs(d);const{setCardType:u,setCardPreferences:m,setIsDevMode:h}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:f,setCustomCardPreferences:p,setQueryConfig:g}=s.useEditorActions(),[x,v]=s.useLocalStorageState("chart-section-active",null),j=A.useMemo(()=>x?[x,...bt.filter(N=>N!==x)]:bt,[x]);A.useEffect(()=>{(async()=>{if(c){const w=(await Promise.allSettled(c.plugins.map(async L=>{try{return(await s.loadManifest(L.value)).visuals.map(O=>({name:O.name,icon:O.icon,url:L.value,pluginName:L.label,pluginType:L.type,chartType:O.chartType,componentType:O.componentType}))}catch(D){return console.error(`Failed to load manifest for plugin ${L.label}`,D),[]}}))).filter(L=>L.status==="fulfilled").flatMap(L=>L.value);r(w)}})()},[c]);function b(N){f(null),m({}),u(N),["custom","text","map"].includes(N)&&(h(!0),g(void 0)),a(N),l(!1)}function C(N){f(null),m({}),u("custom"),p({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),g(void 0),a("custom"),l(!1)}const R=()=>{var k;if(t==="custom"){const w=s.useEditorStore.getState().card;return((k=w==null?void 0:w.customCardPreferences)==null?void 0:k.componentName)||"Custom Visual"}const N=Ze.find(w=>w.id===t);return(N==null?void 0:N.label)||"Select chart type"},E=()=>{var k,w;if(t==="custom"){const L=s.useEditorStore.getState().card,D=(k=L==null?void 0:L.customCardPreferences)==null?void 0:k.icon,O=(w=L==null?void 0:L.customCardPreferences)==null?void 0:w.componentName;if(D&&O)return e.jsx(pi,{icon:D,componentName:O});if(O){const M=Zs(O);if(M)return M}return e.jsx(qe,{className:"h-4 w-4"})}const N=Ze.find(L=>L.id===t);if(N){const L=N.icon;return e.jsx(L,{className:"h-4 w-4"})}return e.jsx(qe,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:o,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[E(),e.jsx("span",{children:R()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[335px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),j.map(N=>{if(N==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="default",onCheckedChange:k=>v(k?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:Ze.map(k=>{const w=k.icon;return e.jsx(s.CommandItem,{value:`${k.label} ${k.id} chart graph visualization`,onSelect:()=>b(k.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{className:"h-4 w-4"}),e.jsx("span",{children:k.label})]})},k.id)})},"default");if(N==="standardPlugin"){const k=n.filter(w=>w.pluginType==="standard");return k.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="standardPlugin",onCheckedChange:w=>v(w?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.filter(w=>w.componentType==="chart").map((w,L)=>e.jsx(vt,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"standardPlugin"):null}if(N==="customPlugin"){const k=n.filter(w=>w.pluginType==="custom");return k.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="customPlugin",onCheckedChange:w=>v(w?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.map((w,L)=>e.jsx(vt,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"customPlugin"):null}return null})]})]})})]})})}const pi=({icon:t,componentName:a})=>{const n=ms(),r=Zs(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(qe,{className:"h-4 w-4"})},Cn=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Ge,{className:"h-3 w-3"})}):a==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx($e,{className:"h-3 w-3"})}):a==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(es,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ge,{className:"h-3 w-3"})})};function fi({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=A.useState(t),[o,l]=A.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:o?n:t,onChange:u=>{r(u.target.value),l(!0)},onFocus:()=>l(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&o&&n!==t?(a(n),l(!1)):u.key==="Escape"&&(r(t),l(!1))},"aria-label":"Edit alias template"}),o&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),l(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),l(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function gi({valueAliases:t,onValueAliasesChange:a}){const[n,r]=A.useState(null),[o,l]=A.useState(""),[c,i]=A.useState(""),d=()=>{a({...t,"":""})},u=h=>{const f={...t};delete f[h],a(f)},m=h=>{const f={...t};delete f[h],f[o]=c,a(f),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,f],p)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:o,onChange:g=>l(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?m(h):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?m(h):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),l(h),i(f)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),l(h),i(f)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+p)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Nt({value:t,onSave:a,placeholder:n="",type:r="text",className:o=""}){const[l,c]=A.useState(t??""),[i,d]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const u=()=>{a(l),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${o}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:i?l:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&l!==t?u():h.key==="Escape"&&m()},"aria-label":n||"Edit field"}),i&&l!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function ji({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:l=!1,cardType:c}){var tt;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:f}=s.useSortable({id:t.id}),p=s.useEditorStore(W=>W.card),{updateLabel:g,handleAggregationChange:x,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:R,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:N,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:w}=Xs(p),[L,D]=A.useState(!1),[O,M]=A.useState(t.dateFormat||"YYYY-MM-DD"),[I,y]=A.useState(t.customFormat||""),[T,B]=A.useState(!!t.customFormat),[z,V]=A.useState(t.granularity||"day"),[P,X]=A.useState(t.aliasTemplate||""),[K,_]=A.useState(t.valueAliases||{}),$=W=>{W==="custom"?B(!0):(B(!1),M(W),a==="groupBy"&&v(n,W,""))},q=W=>{y(W),a==="groupBy"&&v(n,"custom",W)},U=W=>{var _e;V(W);const xe=(_e=H(W)[0])==null?void 0:_e.value;xe&&!T&&(M(xe),a==="groupBy"&&v(n,xe,"")),a==="groupBy"&&j(n,W)},G=W=>{X(W),a==="metrics"&&b(n,W)},Q=W=>{_(W),a==="metrics"&&C(n,W)},Y=W=>{g(a,n,W)},Z=()=>{R(a,n)},te={transform:s.CSS.Transform.toString(m),transition:h},ae=s.getDataType(t.dataType),se=ae==="date",oe=c==="kpi",H=W=>{switch(W){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},F=H(z),J=!oe&&a!=="pivotBy",ie=se&&a==="groupBy",be=!oe&&se&&a==="groupBy",ke=oe&&se&&a==="groupBy",ne=oe&&a==="metrics"&&((tt=p.config)==null?void 0:tt.comparisonType)==="target",le=a==="metrics",ce=()=>e.jsx("div",{onPointerDown:W=>{W.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),Dn=()=>J?e.jsx(Nt,{value:t.label??"",onSave:Y,placeholder:"Display label...",type:"text"}):null,st=()=>ie?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:z,onValueChange:U,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(W=>e.jsx(s.SelectItem,{className:"text-xs",value:W,children:s.toTitleCase(W)},W))})]})]}):null,kn=()=>be?e.jsxs(e.Fragment,{children:[st(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:T?"custom":O,onValueChange:$,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:F.map(W=>e.jsx(s.SelectItem,{className:"text-xs",value:W.value,children:W.label},W.value))})]}),T&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:I,onChange:W=>{W.stopPropagation(),q(W.target.value)},onClick:W=>W.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,En=()=>{var W,ge,xe,_e,nt;return ke?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((W=p.config)==null?void 0:W.comparisonType)||"none",onValueChange:E,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ge=p.config)==null?void 0:ge.showTrendline)||!1,onCheckedChange:S})]})}),((xe=p.config)==null?void 0:xe.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((_e=p.config)==null?void 0:_e.trendlineWindow)||30,onChange:Mn=>{const An=parseInt(Mn.target.value)||30;N(An)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((nt=p.config)==null?void 0:nt.trendlineGranularity)||"day",onValueChange:k,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},Tn=()=>{var W,ge;return ne?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(Nt,{value:((W=p.config)==null?void 0:W.targetValue)!==void 0&&((ge=p.config)==null?void 0:ge.targetValue)!==null?String(p.config.targetValue):"",onSave:xe=>{!isNaN(Number(xe))&&xe!==null?w(Number(xe)):w(0)},placeholder:"Enter target value...",type:"text"})]}):null},In=()=>le?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:W=>{x(n,W)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(vn,{column:t}),l&&e.jsxs(e.Fragment,{children:[e.jsx(fi,{aliasTemplate:P,onAliasTemplateChange:G}),e.jsx(gi,{valueAliases:K,onValueAliasesChange:Q})]})]}):null;return e.jsxs("div",{ref:u,style:te,...i,...d,className:`group mx-auto flex w-full max-w-[300px] flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.GripVertical,{className:"h-3 w-3"}),e.jsx(Cn,{dataType:ae}),e.jsx(Ws,{className:"max-w-[180px] flex-1 text-sm",children:t.label||t.name}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:W=>{W.stopPropagation(),D(!L)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${L?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:W=>{W.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ge=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ge),o(ge)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:W=>{W.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),L&&e.jsxs("div",{className:"space-y-3",children:[ce(),Dn(),c==="kpi"&&st(),kn(),En(),Tn(),In()]})]})}function yi({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Je({zone:t,fields:a,label:n,placeholder:r,shouldShow:o,hasPivotColumns:l=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(g=>g.card),m=s.useEditorStore(g=>g.card.type),h=a.length>0,f=(g,x)=>{var j;!((j=u.config)!=null&&j.sortByColumns)||u.config.sortByColumns.findIndex(b=>b.id===g)===-1||d(u.id,g,{direction:x})};if(t==="sortBy"&&o===!1)return null;const p=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),p&&e.jsx(yi,{concept:t})]}),e.jsx("div",{ref:i,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"border-muted-foreground/20 bg-background"}`,children:a.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:a.map(g=>g.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((g,x)=>{const j=g.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(ji,{field:g,zone:t,index:x,sortDirection:j,onSortDirectionChange:b=>f(g.id,b),hasPivotColumns:l,cardType:m})})},g.id)})})})})]})}function vi({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const o=s.useEditorStore(h=>h.card),l=o==null?void 0:o.type,c=t.length>0||n.length>0,i=l!=="kpi",d=l!=="kpi"&&c,u=()=>l==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},m=()=>l==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Je,{zone:"groupBy",fields:t,label:u().label,placeholder:u().placeholder}),i&&e.jsx(Je,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Je,{zone:"metrics",fields:n,label:m().label,placeholder:m().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(Je,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function bi({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:l}){const c=s.useEditorStore(h=>h.showAIDialog),i=n.length>0||r.length>0||o.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-96 flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(xi,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||m}),children:e.jsx(us,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(Da,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(vi,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:l}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Ni({initialFilters:t,availableFields:a}={}){const[n,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(E=>E.card.dataSource);const{columns:o,isLoading:l}=s.useColumns(),i=a||o||[],d={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=E=>{const S=N=>{if(N.id===E){const k=i[0]||d;return{...N,conditions:[...N.conditions,{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},m=E=>{const S=N=>{if(N.id===E){const k=i[0]||d;return{...N,groups:[...N.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}],groups:[]}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},h=(E,S)=>{const N=k=>k.id===E?{...k,conditions:k.conditions.filter(w=>w.id!==S)}:{...k,groups:k.groups.map(N)};r(N(n))},f=(E,S)=>{const N=k=>k.id===E?{...k,groups:k.groups.filter(w=>w.id!==S)}:{...k,groups:k.groups.map(N)};r(N(n))},p=(E,S,N,k)=>{if(N==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const w=L=>L.id===E?{...L,conditions:L.conditions.map(D=>D.id===S?{...D,[N]:k}:D)}:{...L,groups:L.groups.map(w)};r(w(n))},g=(E,S,N)=>{const k=w=>w.id===E?{...w,conditions:w.conditions.map(L=>L.id===S?{...L,...N}:L)}:{...w,groups:w.groups.map(k)};r(k(n))},x=(E,S)=>{const N=k=>k.id===E?{...k,logicalOperator:S}:{...k,groups:k.groups.map(N)};r(N(n))},v=(E,S)=>{const N=k=>k.id===E?{...k,negate:S}:{...k,groups:k.groups.map(N)};r(N(n))},j=(E,S,N)=>{const k=w=>w.id===E?{...w,conditions:s.arrayMove(w.conditions,S,N)}:{...w,groups:w.groups.map(k)};r(k(n))},b=(E,S,N)=>{const k=w=>w.id===E?{...w,groups:s.arrayMove(w.groups,S,N)}:{...w,groups:w.groups.map(k)};r(k(n))},C=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const S=k=>{let w="";typeof k.field=="object"?w=k.field.entityName?`${k.field.entityName}.${k.field.name}`:k.field.name:w=String(k.field);const L=k.operator;let D=k.value;if(k.field.dataType==="string"&&!["in","not in"].includes(k.operator))typeof D=="string"?D=`'${D}'`:Array.isArray(D)&&(D=`'${D.join(", ")}'`);else if(k.field.dataType==="date")(typeof D=="string"||D instanceof Date)&&(D=`DATE('${D}')`);else if(["in","not in"].includes(k.operator)){let O=[];Array.isArray(D)?O=D.map(M=>typeof M=="string"?`'${M}'`:String(M)):typeof D=="string"?O=D.split(",").map(M=>{const I=M.trim();return k.field.dataType==="string"?`'${I}'`:I}):typeof D=="number"&&(O=[String(D)]),D=`(${O.join(", ")})`}switch(L){case"contains":return typeof D=="string"?`${w} LIKE '%${D.replace(/'/g,"")}'`:`${w} LIKE '%${String(D)}'`;case"startsWith":return typeof D=="string"?`${w} LIKE '${D.replace(/'/g,"")}%'`:`${w} LIKE '${String(D)}%'`;case"endsWith":return typeof D=="string"?`${w} LIKE '%${D.replace(/'/g,"")}'`:`${w} LIKE '%${String(D)}'`;default:return`${w} ${L} ${D}`}},N=k=>{const w=k.conditions.map(S),L=k.groups.map(I=>N(I)),D=[...w,...L].filter(Boolean);if(D.length===0)return"";const O=D.join(` ${k.logicalOperator} `),M=D.length>1?`(${O})`:O;return k.negate?`NOT ${M}`:M};return N(E)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:l,addCondition:u,addGroup:m,removeCondition:h,removeGroup:f,updateCondition:p,updateConditionFields:g,updateGroupOperator:x,updateGroupNegate:v,reorderConditions:j,reorderGroups:b,generateSQLPreview:C,hasAnyFilters:R}}function Ci({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Si=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(aa,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},wi=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Di({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[l,c]=A.useState(!1),i=A.useMemo(()=>{const d={};return n.forEach(u=>{const m=wi(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:l,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:s.cn("justify-between",!t&&"text-muted-foreground",o),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ci,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Si(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((f,p)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{a(f),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===f.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+p))]},`${d}-${m}`))},d))})]})})]})}function et(t){var g;const a=s.useEditorStore(x=>x.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(x=>x.card.config),o=r==null?void 0:r.joinPlan,l={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...l,role:"sortby",direction:"asc"},d={joinPlan:o,groupByColumns:[l],metricColumns:[c],sortByColumns:[i]},u=((g=a.dataSource)==null?void 0:g.connectionId)||a.connectionId,{data:m,isPending:h,error:f}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:u,cardConfig:d,cardDataSource:a.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!u,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:h,error:f}}function ki({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[l,c]=ue.useState(!1),{filterValues:i}=et(t),d=m=>{n(a.filter(h=>h!==m))},u=m=>{a.includes(m)?n(a.filter(h=>h!==m)):n([...a,m])};return e.jsx("div",{className:s.cn("w-full",o),children:e.jsxs(s.Popover,{open:l,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(m=>{const h=i.find(f=>f.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:f=>{f.key==="Enter"&&d(m)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}const Sn=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=Sn(n)}),a};function Ei({field:t,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:l,isPending:c,error:i}=et(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:o||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:l.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}const Ti=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Ii=["=","!=","contains","startsWith","endsWith","in","not in"],Mi=["=","!=",">",">=","<","<=","in","not in"],Ai=["=","!="],Li=["=","!=",">",">=","<","<=","in","not in"];function Ri(t){switch(t){case"string":return Ii;case"number":return Mi;case"boolean":return Ai;case"date":return Li;default:return Ti}}function wn({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:l,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:f,transition:p,isDragging:g}=s.useSortable({id:t.id}),{isPending:x,error:v}=et(t.field),j={transform:s.CSS.Transform.toString(f),transition:p};return e.jsxs("div",{ref:h,style:j,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:b=>c(n,b),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Di,{value:t.field,onValueChange:b=>{d(n,t.id,{field:b,value:""})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:b=>{b==="in"||b==="not in"?d(n,t.id,{operator:b,value:[]}):d(n,t.id,{operator:b,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ri(s.getDataType(t.field.dataType)).map(b=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:b,children:b},b))})]}),s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?x?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ki,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(b=>typeof b=="string")?t.value:[],onChange:b=>d(n,t.id,{value:b}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Ei,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:b=>d(n,t.id,{value:b==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:b=>o(n,t.id,"value",b.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>l(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Oi({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:l,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:f,availableFields:p,renderFilterGroup:g,updateConditionFields:x}){const{attributes:v,listeners:j,setNodeRef:b,transform:C,transition:R,isDragging:E}=s.useSortable({id:t.id}),S={transform:s.CSS.Transform.toString(C),transition:R},N=w=>{const{active:L,over:D}=w;if(D&&L.id!==D.id){const O=t.conditions.findIndex(I=>I.id===L.id),M=t.conditions.findIndex(I=>I.id===D.id);O!==-1&&M!==-1&&u(t.id,O,M)}},k=w=>{const{active:L,over:D}=w;if(D&&L.id!==D.id&&n){const O=t.groups.findIndex(I=>I.id===L.id),M=t.groups.findIndex(I=>I.id===D.id);O!==-1&&M!==-1&&m(n,O,M)}};return e.jsxs("div",{ref:b,style:S,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...j,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:w=>r(t.id,w),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&l(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:N,children:e.jsx(s.SortableContext,{items:t.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((w,L)=>e.jsx(wn,{condition:w,index:L,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:x},w.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:k,children:e.jsx(s.SortableContext,{items:t.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(w=>g(w,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Fi({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:l,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:f,updateConditionFields:p,updateGroupOperator:g,updateGroupNegate:x,reorderConditions:v,reorderGroups:j,generateSQLPreview:b,hasAnyFilters:C,setCurrentFilters:R}=Ni({initialFilters:t,availableFields:a}),E=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[S,N]=A.useState(!1),k=(D,O,M)=>{const I=y=>y.id===D?{...y,conditions:y.conditions.map(T=>T.id===O?{...T,field:M,dataType:M.dataType}:T)}:{...y,groups:y.groups.map(I)};R(I(l))},w=(D,O=0,M)=>O===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:T}=I;if(T&&y.id!==T.id){const B=D.conditions.findIndex(V=>V.id===y.id),z=D.conditions.findIndex(V=>V.id===T.id);B!==-1&&z!==-1&&v(D.id,B,z)}},children:e.jsx(s.SortableContext,{items:D.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:D.conditions.map((I,y)=>e.jsx(wn,{condition:I,index:y,groupId:D.id,groupLogicalOperator:D.logicalOperator,onUpdateCondition:f,onUpdateField:k,onRemoveCondition:m,onUpdateGroupOperator:g,availableFields:c,updateConditionFields:p},I.id))})}),e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:T}=I;if(T&&y.id!==T.id){const B=D.groups.findIndex(V=>V.id===y.id),z=D.groups.findIndex(V=>V.id===T.id);B!==-1&&z!==-1&&j(D.id,B,z)}},children:e.jsx(s.SortableContext,{items:D.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:D.groups.map(I=>w(I,O+1,D.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),S&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},D.id):e.jsx(Oi,{group:D,depth:O,parentGroupId:M,onUpdateGroupOperator:g,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:f,onUpdateField:k,onRemoveCondition:m,onReorderConditions:v,onReorderGroups:j,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:w,updateConditionFields:p},D.id),L=Sn(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):w(l),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:S,onCheckedChange:D=>N(!!D)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),C&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:b(l)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),L>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(C?l:null),children:"Apply Filters"})]})]})}function Bi({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:l,onOpenChange:c}){const i=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:l,onOpenChange:c,children:[l&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Fi,{filters:a,availableFields:o,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function zi({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var p;const[o,l]=A.useState(null),c=s.useEditorStore(g=>g.card),i=(p=c==null?void 0:c.config)==null?void 0:p.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],u=A.useCallback(g=>g.startsWith("card-")?null:g.startsWith("source-")||a.find(x=>x.id===g)?"source":n("groupBy").find(x=>x.id===g)?"groupBy":n("metrics").find(x=>x.id===g)?"metrics":n("pivotBy").find(x=>x.id===g)?"pivotBy":n("sortBy").find(x=>x.id===g)?"sortBy":null,[a,n]),m=A.useCallback(g=>{l(g.active.id)},[]),h=A.useCallback(g=>{const{active:x,over:v}=g;if(!v||!t){l(null);return}const j=x.id,b=v.id,C=u(j),R=u(b)||b;if(C==="source"&&R==="sortBy"){l(null);return}if(C==="source"&&R!=="source"&&R!=="sortBy"){const E=[...a].find(w=>w.id===j);if(!E){l(null);return}const S=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(S.length>0){const w=S[0].qualifiedEntityName;if(!w){l(null);return}if(w!==E.qualifiedEntityName&&E.qualifiedEntityName)if(i){if(!Nn(w,E.qualifiedEntityName,i)){Es(),l(null);return}}else{Es(),l(null);return}}const N=n(R);if(Ts(E,N)){l(null);return}const k=s.getNewField(E,R);l(null),r(R,[...N,k]);return}if(C&&R&&C!=="source"&&R!=="source"&&C!==R){const E=n(C),S=n(R),N=E.find(L=>L.id===j);if(!N){l(null);return}const k=s.getNewField(N,R);if(l(null),R==="sortBy"){if(C==="pivotBy"){l(null);return}Ts(N,S)||r(R,[...S,k]);return}const w=E.filter(L=>L.id!==j);r(C,w),r(R,[...S,k]);return}if(C&&R&&C===R&&C!=="source"){const E=n(C),S=E.findIndex(k=>k.id===j),N=E.findIndex(k=>k.id===b);if(S!==N){const k=s.arrayMove(E,S,N);r(C,k)}}l(null)},[t,a,n,r,u,i]),f=o?d.find(g=>g.id===o):null;return{activeId:o,activeField:f,handleDragStart:m,handleDragEnd:h}}function Pi({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const r=s.useEditorStore(p=>p.isDevMode),o=s.useEditorStore(p=>p.card);s.isExplorerCard(o);const{config:l}=A.useContext(s.SemaphorContext).tokenProps,c=(l==null?void 0:l.showAdvancedMode)!==!1,{setIsDevMode:i}=s.useEditorActions(),d=s.useEditorStore(p=>p.showAIDialog),u=s.useEditorStore(p=>p.frame),m=s.useManagementStore(p=>p.selectedVisual),h=(m==null?void 0:m.id)===(u==null?void 0:u.id),{setShowAIDialog:f}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",d&&"justify-end",!c&&"justify-end"),children:[c&&t&&!d&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:r,onCheckedChange:()=>i(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx($s,{}),n&&!h&&e.jsx(Us,{variant:"default"}),h&&e.jsx(Qr,{}),a&&s.isDevEnv]})]})}function Vi({activeView:t,onViewChange:a}){const n=s.useEditorStore(o=>o.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:o=>a(o),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-2 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const _i=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Ui(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=A.useState(!1),[o,l]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),a(t.id,parseInt(m))},i=m=>{const h=m.target.value;l(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:o,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:_i.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function $i({isOpen:t,onClose:a}){const n=Yt(a,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),o=s.useEditorStore(m=>m.card),l=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(o),{getCard:d}=s.useCustomVisual(r),u=A.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:l,settings:c})})})]})})}function qi({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:l,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:f}){var O;const p=s.useEditorStore(M=>M.card),g=s.useDashboardStore(M=>M.filterValues),{updateCardConfig:x}=s.useEditorActions(),v=s.useEditorStore(M=>M.showAIDialog),[j,b]=A.useState(!1),C=s.useEditorStore(M=>{var I;return((I=M.card.customCardPreferences)==null?void 0:I.url)&&M.card.type==="custom"}),{data:R,errorMessage:E,isPending:S,isLoading:N,isFetching:k}=s.useDashboardCardQuery(u);function w(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(p.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(g||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",m.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":f?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const L=M=>{if(!p.config)return;if(!M.length){x(p.id,{...p.config,sortByColumns:[]});return}const I=p.config,y=M.map(({id:T,desc:B})=>{var X,K;const z=(X=I.metricColumns)==null?void 0:X.find(_=>_.label===T),V=(K=I.groupByColumns)==null?void 0:K.find(_=>_.label===T),P=z||V;return P?{id:s.getFieldId("sortBy",P),name:P.name,dataType:P.dataType,label:P.label,qualifiedEntityName:P.qualifiedEntityName,entityId:P.entityId,entityName:P.entityName,entityType:P.entityType,role:"sortby",direction:B?"desc":"asc"}:null}).filter(T=>T!==null);x(p.id,{...I,sortByColumns:y})},D=A.useMemo(()=>{var M,I;return(I=(M=p.config)==null?void 0:M.sortByColumns)==null?void 0:I.map(y=>({id:y.label,desc:y.direction==="desc"}))},[(O=p.config)==null?void 0:O.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(Pi,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:l,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&w(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&v&&e.jsx(mn,{variant:"outline"}),e.jsx(Vi,{activeView:t,onViewChange:a}),i&&e.jsxs(s.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:i,children:[e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),d>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:d})]}),e.jsx("div",{className:"ml-2",children:e.jsx(Ui,{})}),v&&e.jsx(us,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(hn,{})})]}),!j&&C&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>b(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(Ca,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:N||k?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(xn,{})}),t==="table"&&(R==null?void 0:R.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(N||k)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(s.TableVisual,{card:u,data:R==null?void 0:R.records,onSortChange:L,sortState:D})]}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[(R==null?void 0:R.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(an,{sql:R==null?void 0:R.sql,error:E})]})})]}),e.jsx($i,{isOpen:j,onClose:()=>b(!1)})]})]})}function Yi({activeField:t}){const[a,n]=A.useState(!0);return A.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Cn,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const Gi=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var o;if((o=r.reason)!=null&&o.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Hi(){var _,$;const[t,a]=A.useState("chart"),[n,r]=A.useState(!1),[o,l]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(q=>q.showAIDialog),u=s.useDashboardStore(q=>q.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(q=>q.card.type);A.useEffect(()=>Gi(),[]);const f=()=>{console.log("Accept clicked - would save/apply current configuration")},p=()=>{console.log("Clear clicked - would reset all configurations")},g=()=>{console.log("Advanced mode toggled")},x=()=>{l(!0)},v=q=>{m(q)},j=s.useEditorStore(q=>q.frame),b=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.activeTabCardId),s.useEditorStore(q=>q.actions.getAvailableFields);const{addCard:C,removeCard:R,updateCard:E,setActiveCard:S,updateFilters:N}=s.useEditorActions(),{columns:k=[],isLoading:w,error:L}=s.useColumns(),D=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=b,{getFieldsForContainer:M,setFieldsForContainer:I}=Xs(O),{activeField:y,handleDragStart:T,handleDragEnd:B}=zi({activeCardId:j.activeCardId,sourceFields:k,getFieldsForContainer:M,setFieldsForContainer:I}),z=(q,U)=>{U&&N(q,U)},V=q=>{var U;E(q,{config:{...(U=j.cards.find(G=>G.id===q))==null?void 0:U.config,filters:void 0}})},P=k,X=q=>{if(!q)return 0;let U=q.conditions.length;return q.groups.forEach(G=>{U+=X(G)}),U},K=X(((_=O==null?void 0:O.config)==null?void 0:_.filters)||null);return e.jsxs(s.DndContext,{sensors:D,collisionDetection:s.closestCenter,onDragStart:T,onDragEnd:B,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(ui,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(bi,{selectedChart:h,onChartChange:v,groupByFields:M("groupBy"),pivotByFields:M("pivotBy"),metricsFields:M("metrics"),sortByFields:M("sortBy")}),e.jsx(qi,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:f,onClear:p,onAdvancedToggle:g,onFiltersClick:x,filterCount:K,activeCard:O,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:k,columnsLoading:w,columnsError:L,getFieldsForContainer:M,cards:j.cards,activeCardId:j.activeCardId,addCard:C,setActiveCard:S})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),O&&e.jsx(Bi,{cardId:O.id,filters:(($=O.config)==null?void 0:$.filters)||null,onFiltersChange:z,onClearFilters:V,availableFields:P,isOpen:o,onOpenChange:l}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Yi,{activeField:y||null})})]})}function Qi({authToken:t,onSave:a,onClose:n}){const r=A.useRef(null),o=s.useEditorStore(b=>b.showAIDialog),l=s.useEditorStore(b=>b.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:f,handleDragCancel:p,sensors:g}=Or();A.useEffect(()=>{a&&d(a),n&&u(n)},[a,d,n,u]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var b,C;o?((b=r.current)==null||b.resize(40),i(!0)):(i(!1),(C=r.current)==null||C.resize(0))},[o,i]);function x(b){b<1?i(!1):o||i(!0)}function v(){return e.jsxs(e.Fragment,{children:[e.jsx(tn,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Jo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(jt,{})})]})]})}function j(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Hi,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(jt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:l?e.jsx(s.DndContext,{sensors:g,onDragStart:f,onDragEnd:h,onDragOver:m,onDragCancel:p,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:v()})}):j()})}function Ki(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function o(c){t&&(r(t,c),a(!1))}function l(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Qi,{onSave:o,onClose:l})})}function Wi(){const t=s.useEditorStore(l=>l.selectedDatabaseName),a=s.useEditorStore(l=>l.selectedTableName),n=s.useDashboardStore(l=>l.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:o}=jn();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(l=>{const c=n==null?void 0:n.find(i=>i.column===s.fmt(l.column_name)&&i.table===a&&i.database===t);return e.jsx("div",{onClick:()=>o(l),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vs,{column:l}),e.jsx("span",{children:l.column_name})]})},l.column_name)})})}function Ji(){s.useDashboardStore(a=>a.showFilters);const t=s.useDashboardStore(a=>a.actions.setShowFilters);return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:e.jsx(tn,{type:"filter",ColumnsComponent:()=>e.jsx(Wi,{})})})]})}function Xi(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Zi(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(Xi,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Ji,{})})]})}function el(){const t=s.useDashboardStore(o=>o.dashboard),a=s.useDashboardStore(o=>o.actions.setDashboard),n=s.useDashboardStore(o=>o.showDashboardJSON),r=s.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:o=>{if(o)try{JSON.parse(o),a(JSON.parse(o))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function sl({showControls:t=!1,showFooter:a=!0,...n}){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsxs(s.UXProvider,{children:[e.jsx(el,{}),e.jsxs("main",{className:"flex h-full flex-col",children:[t&&e.jsx(Ir,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(Ki,{}),e.jsx(Zi,{})]})]})]})]})})}exports.DashboardPlus=sl;exports.ResourceManagementPanel=en;exports.ScheduleDashboard=Bt;exports.SelectComponent=ze;exports.cleanCard=Rt;exports.downloadPdf=Ft;exports.getDashbaordStateWithoutData=Bs;
425
+ ON ${b}`}),g};return l.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>o(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(ii,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:l,generateSQLPreview:u})})]})}),e.jsx(yt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(yt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>o(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function ci({entity:t,title:a,maxDetails:n=10}){const o=s.getEntityDetails(t).slice(0,n),l=o.find(i=>i.label==="Description"),c=o.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a||s.getDisplayName(t)}),l&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function di({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((a,n)=>{const r=s.getEntityDetails(a),o=r.find(c=>c.label==="Description"),l=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(a)}),o&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),l.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:l.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function ui({isVisible:t,onToggleVisibility:a}){s.useEditorStore(m=>m.isDevMode),s.useEditorStore(m=>m.card.connectionId),s.useDashboardStore(m=>m.isVisualEditing);const[n,r]=A.useState(!1),[o,l]=A.useState(!0),c=s.useEditorStore(m=>m.card.dataSource),{updateDataSource:i}=s.useEditorActions(),d={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},u={...d,...c,selectedEntities:(c==null?void 0:c.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!o}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>l(!o),className:"h-6 w-6 p-0",children:o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${o?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[u.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[u.selectedEntities.slice(0,3).map((m,h)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(m),e.jsx("button",{onClick:f=>{f.stopPropagation();const p=u.selectedEntities.filter(g=>!(g.name===m.name&&g.type===m.type));i({...d,...c,selectedEntities:p})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(ci,{entity:m})]},`${m.type}-${m.name}-${h}`)),u.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",u.selectedEntities.length-3," more"]})}),e.jsx(di,{entities:u.selectedEntities.slice(3)})]})]})}),e.jsx(li,{})]})]}),e.jsx(ai,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(c==null?void 0:c.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:u,fallbackDataSource:d})]})}const Ze=[{id:"table",icon:cs,label:"Table"},{id:"bar",icon:os,label:"Bar Chart"},{id:"line",icon:is,label:"Line Chart"},{id:"area",icon:Dt,label:"Area Chart"},{id:"stackedBar",icon:Is,label:"Stacked Bar Chart"},{id:"combo",icon:Kn,label:"Combo Chart"},{id:"stackedLine",icon:Qs,label:"Stacked Line Chart"},{id:"scatter",icon:As,label:"Scatter Chart"},{id:"bubble",icon:Gs,label:"Bubble Chart"},{id:"pie",icon:ls,label:"Pie Chart"},{id:"doughnut",icon:Ls,label:"Doughnut Chart"},{id:"funnel",icon:Hs,label:"Funnel Chart"},{id:"radar",icon:Os,label:"Radar Chart"},{id:"polarArea",icon:Ys,label:"Polar Area Chart"},{id:"tornado",icon:Fs,label:"Tornado Chart"},{id:"range",icon:Ms,label:"Range Chart"},{id:"kpi",icon:Ks,label:"KPI"},{id:"text",icon:St,label:"Text"},{id:"map",icon:Rs,label:"Map"}],Zs=t=>{const a=t.toLowerCase();for(const n of Ze)if(n.id==="doughnut"){if(a.includes("doughnut")||a.includes("donut")){const r=n.icon;return A.createElement(r,{className:"h-4 w-4"})}}else if(a.includes(n.id.toLowerCase())){const r=n.icon;return A.createElement(r,{className:"h-4 w-4"})}return null},mi="chart-selector-standard-first";function hi(){const[t,a]=s.useLocalStorageState(mi,!0);return{standardFirst:t,updatePreference:a}}const vt=({pluginVisual:t,index:a,onSelect:n})=>{const r=ms(t.icon||""),o=t.name.charAt(0).toUpperCase(),l=Zs(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):l||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:o}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},bt=["default","standardPlugin","customPlugin"];function xi({selectedChart:t,onChartChange:a}){var S;const[n,r]=A.useState([]),[o,l]=A.useState(!1),{data:c}=qs();hi();const d=((S=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:S.url)||"";zs(d);const{setCardType:u,setCardPreferences:m,setIsDevMode:h}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:f,setCustomCardPreferences:p,setQueryConfig:g}=s.useEditorActions(),[x,v]=s.useLocalStorageState("chart-section-active",null),j=A.useMemo(()=>x?[x,...bt.filter(N=>N!==x)]:bt,[x]);A.useEffect(()=>{(async()=>{if(c){const w=(await Promise.allSettled(c.plugins.map(async L=>{try{return(await s.loadManifest(L.value)).visuals.map(O=>({name:O.name,icon:O.icon,url:L.value,pluginName:L.label,pluginType:L.type,chartType:O.chartType,componentType:O.componentType}))}catch(D){return console.error(`Failed to load manifest for plugin ${L.label}`,D),[]}}))).filter(L=>L.status==="fulfilled").flatMap(L=>L.value);r(w)}})()},[c]);function b(N){f(null),m({}),u(N),["custom","text","map"].includes(N)&&(h(!0),g(void 0)),a(N),l(!1)}function C(N){f(null),m({}),u("custom"),p({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),g(void 0),a("custom"),l(!1)}const R=()=>{var k;if(t==="custom"){const w=s.useEditorStore.getState().card;return((k=w==null?void 0:w.customCardPreferences)==null?void 0:k.componentName)||"Custom Visual"}const N=Ze.find(w=>w.id===t);return(N==null?void 0:N.label)||"Select chart type"},E=()=>{var k,w;if(t==="custom"){const L=s.useEditorStore.getState().card,D=(k=L==null?void 0:L.customCardPreferences)==null?void 0:k.icon,O=(w=L==null?void 0:L.customCardPreferences)==null?void 0:w.componentName;if(D&&O)return e.jsx(pi,{icon:D,componentName:O});if(O){const M=Zs(O);if(M)return M}return e.jsx(qe,{className:"h-4 w-4"})}const N=Ze.find(L=>L.id===t);if(N){const L=N.icon;return e.jsx(L,{className:"h-4 w-4"})}return e.jsx(qe,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:o,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[E(),e.jsx("span",{children:R()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[335px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),j.map(N=>{if(N==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="default",onCheckedChange:k=>v(k?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:Ze.map(k=>{const w=k.icon;return e.jsx(s.CommandItem,{value:`${k.label} ${k.id} chart graph visualization`,onSelect:()=>b(k.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{className:"h-4 w-4"}),e.jsx("span",{children:k.label})]})},k.id)})},"default");if(N==="standardPlugin"){const k=n.filter(w=>w.pluginType==="standard");return k.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="standardPlugin",onCheckedChange:w=>v(w?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.filter(w=>w.componentType==="chart").map((w,L)=>e.jsx(vt,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"standardPlugin"):null}if(N==="customPlugin"){const k=n.filter(w=>w.pluginType==="custom");return k.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:x==="customPlugin",onCheckedChange:w=>v(w?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.map((w,L)=>e.jsx(vt,{pluginVisual:w,index:L,onSelect:()=>C(w)},`${w.url}-${w.name}-${L}`))},"customPlugin"):null}return null})]})]})})]})})}const pi=({icon:t,componentName:a})=>{const n=ms(),r=Zs(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(qe,{className:"h-4 w-4"})},Cn=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(Ge,{className:"h-3 w-3"})}):a==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx($e,{className:"h-3 w-3"})}):a==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(es,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ge,{className:"h-3 w-3"})})};function fi({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=A.useState(t),[o,l]=A.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:o?n:t,onChange:u=>{r(u.target.value),l(!0)},onFocus:()=>l(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&o&&n!==t?(a(n),l(!1)):u.key==="Escape"&&(r(t),l(!1))},"aria-label":"Edit alias template"}),o&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),l(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),l(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function gi({valueAliases:t,onValueAliasesChange:a}){const[n,r]=A.useState(null),[o,l]=A.useState(""),[c,i]=A.useState(""),d=()=>{a({...t,"":""})},u=h=>{const f={...t};delete f[h],a(f)},m=h=>{const f={...t};delete f[h],f[o]=c,a(f),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,f],p)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:o,onChange:g=>l(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?m(h):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?m(h):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),l(h),i(f)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),l(h),i(f)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+p)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Nt({value:t,onSave:a,placeholder:n="",type:r="text",className:o=""}){const[l,c]=A.useState(t??""),[i,d]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const u=()=>{a(l),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${o}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:i?l:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&l!==t?u():h.key==="Escape"&&m()},"aria-label":n||"Edit field"}),i&&l!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function ji({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:l=!1,cardType:c}){var tt;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:f}=s.useSortable({id:t.id}),p=s.useEditorStore(W=>W.card),{updateLabel:g,handleAggregationChange:x,handleDateFormatChange:v,handleGranularityChange:j,handleAliasTemplateChange:b,handleValueAliasesChange:C,removeField:R,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:N,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:w}=Xs(p),[L,D]=A.useState(!1),[O,M]=A.useState(t.dateFormat||"YYYY-MM-DD"),[I,y]=A.useState(t.customFormat||""),[T,B]=A.useState(!!t.customFormat),[z,V]=A.useState(t.granularity||"day"),[P,X]=A.useState(t.aliasTemplate||""),[K,_]=A.useState(t.valueAliases||{}),$=W=>{W==="custom"?B(!0):(B(!1),M(W),a==="groupBy"&&v(n,W,""))},q=W=>{y(W),a==="groupBy"&&v(n,"custom",W)},U=W=>{var _e;V(W);const xe=(_e=H(W)[0])==null?void 0:_e.value;xe&&!T&&(M(xe),a==="groupBy"&&v(n,xe,"")),a==="groupBy"&&j(n,W)},G=W=>{X(W),a==="metrics"&&b(n,W)},Q=W=>{_(W),a==="metrics"&&C(n,W)},Y=W=>{g(a,n,W)},Z=()=>{R(a,n)},te={transform:s.CSS.Transform.toString(m),transition:h},ae=s.getDataType(t.dataType),se=ae==="date",oe=c==="kpi",H=W=>{switch(W){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},F=H(z),J=!oe&&a!=="pivotBy",ie=se&&a==="groupBy",be=!oe&&se&&a==="groupBy",ke=oe&&se&&a==="groupBy",ne=oe&&a==="metrics"&&((tt=p.config)==null?void 0:tt.comparisonType)==="target",le=a==="metrics",ce=()=>e.jsx("div",{onPointerDown:W=>{W.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),Dn=()=>J?e.jsx(Nt,{value:t.label??"",onSave:Y,placeholder:"Display label...",type:"text"}):null,st=()=>ie?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:z,onValueChange:U,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(W=>e.jsx(s.SelectItem,{className:"text-xs",value:W,children:s.toTitleCase(W)},W))})]})]}):null,kn=()=>be?e.jsxs(e.Fragment,{children:[st(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:T?"custom":O,onValueChange:$,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:F.map(W=>e.jsx(s.SelectItem,{className:"text-xs",value:W.value,children:W.label},W.value))})]}),T&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:I,onChange:W=>{W.stopPropagation(),q(W.target.value)},onClick:W=>W.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,En=()=>{var W,ge,xe,_e,nt;return ke?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((W=p.config)==null?void 0:W.comparisonType)||"none",onValueChange:E,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ge=p.config)==null?void 0:ge.showTrendline)||!1,onCheckedChange:S})]})}),((xe=p.config)==null?void 0:xe.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((_e=p.config)==null?void 0:_e.trendlineWindow)||30,onChange:Mn=>{const An=parseInt(Mn.target.value)||30;N(An)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((nt=p.config)==null?void 0:nt.trendlineGranularity)||"day",onValueChange:k,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},Tn=()=>{var W,ge;return ne?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(Nt,{value:((W=p.config)==null?void 0:W.targetValue)!==void 0&&((ge=p.config)==null?void 0:ge.targetValue)!==null?String(p.config.targetValue):"",onSave:xe=>{!isNaN(Number(xe))&&xe!==null?w(Number(xe)):w(0)},placeholder:"Enter target value...",type:"text"})]}):null},In=()=>le?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:W=>{x(n,W)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(vn,{column:t}),l&&e.jsxs(e.Fragment,{children:[e.jsx(fi,{aliasTemplate:P,onAliasTemplateChange:G}),e.jsx(gi,{valueAliases:K,onValueAliasesChange:Q})]})]}):null;return e.jsxs("div",{ref:u,style:te,...i,...d,className:`group mx-auto flex w-full max-w-[300px] flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.GripVertical,{className:"h-3 w-3"}),e.jsx(Cn,{dataType:ae}),e.jsx(Ws,{className:"max-w-[180px] flex-1 text-sm",children:t.label||t.name}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:W=>{W.stopPropagation(),D(!L)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${L?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:W=>{W.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ge=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ge),o(ge)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:W=>{W.stopPropagation(),Z()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),L&&e.jsxs("div",{className:"space-y-3",children:[ce(),Dn(),c==="kpi"&&st(),kn(),En(),Tn(),In()]})]})}function yi({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Je({zone:t,fields:a,label:n,placeholder:r,shouldShow:o,hasPivotColumns:l=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(g=>g.card),m=s.useEditorStore(g=>g.card.type),h=a.length>0,f=(g,x)=>{var j;!((j=u.config)!=null&&j.sortByColumns)||u.config.sortByColumns.findIndex(b=>b.id===g)===-1||d(u.id,g,{direction:x})};if(t==="sortBy"&&o===!1)return null;const p=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),p&&e.jsx(yi,{concept:t})]}),e.jsx("div",{ref:i,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"border-muted-foreground/20 bg-background"}`,children:a.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:a.map(g=>g.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((g,x)=>{const j=g.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(ji,{field:g,zone:t,index:x,sortDirection:j,onSortDirectionChange:b=>f(g.id,b),hasPivotColumns:l,cardType:m})})},g.id)})})})})]})}function vi({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const o=s.useEditorStore(h=>h.card),l=o==null?void 0:o.type,c=t.length>0||n.length>0,i=l!=="kpi",d=l!=="kpi"&&c,u=()=>l==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},m=()=>l==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Je,{zone:"groupBy",fields:t,label:u().label,placeholder:u().placeholder}),i&&e.jsx(Je,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Je,{zone:"metrics",fields:n,label:m().label,placeholder:m().placeholder,hasPivotColumns:a.length>0}),d&&e.jsx(Je,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function bi({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:l}){const c=s.useEditorStore(h=>h.showAIDialog),i=n.length>0||r.length>0||o.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-96 flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(xi,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||m}),children:e.jsx(us,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(Da,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(vi,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:l}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Ni({initialFilters:t,availableFields:a}={}){const[n,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(E=>E.card.dataSource);const{columns:o,isLoading:l}=s.useColumns(),i=a||o||[],d={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=E=>{const S=N=>{if(N.id===E){const k=i[0]||d;return{...N,conditions:[...N.conditions,{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},m=E=>{const S=N=>{if(N.id===E){const k=i[0]||d;return{...N,groups:[...N.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:k,operator:"=",value:""}],groups:[]}]}}return{...N,groups:N.groups.map(S)}};r(S(n))},h=(E,S)=>{const N=k=>k.id===E?{...k,conditions:k.conditions.filter(w=>w.id!==S)}:{...k,groups:k.groups.map(N)};r(N(n))},f=(E,S)=>{const N=k=>k.id===E?{...k,groups:k.groups.filter(w=>w.id!==S)}:{...k,groups:k.groups.map(N)};r(N(n))},p=(E,S,N,k)=>{if(N==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const w=L=>L.id===E?{...L,conditions:L.conditions.map(D=>D.id===S?{...D,[N]:k}:D)}:{...L,groups:L.groups.map(w)};r(w(n))},g=(E,S,N)=>{const k=w=>w.id===E?{...w,conditions:w.conditions.map(L=>L.id===S?{...L,...N}:L)}:{...w,groups:w.groups.map(k)};r(k(n))},x=(E,S)=>{const N=k=>k.id===E?{...k,logicalOperator:S}:{...k,groups:k.groups.map(N)};r(N(n))},v=(E,S)=>{const N=k=>k.id===E?{...k,negate:S}:{...k,groups:k.groups.map(N)};r(N(n))},j=(E,S,N)=>{const k=w=>w.id===E?{...w,conditions:s.arrayMove(w.conditions,S,N)}:{...w,groups:w.groups.map(k)};r(k(n))},b=(E,S,N)=>{const k=w=>w.id===E?{...w,groups:s.arrayMove(w.groups,S,N)}:{...w,groups:w.groups.map(k)};r(k(n))},C=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const S=k=>{let w="";typeof k.field=="object"?w=k.field.entityName?`${k.field.entityName}.${k.field.name}`:k.field.name:w=String(k.field);const L=k.operator;let D=k.value;if(k.field.dataType==="string"&&!["in","not in"].includes(k.operator))typeof D=="string"?D=`'${D}'`:Array.isArray(D)&&(D=`'${D.join(", ")}'`);else if(k.field.dataType==="date")(typeof D=="string"||D instanceof Date)&&(D=`DATE('${D}')`);else if(["in","not in"].includes(k.operator)){let O=[];Array.isArray(D)?O=D.map(M=>typeof M=="string"?`'${M}'`:String(M)):typeof D=="string"?O=D.split(",").map(M=>{const I=M.trim();return k.field.dataType==="string"?`'${I}'`:I}):typeof D=="number"&&(O=[String(D)]),D=`(${O.join(", ")})`}switch(L){case"contains":return typeof D=="string"?`${w} LIKE '%${D.replace(/'/g,"")}'`:`${w} LIKE '%${String(D)}'`;case"startsWith":return typeof D=="string"?`${w} LIKE '${D.replace(/'/g,"")}%'`:`${w} LIKE '${String(D)}%'`;case"endsWith":return typeof D=="string"?`${w} LIKE '%${D.replace(/'/g,"")}'`:`${w} LIKE '%${String(D)}'`;default:return`${w} ${L} ${D}`}},N=k=>{const w=k.conditions.map(S),L=k.groups.map(I=>N(I)),D=[...w,...L].filter(Boolean);if(D.length===0)return"";const O=D.join(` ${k.logicalOperator} `),M=D.length>1?`(${O})`:O;return k.negate?`NOT ${M}`:M};return N(E)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:l,addCondition:u,addGroup:m,removeCondition:h,removeGroup:f,updateCondition:p,updateConditionFields:g,updateGroupOperator:x,updateGroupNegate:v,reorderConditions:j,reorderGroups:b,generateSQLPreview:C,hasAnyFilters:R}}function Ci({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Si=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(aa,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},wi=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Di({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[l,c]=A.useState(!1),i=A.useMemo(()=>{const d={};return n.forEach(u=>{const m=wi(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:l,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:s.cn("justify-between",!t&&"text-muted-foreground",o),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ci,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Si(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((f,p)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{a(f),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===f.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+p))]},`${d}-${m}`))},d))})]})})]})}function et(t){var g;const a=s.useEditorStore(x=>x.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(x=>x.card.config),o=r==null?void 0:r.joinPlan,l={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...l,role:"sortby",direction:"asc"},d={joinPlan:o,groupByColumns:[l],metricColumns:[c],sortByColumns:[i]},u=((g=a.dataSource)==null?void 0:g.connectionId)||a.connectionId,{data:m,isPending:h,error:f}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:u,cardConfig:d,cardDataSource:a.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!u,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(x=>({label:x[t.name]||"BLANK",value:x[t.name]||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:h,error:f}}function ki({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[l,c]=ue.useState(!1),{filterValues:i}=et(t),d=m=>{n(a.filter(h=>h!==m))},u=m=>{a.includes(m)?n(a.filter(h=>h!==m)):n([...a,m])};return e.jsx("div",{className:s.cn("w-full",o),children:e.jsxs(s.Popover,{open:l,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(m=>{const h=i.find(f=>f.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:f=>{f.key==="Enter"&&d(m)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}const Sn=t=>{if(!t)return 0;let a=t.conditions.length;return t.groups.forEach(n=>{a+=Sn(n)}),a};function Ei({field:t,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:l,isPending:c,error:i}=et(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:o||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:l.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}const Ti=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Ii=["=","!=","contains","startsWith","endsWith","in","not in"],Mi=["=","!=",">",">=","<","<=","in","not in"],Ai=["=","!="],Li=["=","!=",">",">=","<","<=","in","not in"];function Ri(t){switch(t){case"string":return Ii;case"number":return Mi;case"boolean":return Ai;case"date":return Li;default:return Ti}}function wn({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:l,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:f,transition:p,isDragging:g}=s.useSortable({id:t.id}),{isPending:x,error:v}=et(t.field),j={transform:s.CSS.Transform.toString(f),transition:p};return e.jsxs("div",{ref:h,style:j,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:b=>c(n,b),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Di,{value:t.field,onValueChange:b=>{d(n,t.id,{field:b,value:""})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:b=>{b==="in"||b==="not in"?d(n,t.id,{operator:b,value:[]}):d(n,t.id,{operator:b,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-28",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ri(s.getDataType(t.field.dataType)).map(b=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:b,children:b},b))})]}),s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?x?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ki,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(b=>typeof b=="string")?t.value:[],onChange:b=>d(n,t.id,{value:b}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Ei,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:b=>d(n,t.id,{value:b}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:b=>d(n,t.id,{value:b==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:b=>o(n,t.id,"value",b.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>l(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Oi({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:l,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:f,availableFields:p,renderFilterGroup:g,updateConditionFields:x}){const{attributes:v,listeners:j,setNodeRef:b,transform:C,transition:R,isDragging:E}=s.useSortable({id:t.id}),S={transform:s.CSS.Transform.toString(C),transition:R},N=w=>{const{active:L,over:D}=w;if(D&&L.id!==D.id){const O=t.conditions.findIndex(I=>I.id===L.id),M=t.conditions.findIndex(I=>I.id===D.id);O!==-1&&M!==-1&&u(t.id,O,M)}},k=w=>{const{active:L,over:D}=w;if(D&&L.id!==D.id&&n){const O=t.groups.findIndex(I=>I.id===L.id),M=t.groups.findIndex(I=>I.id===D.id);O!==-1&&M!==-1&&m(n,O,M)}};return e.jsxs("div",{ref:b,style:S,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...j,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:w=>r(t.id,w),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&l(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:N,children:e.jsx(s.SortableContext,{items:t.conditions.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((w,L)=>e.jsx(wn,{condition:w,index:L,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:x},w.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:k,children:e.jsx(s.SortableContext,{items:t.groups.map(w=>w.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(w=>g(w,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Fi({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:l,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:f,updateConditionFields:p,updateGroupOperator:g,updateGroupNegate:x,reorderConditions:v,reorderGroups:j,generateSQLPreview:b,hasAnyFilters:C,setCurrentFilters:R}=Ni({initialFilters:t,availableFields:a}),E=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[S,N]=A.useState(!1),k=(D,O,M)=>{const I=y=>y.id===D?{...y,conditions:y.conditions.map(T=>T.id===O?{...T,field:M,dataType:M.dataType}:T)}:{...y,groups:y.groups.map(I)};R(I(l))},w=(D,O=0,M)=>O===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:T}=I;if(T&&y.id!==T.id){const B=D.conditions.findIndex(V=>V.id===y.id),z=D.conditions.findIndex(V=>V.id===T.id);B!==-1&&z!==-1&&v(D.id,B,z)}},children:e.jsx(s.SortableContext,{items:D.conditions.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:D.conditions.map((I,y)=>e.jsx(wn,{condition:I,index:y,groupId:D.id,groupLogicalOperator:D.logicalOperator,onUpdateCondition:f,onUpdateField:k,onRemoveCondition:m,onUpdateGroupOperator:g,availableFields:c,updateConditionFields:p},I.id))})}),e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:I=>{const{active:y,over:T}=I;if(T&&y.id!==T.id){const B=D.groups.findIndex(V=>V.id===y.id),z=D.groups.findIndex(V=>V.id===T.id);B!==-1&&z!==-1&&j(D.id,B,z)}},children:e.jsx(s.SortableContext,{items:D.groups.map(I=>I.id),strategy:s.verticalListSortingStrategy,children:D.groups.map(I=>w(I,O+1,D.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),S&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(D.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},D.id):e.jsx(Oi,{group:D,depth:O,parentGroupId:M,onUpdateGroupOperator:g,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:f,onUpdateField:k,onRemoveCondition:m,onReorderConditions:v,onReorderGroups:j,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:w,updateConditionFields:p},D.id),L=Sn(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):w(l),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:S,onCheckedChange:D=>N(!!D)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),C&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:b(l)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),L>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(C?l:null),children:"Apply Filters"})]})]})}function Bi({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:l,onOpenChange:c}){const i=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:l,onOpenChange:c,children:[l&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Fi,{filters:a,availableFields:o,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function zi({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var p;const[o,l]=A.useState(null),c=s.useEditorStore(g=>g.card),i=(p=c==null?void 0:c.config)==null?void 0:p.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],u=A.useCallback(g=>g.startsWith("card-")?null:g.startsWith("source-")||a.find(x=>x.id===g)?"source":n("groupBy").find(x=>x.id===g)?"groupBy":n("metrics").find(x=>x.id===g)?"metrics":n("pivotBy").find(x=>x.id===g)?"pivotBy":n("sortBy").find(x=>x.id===g)?"sortBy":null,[a,n]),m=A.useCallback(g=>{l(g.active.id)},[]),h=A.useCallback(g=>{const{active:x,over:v}=g;if(!v||!t){l(null);return}const j=x.id,b=v.id,C=u(j),R=u(b)||b;if(C==="source"&&R==="sortBy"){l(null);return}if(C==="source"&&R!=="source"&&R!=="sortBy"){const E=[...a].find(w=>w.id===j);if(!E){l(null);return}const S=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(S.length>0){const w=S[0].qualifiedEntityName;if(!w){l(null);return}if(w!==E.qualifiedEntityName&&E.qualifiedEntityName)if(i){if(!Nn(w,E.qualifiedEntityName,i)){Es(),l(null);return}}else{Es(),l(null);return}}const N=n(R);if(Ts(E,N)){l(null);return}const k=s.getNewField(E,R);l(null),r(R,[...N,k]);return}if(C&&R&&C!=="source"&&R!=="source"&&C!==R){const E=n(C),S=n(R),N=E.find(L=>L.id===j);if(!N){l(null);return}const k=s.getNewField(N,R);if(l(null),R==="sortBy"){if(C==="pivotBy"){l(null);return}Ts(N,S)||r(R,[...S,k]);return}const w=E.filter(L=>L.id!==j);r(C,w),r(R,[...S,k]);return}if(C&&R&&C===R&&C!=="source"){const E=n(C),S=E.findIndex(k=>k.id===j),N=E.findIndex(k=>k.id===b);if(S!==N){const k=s.arrayMove(E,S,N);r(C,k)}}l(null)},[t,a,n,r,u,i]),f=o?d.find(g=>g.id===o):null;return{activeId:o,activeField:f,handleDragStart:m,handleDragEnd:h}}function Pi({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const r=s.useEditorStore(p=>p.isDevMode),o=s.useEditorStore(p=>p.card);s.isExplorerCard(o);const{config:l}=A.useContext(s.SemaphorContext).tokenProps,c=(l==null?void 0:l.showAdvancedMode)!==!1,{setIsDevMode:i}=s.useEditorActions(),d=s.useEditorStore(p=>p.showAIDialog),u=s.useEditorStore(p=>p.frame),m=s.useManagementStore(p=>p.selectedVisual),h=(m==null?void 0:m.id)===(u==null?void 0:u.id),{setShowAIDialog:f}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",d&&"justify-end",!c&&"justify-end"),children:[c&&t&&!d&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:r,onCheckedChange:()=>i(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx($s,{}),n&&!h&&e.jsx(Us,{variant:"default"}),h&&e.jsx(Qr,{}),a&&s.isDevEnv]})]})}function Vi({activeView:t,onViewChange:a}){const n=s.useEditorStore(o=>o.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:o=>a(o),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-2 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const _i=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Ui(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=A.useState(!1),[o,l]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),a(t.id,parseInt(m))},i=m=>{const h=m.target.value;l(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:o,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:_i.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function $i({isOpen:t,onClose:a}){const n=Yt(a,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),o=s.useEditorStore(m=>m.card),l=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(o),{getCard:d}=s.useCustomVisual(r),u=A.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:l,settings:c})})})]})})}function qi({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:l,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:f}){var O;const p=s.useEditorStore(M=>M.card),g=s.useDashboardStore(M=>M.filterValues),{updateCardConfig:x}=s.useEditorActions(),v=s.useEditorStore(M=>M.showAIDialog),[j,b]=A.useState(!1),C=s.useEditorStore(M=>{var I;return((I=M.card.customCardPreferences)==null?void 0:I.url)&&M.card.type==="custom"}),{data:R,errorMessage:E,isPending:S,isLoading:N,isFetching:k}=s.useDashboardCardQuery(u);function w(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(p.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(g||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",m.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":f?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const L=M=>{if(!p.config)return;if(!M.length){x(p.id,{...p.config,sortByColumns:[]});return}const I=p.config,y=M.map(({id:T,desc:B})=>{var X,K;const z=(X=I.metricColumns)==null?void 0:X.find(_=>_.label===T),V=(K=I.groupByColumns)==null?void 0:K.find(_=>_.label===T),P=z||V;return P?{id:s.getFieldId("sortBy",P),name:P.name,dataType:P.dataType,label:P.label,qualifiedEntityName:P.qualifiedEntityName,entityId:P.entityId,entityName:P.entityName,entityType:P.entityType,role:"sortby",direction:B?"desc":"asc"}:null}).filter(T=>T!==null);x(p.id,{...I,sortByColumns:y})},D=A.useMemo(()=>{var M,I;return(I=(M=p.config)==null?void 0:M.sortByColumns)==null?void 0:I.map(y=>({id:y.label,desc:y.direction==="desc"}))},[(O=p.config)==null?void 0:O.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(Pi,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:l,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&w(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&v&&e.jsx(mn,{variant:"outline"}),e.jsx(Vi,{activeView:t,onViewChange:a}),i&&e.jsxs(s.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:i,children:[e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),d>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:d})]}),e.jsx("div",{className:"ml-2",children:e.jsx(Ui,{})}),v&&e.jsx(us,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(hn,{})})]}),!j&&C&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>b(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(Ca,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:N||k?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(xn,{})}),t==="table"&&(R==null?void 0:R.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(N||k)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(s.TableVisual,{card:u,data:R==null?void 0:R.records,onSortChange:L,sortState:D})]}),t==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[(R==null?void 0:R.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(an,{sql:R==null?void 0:R.sql,error:E})]})})]}),e.jsx($i,{isOpen:j,onClose:()=>b(!1)})]})]})}function Yi({activeField:t}){const[a,n]=A.useState(!0);return A.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Cn,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const Gi=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var o;if((o=r.reason)!=null&&o.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Hi(){var _,$;const[t,a]=A.useState("chart"),[n,r]=A.useState(!1),[o,l]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(q=>q.showAIDialog),u=s.useDashboardStore(q=>q.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(q=>q.card.type);A.useEffect(()=>Gi(),[]);const f=()=>{console.log("Accept clicked - would save/apply current configuration")},p=()=>{console.log("Clear clicked - would reset all configurations")},g=()=>{console.log("Advanced mode toggled")},x=()=>{l(!0)},v=q=>{m(q)},j=s.useEditorStore(q=>q.frame),b=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.activeTabCardId),s.useEditorStore(q=>q.actions.getAvailableFields);const{addCard:C,removeCard:R,updateCard:E,setActiveCard:S,updateFilters:N}=s.useEditorActions(),{columns:k=[],isLoading:w,error:L}=s.useColumns(),D=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=b,{getFieldsForContainer:M,setFieldsForContainer:I}=Xs(O),{activeField:y,handleDragStart:T,handleDragEnd:B}=zi({activeCardId:j.activeCardId,sourceFields:k,getFieldsForContainer:M,setFieldsForContainer:I}),z=(q,U)=>{U&&N(q,U)},V=q=>{var U;E(q,{config:{...(U=j.cards.find(G=>G.id===q))==null?void 0:U.config,filters:void 0}})},P=k,X=q=>{if(!q)return 0;let U=q.conditions.length;return q.groups.forEach(G=>{U+=X(G)}),U},K=X(((_=O==null?void 0:O.config)==null?void 0:_.filters)||null);return e.jsxs(s.DndContext,{sensors:D,collisionDetection:s.closestCenter,onDragStart:T,onDragEnd:B,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(ui,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(bi,{selectedChart:h,onChartChange:v,groupByFields:M("groupBy"),pivotByFields:M("pivotBy"),metricsFields:M("metrics"),sortByFields:M("sortBy")}),e.jsx(qi,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:f,onClear:p,onAdvancedToggle:g,onFiltersClick:x,filterCount:K,activeCard:O,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:k,columnsLoading:w,columnsError:L,getFieldsForContainer:M,cards:j.cards,activeCardId:j.activeCardId,addCard:C,setActiveCard:S})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),O&&e.jsx(Bi,{cardId:O.id,filters:(($=O.config)==null?void 0:$.filters)||null,onFiltersChange:z,onClearFilters:V,availableFields:P,isOpen:o,onOpenChange:l}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Yi,{activeField:y||null})})]})}function Qi({authToken:t,onSave:a,onClose:n}){const r=A.useRef(null),o=s.useEditorStore(b=>b.showAIDialog),l=s.useEditorStore(b=>b.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:f,handleDragCancel:p,sensors:g}=Or();A.useEffect(()=>{a&&d(a),n&&u(n)},[a,d,n,u]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var b,C;o?((b=r.current)==null||b.resize(40),i(!0)):(i(!1),(C=r.current)==null||C.resize(0))},[o,i]);function x(b){b<1?i(!1):o||i(!0)}function v(){return e.jsxs(e.Fragment,{children:[e.jsx(tn,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Jo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(jt,{})})]})]})}function j(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Hi,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(jt,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:l?e.jsx(s.DndContext,{sensors:g,onDragStart:f,onDragEnd:h,onDragOver:m,onDragCancel:p,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:v()})}):j()})}function Ki(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function o(c){t&&(r(t,c),a(!1))}function l(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Qi,{onSave:o,onClose:l})})}function Wi(){const t=s.useEditorStore(l=>l.selectedDatabaseName),a=s.useEditorStore(l=>l.selectedTableName),n=s.useDashboardStore(l=>l.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:o}=jn();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(l=>{const c=n==null?void 0:n.find(i=>i.column===s.fmt(l.column_name)&&i.table===a&&i.database===t);return e.jsx("div",{onClick:()=>o(l),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vs,{column:l}),e.jsx("span",{children:l.column_name})]})},l.column_name)})})}function Ji(){s.useDashboardStore(a=>a.showFilters);const t=s.useDashboardStore(a=>a.actions.setShowFilters);return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:e.jsx(tn,{type:"filter",ColumnsComponent:()=>e.jsx(Wi,{})})})]})}function Xi(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Zi(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(Xi,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Ji,{})})]})}function el(){const t=s.useDashboardStore(o=>o.dashboard),a=s.useDashboardStore(o=>o.actions.setDashboard),n=s.useDashboardStore(o=>o.showDashboardJSON),r=s.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:o=>{if(o)try{JSON.parse(o),a(JSON.parse(o))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function sl({showControls:t=!1,showFooter:a=!0,...n}){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsxs(s.UXProvider,{children:[e.jsx(el,{}),e.jsxs("main",{className:"relative flex h-full flex-col",children:[t&&e.jsx(Ir,{}),e.jsxs(s.DashboardPanel,{...n,children:[e.jsx(Ki,{}),e.jsx(Zi,{})]})]})]})]})})}exports.DashboardPlus=sl;exports.ResourceManagementPanel=en;exports.ScheduleDashboard=Bt;exports.SelectComponent=ze;exports.cleanCard=Rt;exports.downloadPdf=Ft;exports.getDashbaordStateWithoutData=Bs;